
--BEFORE CODE 20.06.2012
--Таблица report_kbk_hist
IF not exists(select * from sysobjects where id = object_id('[dbo].[REPORT_KBK_HIST]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[REPORT_KBK_HIST] (
	[LINK_UP] int NOT NULL ,
	[DATE] datetime NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[LONG_NAME] varchar(8000) NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_REPORT_KBK_HIST]'))
ALTER TABLE [dbo].[REPORT_KBK_HIST] 
ADD CONSTRAINT [PK_REPORT_KBK_HIST] PRIMARY KEY CLUSTERED ([LINK_UP], [DATE])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_REPORT_KBK_HIST_REPORT_KBK_HIST]'))
ALTER TABLE [dbo].[REPORT_KBK_HIST] 
ADD CONSTRAINT [FK_REPORT_KBK_HIST_REPORT_KBK_HIST] FOREIGN KEY ([LINK_UP]) REFERENCES [dbo].[REPORT_KBK] ([link])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_REPORT_KBK_HIST_NAME]'))
ALTER TABLE [dbo].[REPORT_KBK_HIST] 
ADD CONSTRAINT [DF_REPORT_KBK_HIST_NAME] DEFAULT ('') FOR [NAME]
GO

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

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Таблица report_kbk_cashe
IF not exists(select * from sysobjects where id = object_id('[dbo].[REPORT_KBK_CASHE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[REPORT_KBK_CASHE] (
	[LINK_UP] int NOT NULL ,
	[BEGIN_DATE] datetime NOT NULL ,
	[END_DATE] datetime NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[LONG_NAME] varchar(8000) NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_REPORT_KBK_CASHE')
CREATE INDEX [IX_REPORT_KBK_CASHE] ON [dbo].[REPORT_KBK_CASHE] ([LINK_UP]) ON [INDEX]
GO
--Констрэйнты
--Триггеры

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

GO

--Измение колонки table_from таблицы report_spr_data
ALTER TABLE [dbo].[REPORT_SPR_DATA] ALTER COLUMN [Table_From] varchar(254) NOT NULL 
GO

--Измение колонки filter таблицы report_spr_data
ALTER TABLE [dbo].[REPORT_SPR_DATA] ALTER COLUMN [Filter] varchar(254) NULL 
GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW [dbo].RO_KBK_HIST_VIEW
AS 

SELECT K.[link],
       K.[Code],
       K.[Link_self],
       K.[Code_Form],
       K.[Childrens],
       KH.Name,
       K.[ImageIndex],
       K.[Code_str],
       K.[property],
       K.[add_info],
       K.[orders],
       KH.[Long_Name],       
       KH.[begin_date], 
       KH.[end_date]
       
FROM dbo.REPORT_KBK K
      JOIN dbo.report_kbk_cashe KH ON KH.[LINK_UP] = K.[link]

GO


GRANT SELECT ON dbo.[RO_KBK_HIST_VIEW] TO PUBLIC

GO


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


GO
--Таблица TYPE_OPER_NDS
IF not exists(select * from sysobjects where id = object_id('[dbo].[TYPE_OPER_NDS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[TYPE_OPER_NDS] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[CODE] varchar(2) NOT NULL ,
	[SHORT_NAME] varchar(254) NOT NULL ,
	[FULL_NAME] varchar(2000) NOT NULL ,
	[ISUSED] tinyint NOT NULL )
GO

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_TYPE_OPER_NDS_CODE]'))
ALTER TABLE [dbo].[TYPE_OPER_NDS] 
ADD CONSTRAINT [DF_TYPE_OPER_NDS_CODE] DEFAULT ('') FOR [CODE]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_TYPE_OPER_NDS_SHORT_NAME]'))
ALTER TABLE [dbo].[TYPE_OPER_NDS] 
ADD CONSTRAINT [DF_TYPE_OPER_NDS_SHORT_NAME] DEFAULT ('') FOR [SHORT_NAME]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_TYPE_OPER_NDS_NAME]'))
ALTER TABLE [dbo].[TYPE_OPER_NDS] 
ADD CONSTRAINT [DF_TYPE_OPER_NDS_NAME] DEFAULT ('') FOR [FULL_NAME]
GO

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


GO
--- !!!Справочники для налоговых деклараций!!! ---
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CATALOG_SPR_TAX', 'Бухгалтерия: Справочники для налоговых деклараций', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SMETA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CONTAINER_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CATALOG_SPR_TAX', NAME = 'Бухгалтерия: Справочники для налоговых деклараций', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SMETA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CONTAINER_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='CATALOG_SPR_TAX'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_TAX_PERIOD', 'Налоговый период', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_TAX_PERIOD', NAME = 'Налоговый период', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_TAX_PERIOD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_REORG_DEP', 'Коды форм реорганизации (ликвидации)', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_REORG_DEP', NAME = 'Коды форм реорганизации (ликвидации)', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_REORG_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_PLACE_ND_IMU', 'Коды представления НД по налогу на имущество', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_PLACE_ND_IMU', NAME = 'Коды представления НД по налогу на имущество', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_SPR_TAX'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_PLACE_ND_IMU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TAX_PERIOD_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TAX_PERIOD_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TAX_PERIOD_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TAX_PERIOD_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TAX_PERIOD_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TAX_PERIOD_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TAX_PERIOD_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TAX_PERIOD_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TAX_PERIOD_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TAX_PERIOD_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TAX_PERIOD_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TAX_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TAX_PERIOD_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_REORG_DEP_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_REORG_DEP_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_REORG_DEP_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_REORG_DEP_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_REORG_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_REORG_DEP_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_REORG_DEP_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_REORG_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_REORG_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_REORG_DEP_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_REORG_DEP_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_REORG_DEP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_REORG_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_PLACE_ND_IMU_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_PLACE_ND_IMU_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_PLACE_ND_IMU_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_PLACE_ND_IMU_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_PLACE_ND_IMU_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_PLACE_ND_IMU_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_PLACE_ND_IMU_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_PLACE_ND_IMU_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_PLACE_ND_IMU_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_PLACE_ND_IMU_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_PLACE_ND_IMU_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_PLACE_ND_IMU'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_PLACE_ND_IMU_NAME'
GO
EXEC X_SET_PROP 'CATALOG_SPR_TAX', 'NAME', 'Бухгалтерия: Справочники для налоговых деклараций'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'TITLE', 'Налоговый период'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'INIT_OBJECT_METHOD', 'X_SPISOK ("DICTIONARY_TAX_PERIOD")'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_TAX_PERIOD", "XK_DELETE_DICTION_REC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DICTIONARY_TAX_PERIOD'', m.cAlias," CODE, NAME","DICTIONARY_TAX_PERIOD")'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("DICTIONARY_TAX_PERIOD")'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("DICTIONARY_TAX_PERIOD")'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DICTIONARY_TAX_PERIOD', 'HISTORY_DOC_FIELD_NUMBER', 'NULL'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'TITLE', 'Коды форм реорганизации (ликвидации)'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'INIT_OBJECT_METHOD', 'X_SPISOK ("DICTIONARY_REORG_DEP")'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_REORG_DEP", "XK_DELETE_DICTION_REC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DICTIONARY_REORG_DEP'', m.cAlias," CODE, NAME","DICTIONARY_REORG_DEP")'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("DICTIONARY_REORG_DEP")'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("DICTIONARY_REORG_DEP")'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DICTIONARY_REORG_DEP', 'HISTORY_DOC_FIELD_NUMBER', 'NULL'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'TITLE', 'Коды представления НД по налогу на имущество'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'INIT_OBJECT_METHOD', 'X_SPISOK ("DICTIONARY_PLACE_ND_IMU")'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_PLACE_ND_IMU", "XK_DELETE_DICTION_REC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DICTIONARY_PLACE_ND_IMU'', m.cAlias," CODE, NAME","DICTIONARY_PLACE_ND_IMU")'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("DICTIONARY_PLACE_ND_IMU")'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("DICTIONARY_PLACE_ND_IMU")'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DICTIONARY_PLACE_ND_IMU', 'HISTORY_DOC_FIELD_NUMBER', 'NULL'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_MARKER', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'TYPE_FIELD_DICT', 'CHAR(2)'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'TYPE_FIELD_DICT', 'CHAR(254)'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'DIC_TAX_PERIOD_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_MARKER', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'TYPE_FIELD_DICT', 'CHAR(1)'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'TYPE_FIELD_DICT', 'CHAR(254)'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'DIC_REORG_DEP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_MARKER', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'TYPE_FIELD_DICT', 'CHAR(254)'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'DIC_PLACE_ND_IMU_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO




GO
--Таблица G_PROV_INVOICE
IF not exists(select * from sysobjects where id = object_id('[dbo].[G_PROV_INVOICE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[G_PROV_INVOICE] (
	[DOC_LINK] int NOT NULL ,
	[SELLER] int NULL ,
	[BUYER] int NULL ,
	[SHIPPER] int NULL ,
	[RECEIVER] int NULL ,
	[PRODUCER] int NULL ,
	[PAY_NUM] varchar(30) NOT NULL ,
	[PAY_DATE] datetime NULL ,
	[OSNOV] int NULL ,
	[TAX_RATE] numeric(5, 2) NOT NULL ,
	[INBOOK] tinyint NOT NULL ,
	[SEL_SHIP] tinyint NOT NULL ,
	[BUY_RECIVE] tinyint NOT NULL ,
	[COR_NUM] varchar(30) NOT NULL ,
	[COR_DATE] datetime NULL ,
	[TAX_SUM] numeric(28, 4) NOT NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_G_PROV_INVOICE]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [PK_G_PROV_INVOICE] PRIMARY KEY CLUSTERED ([DOC_LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_G_PROV]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_G_PROV] FOREIGN KEY ([DOC_LINK]) REFERENCES [dbo].[G_PROV] ([LINK])
 ON DELETE CASCADE
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_DEPARTMENTS]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_DEPARTMENTS] FOREIGN KEY ([SELLER]) REFERENCES [dbo].[DEPARTMENTS] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_DEPARTMENTS1]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_DEPARTMENTS1] FOREIGN KEY ([BUYER]) REFERENCES [dbo].[DEPARTMENTS] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_DEPARTMENTS2]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_DEPARTMENTS2] FOREIGN KEY ([RECEIVER]) REFERENCES [dbo].[DEPARTMENTS] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_DEPARTMENTS3]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_DEPARTMENTS3] FOREIGN KEY ([SHIPPER]) REFERENCES [dbo].[DEPARTMENTS] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_DEPARTMENTS4]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_DEPARTMENTS4] FOREIGN KEY ([PRODUCER]) REFERENCES [dbo].[DEPARTMENTS] ([LINK])
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_G_PROV_INVOICE_PAY_NUM]'))
ALTER TABLE [dbo].[G_PROV_INVOICE] 
ADD CONSTRAINT [DF_G_PROV_INVOICE_PAY_NUM] DEFAULT ('') FOR [PAY_NUM]
GO

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

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

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

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

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


GO
--Таблица G_PROV_INVOICE_COR
IF not exists(select * from sysobjects where id = object_id('[dbo].[G_PROV_INVOICE_COR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[G_PROV_INVOICE_COR] (
	[DOC_LINK] int NOT NULL ,
	[OSNOV] int NULL ,
	[COR_NUM] varchar(30) NOT NULL ,
	[COR_DATE] datetime NULL ,
	[INBOOK] tinyint NOT NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_G_PROV_INVOICE_COR]'))
ALTER TABLE [dbo].[G_PROV_INVOICE_COR] 
ADD CONSTRAINT [PK_G_PROV_INVOICE_COR] PRIMARY KEY CLUSTERED ([DOC_LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_COR_G_PROV]'))
ALTER TABLE [dbo].[G_PROV_INVOICE_COR] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_COR_G_PROV] FOREIGN KEY ([DOC_LINK]) REFERENCES [dbo].[G_PROV] ([LINK])
 ON DELETE CASCADE
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_G_PROV_INVOICE_COR_OSNOV]'))
ALTER TABLE [dbo].[G_PROV_INVOICE_COR] 
ADD CONSTRAINT [FK_G_PROV_INVOICE_COR_OSNOV] FOREIGN KEY ([OSNOV]) REFERENCES [dbo].[OSNOV] ([LINK])
GO

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

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


GO
--Таблица KL_COUNTRY
IF not exists(select * from sysobjects where id = object_id('[dbo].[KL_COUNTRY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[KL_COUNTRY] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[CODE1] varchar(5) NOT NULL ,
	[CODE2] varchar(5) NULL ,
	[CODE3] varchar(5) NULL ,
	[NAME] varchar(254) NOT NULL ,
	[FULL_NAME] varchar(254) NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_KL_COUNTRY]'))
ALTER TABLE [dbo].[KL_COUNTRY] 
ADD CONSTRAINT [PK_KL_COUNTRY] PRIMARY KEY CLUSTERED ([LINK])
GO
--Триггеры


GO
--Таблица OUT_TABLE_INVOICE_COR
IF not exists(select * from sysobjects where id = object_id('[dbo].[OUT_TABLE_INVOICE_COR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[OUT_TABLE_INVOICE_COR] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[DOC_LINK] int NOT NULL ,
	[LINK_UP] int NOT NULL ,
	[QTY_AFTER] numeric(19, 4) NOT NULL ,
	[PRICE_AFTER] numeric(19, 4) NOT NULL ,
	[SUM_AFTER] numeric(19, 4) NOT NULL ,
	[AKCIZ_AFTER] numeric(19, 4) NOT NULL ,
	[STAVKA_NDS_AFTER] numeric(5, 2) NOT NULL ,
	[NO_NDS_AFTER] tinyint NOT NULL ,
	[SUM_NDS_AFTER] numeric(19, 4) NOT NULL ,
	[SUM_ALL_AFTER] numeric(19, 4) NOT NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_OUT_TABLE_COR_INVOICE')
CREATE UNIQUE INDEX [IX_OUT_TABLE_COR_INVOICE] ON [dbo].[OUT_TABLE_INVOICE_COR] ([DOC_LINK], [LINK_UP]) ON [INDEX]
GO
--Констрэйнты

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

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

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

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

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

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

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

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

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

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

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


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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_OUT_TABLE_INVOICE_COR_TYPE_OPER_NDS]'))
ALTER TABLE [dbo].[OUT_TABLE_INVOICE_COR] 
ADD CONSTRAINT [FK_OUT_TABLE_INVOICE_COR_TYPE_OPER_NDS] FOREIGN KEY ([TYPE_NDS_AFTER]) REFERENCES [dbo].[TYPE_OPER_NDS] ([LINK])
GO


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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_OUT_TABLE_MZ_SUMMA_TYPE_OPER_NDS]'))
ALTER TABLE [dbo].[OUT_TABLE_MZ_SUMMA] 
ADD CONSTRAINT [FK_OUT_TABLE_MZ_SUMMA_TYPE_OPER_NDS] FOREIGN KEY ([TYPE_NDS]) REFERENCES [dbo].[TYPE_OPER_NDS] ([LINK])
GO



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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_OUT_TABLE_MZ_SUMMA_KL_COUNTRY]'))
ALTER TABLE [dbo].[OUT_TABLE_MZ_SUMMA] 
ADD CONSTRAINT [FK_OUT_TABLE_MZ_SUMMA_KL_COUNTRY] FOREIGN KEY ([COUNTRY_LINK]) REFERENCES [dbo].[KL_COUNTRY] ([LINK])
GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей С КОДОМ R_SPR_CSR_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, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЦСР_2011'' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form =''ЦСР_2011_USER'')')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЦСР_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_2011', 'Справочник целевых статей', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_2011]

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 = 'ЦСР_2011' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form ='ЦСР_2011_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 = 'ЦСР_2011_USER' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2011', 'Справочник целевых статей', 4, (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_2011', NAME = 'Справочник целевых статей', ORDERS = '4', 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_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011', 'TITLE', 'Справочник целевых статей'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011', 'SERVER_TABLE_NAME', 'R_SPR_CSR_2011'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_2011'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO

------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 = ''ЦСР_2011_USER''')
declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2011_1'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2011_1', 'Справочник региональных целевых статей (только для организаций)', '#Cols_tmp', '#Data_tmp', 1

GO


------------------- ВЬЮХА ------------------------

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

GO
/*******************************************************************************
	© Кейсистемс (Keysystems), 25.01.2012
	справочник Справочник региональных целевых статей (только для организаций) (сгенерировано Редактором справочников)
*******************************************************************************/
CREATE     VIEW dbo.[R_SPR_CSR_USER_2011_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 = 'ЦСР_2011_USER' GROUP BY K.Code,O.Link_Org,O.Link_Budg,begin_date,end_date

GO

GRANT SELECT ON dbo.[R_SPR_CSR_USER_2011_1] TO PUBLIC

GO

------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011_1')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011_1'
GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1', 'Справочник региональных целевых статей (только для организаций)', 60, (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_2011_1', NAME = 'Справочник региональных целевых статей (только для организаций)', ORDERS = '60', 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_2011_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_1_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_1_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_1_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_1_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_1_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_1_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_1_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_1_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_1_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_1_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_1_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1', 'TITLE', 'Справочник региональных целевых статей (только для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2011_1'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2011_1'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2011_1'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2011_1'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_1_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_1', 'Свод-КС - получатель', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_1', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_1', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей (общий для всех организаций) С КОДОМ R_SPR_CSR_USER_2011_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_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2011_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2011_2', 'Справочник целевых статей (общий для всех организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (общий для всех организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_USER_2011_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_2011 GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_USER_2011_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2', 'Справочник целевых статей (общий для всех организаций)', 61, (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_2011_2', NAME = 'Справочник целевых статей (общий для всех организаций)', ORDERS = '61', 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_2011_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_2_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_2_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_2_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_2_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_2_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_2_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_2_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_2_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2', 'TITLE', 'Справочник целевых статей (общий для всех организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2011_2'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2011_2'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2011_2'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2011_2'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_2_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник источников (17 знаков) С КОДОМ R_SPR_IST_127_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, 'left(code,3) + SUBSTRING(Code,7,17)', 'Код', '', 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, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 4, 'isnull(Long_name,'''')', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_Ist', 5, 'Code', 'Код источника', '', 7,17)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form=''ИСТОЧНИКИ_2011'' and Code NOT IN (select KK.code from dbo.[rk] KK where KK.Code_form=''ИСТОЧНИКИ_2011_USER'' and(isnull(kk.[ed],''30000101'')>isnull([rk].[bd],''19000101'')and isnull([rk].[ed],''30000101'')>isnull(kk.[bd],''19000101''))) and code<''823''')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ИСТОЧНИКИ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_127_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_127_2011', 'Справочник источников (17 знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник источников (17 знаков) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_IST_127_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(code,3) + SUBSTRING(Code,7,17) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,17) as [CODE_IST],max(Name) as [NAME],max(isnull(Long_name,'')) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form='ИСТОЧНИКИ_2011' and Code NOT IN (select KK.code from dbo.report_kbk KK where KK.Code_form='ИСТОЧНИКИ_2011_USER' and(isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101')and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) and code<'823' GROUP BY left(code,3) + SUBSTRING(Code,7,17),Code_str,SUBSTRING(Code,7,17),begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(code,3) + SUBSTRING(Code,7,17) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,17) as [CODE_IST],max(Name) as [NAME],max(isnull(Long_name,'')) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ИСТОЧНИКИ_2011_USER' GROUP BY left(code,3) + SUBSTRING(Code,7,17),Code_str,SUBSTRING(Code,7,17),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_127_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_127_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_127_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011', 'Справочник источников (17 знаков)', 244, (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_IST_127_2011', NAME = 'Справочник источников (17 знаков)', ORDERS = '244', 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_IST_127_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_Long_name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_Long_name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_Long_name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011_Code_Ist')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127_2011_Code_Ist', 'Код источника', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127_2011_Code_Ist', NAME = 'Код источника', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127_2011_Code_Ist'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011', 'TITLE', 'Справочник источников (17 знаков)'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_127_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_127_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_127_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_127_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_Ist', 'TITLE', 'Код источника'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_Ist', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_Ist', 'CONTROLSOURCE', 'm.cAlias + ".Code_Ist"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127_2011_Code_Ist', 'FIELD_DATA', 'Code_Ist'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник целевых статей (для организаций) С КОДОМ R_SPR_CSR_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 #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_USER_2011_1', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_USER_2011_2', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_USER_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_USER_2011', 'Справочник целевых статей (для организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник целевых статей (для организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_CSR_USER_2011]

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_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],max(name) as [NAME],begin_date,end_date FROM R_SPR_CSR_USER_2011_2 GROUP BY Code,Org,Budg,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_CSR_USER_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_USER_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011', 'Справочник целевых статей (для организаций)', 59, (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_2011', NAME = 'Справочник целевых статей (для организаций)', ORDERS = '59', 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_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_USER_2011_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_USER_2011_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_USER_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_USER_2011_Budg'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011', 'TITLE', 'Справочник целевых статей (для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_USER_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_USER_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011', 'SERVER_TABLE_NAME', 'R_SPR_CSR_USER_2011'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_USER_2011'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_USER_2011_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_USER_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник видов расходов С КОДОМ R_SPR_VR_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, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ВР_2011'' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form=''ВР_2011_USER'' and (isnull(kk.[ed],''30000101'')>isnull(report_kbk.[bd],''19000101'') and isnull(report_kbk.[ed],''30000101'')>isnull(kk.[bd],''19000101'')))')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ВР_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_VR_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_VR_2011', 'Справочник видов расходов', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник видов расходов (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_VR_2011]

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 = 'ВР_2011' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form='ВР_2011_USER' and (isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101') and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) 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 = 'ВР_2011_USER' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_VR_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_2011', 'Справочник видов расходов', 234, (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_2011', NAME = 'Справочник видов расходов', ORDERS = '234', 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_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011', 'TITLE', 'Справочник видов расходов'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_VR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011', 'SERVER_TABLE_NAME', 'R_SPR_VR_2011'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_VR_2011'''
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_VR_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник подразделов С КОДОМ R_SPR_RZPR_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', 2, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_str', 3, 'Code_str', 'КОД СТРОКИ', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('PROPERTY', 4, 'PROPERTY', 'Итог', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('RZPR', 5, 'Code', 'Раздел', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''РЗПР_2011''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_RZPR_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_RZPR_2011', 'Справочник подразделов', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO



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



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



	справочник Справочник подразделов (сгенерировано Редактором справочников)



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



CREATE     VIEW dbo.[R_SPR_RZPR_2011]



AS



SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],PROPERTY as [PROPERTY],Code as [RZPR],max(isnull(Long_name, name)) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'РЗПР_2011' GROUP BY Code,Code_str,PROPERTY,Code,begin_date,end_date




GO


GRANT SELECT ON dbo.[R_SPR_RZPR_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RZPR_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RZPR_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011', 'Справочник подразделов', 45, (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_RZPR_2011', NAME = 'Справочник подразделов', ORDERS = '45', 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_RZPR_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_Code_str', 'КОД СТРОКИ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_PROPERTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_PROPERTY', 'Итог', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_PROPERTY', NAME = 'Итог', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_PROPERTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011_RZPR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RZPR_2011_RZPR', 'Раздел', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RZPR_2011_RZPR', NAME = 'Раздел', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RZPR_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RZPR_2011_RZPR'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011', 'SERVER_TABLE_NAME', 'R_SPR_RZPR_2011'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_RZPR_2011'''
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_RZPR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_RZPR_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011', 'TITLE', 'Справочник подразделов'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_PROPERTY', 'TITLE', 'Итог'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_PROPERTY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_PROPERTY', 'CONTROLSOURCE', 'm.cAlias + ".PROPERTY"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_PROPERTY', 'FIELD_DATA', 'PROPERTY'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_RZPR', 'TITLE', 'Раздел'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_RZPR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_RZPR', 'CONTROLSOURCE', 'm.cAlias + ".RZPR"'
GO
EXEC X_SET_PROP 'R_SPR_RZPR_2011_RZPR', 'FIELD_DATA', 'RZPR'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_RZPR_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RZPR_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RZPR_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник региональных ВР (только для организаций) С КОДОМ R_SPR_VR_USER_2011_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 = ''ВР_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_VR_USER_2011_1'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_VR_USER_2011_1', 'Справочник региональных ВР (только для организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник региональных ВР (только для организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_VR_USER_2011_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 = 'ВР_2011_USER' GROUP BY K.Code,O.Link_Org,O.Link_Budg,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_VR_USER_2011_1] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011_1')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011_1'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1', 'Справочник региональных ВР (только для организаций)', 201, (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_1', NAME = 'Справочник региональных ВР (только для организаций)', ORDERS = '201', 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_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_1_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_1_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_1_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_1_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_1_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_1_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_1_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_1_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_1_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_1_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_1_Budg'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1', 'TITLE', 'Справочник региональных ВР (только для организаций)'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_VR_USER_2011_1'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_USER_2011_1'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1', 'SERVER_TABLE_NAME', 'R_SPR_VR_USER_2011_1'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_VR_USER_2011_1'''
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_1_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_1', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_1', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_1', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник источников (без досчет 7000105) С КОДОМ R_SPR_IST_127M03_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 ('Code_str', 2, 'Code_str', 'КОД СТРОКИ', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_Ist', 3, 'Code', 'Код источника', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('NAME', 4, 'NAME', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LONG_NAME', 5, 'LONG_NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_IST_127_2011', 'CODE <> ''70001050000000000000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_127M03_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_127M03_2011', 'Справочник источников (без досчет 7000105)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник источников (без досчет 7000105) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_IST_127M03_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,CODE as [CODE],Code_str as [CODE_STR],Code as [CODE_IST],max(NAME) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM R_SPR_IST_127_2011 WHERE CODE <> '70001050000000000000' GROUP BY CODE,Code_str,Code,begin_date,end_date

	UNION

	select -1 as Link, isnull(((select link from dbo.R_SPR_IST_127_2011 where code = '70001000000000000000')),0) as Link_Self,'70001050000000000000' as CODE,'700' as CODE_STR,'70001050000000000000' as CODE_IST,'Изменение остатков средств на счетах по учету средств бюджета' as NAME,'Изменение остатков средств на счетах по учету средств бюджета' as LONG_NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_127M03_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_127M03_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_127M03_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011', 'Справочник источников (без досчет 7000105)', 158, (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_IST_127M03_2011', NAME = 'Справочник источников (без досчет 7000105)', ORDERS = '158', 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_IST_127M03_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_Code_Ist')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_Code_Ist', 'Код источника', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_Code_Ist', NAME = 'Код источника', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_Code_Ist'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_NAME', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_NAME', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011_LONG_NAM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_127M03_2011_LONG_NAM', 'Наименование', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_127M03_2011_LONG_NAM', NAME = 'Наименование', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_127M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_127M03_2011_LONG_NAM'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011', 'TITLE', 'Справочник источников (без досчет 7000105)'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_127M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_127M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_127M03_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_127M03_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_Ist', 'TITLE', 'Код источника'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_Ist', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_Ist', 'CONTROLSOURCE', 'm.cAlias + ".Code_Ist"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_Code_Ist', 'FIELD_DATA', 'Code_Ist'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_LONG_NAM', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_LONG_NAM', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_LONG_NAM', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_127M03_2011_LONG_NAM', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127M03_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127M03_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_127M03_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ЭКР С КОДОМ R_SPR_ST_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 ('Code_str', 2, '''200''', 'КОД СТРОКИ', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ЭКР_2011'' and substring(code,1,1) in (''2'',''3'',''5'',''6'',''0'')')

declare @link int
select @link = link from report_spr where code = 'R_SPR_ST_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ST_2011', 'Справочник ЭКР', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник ЭКР (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_ST_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],'200' 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 = 'ЭКР_2011' and substring(code,1,1) in ('2','3','5','6','0') GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_ST_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ST_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ST_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_2011', 'Справочник ЭКР', 11, (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_ST_2011', NAME = 'Справочник ЭКР', ORDERS = '11', 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_ST_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011', 'TITLE', 'Справочник ЭКР'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ST_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ST_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011', 'SERVER_TABLE_NAME', 'R_SPR_ST_2011'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ST_2011'''
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ST_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Автозаполняемый справочник для формы 0503128 С КОДОМ R_SPR_AUTO_128_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 ('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_AUTO_128_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_AUTO_128_2011', 'Автозаполняемый справочник для формы 0503128', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Автозаполняемый справочник для формы 0503128 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_AUTO_128_2011]

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_AUTO_128_2011' GROUP BY Code,Code_str, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_AUTO_128_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_128_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_128_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_128_2011', 'Автозаполняемый справочник для формы 0503128', 39, (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_128_2011', NAME = 'Автозаполняемый справочник для формы 0503128', ORDERS = '39', 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_128_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_128_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_128_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_128_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_128_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_128_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_128_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_128_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_128_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_128_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_128_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_128_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_128_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_128_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011', 'TITLE', 'Автозаполняемый справочник для формы 0503128'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_AUTO_128_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_AUTO_128_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011', 'SERVER_TABLE_NAME', 'R_SPR_AUTO_128_2011'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_AUTO_128_2011'''
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_128_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_128_2011', 'public', 4,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_128_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_128_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_128_2011', 'Главный бухгалтер', 4,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_128_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ВР (общий для всех организаций) С КОДОМ R_SPR_VR_USER_2011_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_VR_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_VR_USER_2011_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_VR_USER_2011_2', 'Справочник ВР (общий для всех организаций)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник ВР (общий для всех организаций) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_VR_USER_2011_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_VR_2011 GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_VR_USER_2011_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_USER_2011_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2', 'Справочник ВР (общий для всех организаций)', 202, (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_2', NAME = 'Справочник ВР (общий для всех организаций)', ORDERS = '202', 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_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_2_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_2_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_2_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2_Org')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2_Org', '', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_2_Org', NAME = '', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_2_Org'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2_Budg')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_USER_2011_2_Budg', '', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_USER_2011_2_Budg', NAME = '', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_USER_2011_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_USER_2011_2_Budg'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2', 'TITLE', 'Справочник ВР (общий для всех организаций)'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_VR_USER_2011_2'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_USER_2011_2'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2', 'SERVER_TABLE_NAME', 'R_SPR_VR_USER_2011_2'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_VR_USER_2011_2'''
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Org', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Org', 'CONTROLSOURCE', 'm.cAlias + ".Org"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Org', 'FIELD_DATA', 'Org'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Budg', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Budg', 'CONTROLSOURCE', 'm.cAlias + ".Budg"'
GO
EXEC X_SET_PROP 'R_SPR_VR_USER_2011_2_Budg', 'FIELD_DATA', 'Budg'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_USER_2011_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник источников (17 знаков) С КОДОМ R_SPR_IST_17_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, 'left(code,3) + SUBSTRING(Code,7,17)', 'Код', '', 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, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 4, 'Long_name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_Ist', 5, 'Code', 'Код источника', '', 7,17)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ИСТОЧНИКИ_2011'' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form =''ИСТОЧНИКИ_2011_USER'') and code < ''800''')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ИСТОЧНИКИ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_17_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_17_2011', 'Справочник источников (17 знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник источников (17 знаков) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_IST_17_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(code,3) + SUBSTRING(Code,7,17) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,17) as [CODE_IST],max(Name) as [NAME],max(Long_name) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ИСТОЧНИКИ_2011' and Code not in (select KK.Code from dbo.report_kbk KK where KK.Code_form ='ИСТОЧНИКИ_2011_USER') and code < '800' GROUP BY left(code,3) + SUBSTRING(Code,7,17),Code_str,SUBSTRING(Code,7,17),begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(code,3) + SUBSTRING(Code,7,17) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,17) as [CODE_IST],max(Name) as [NAME],max(Long_name) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ИСТОЧНИКИ_2011_USER' GROUP BY left(code,3) + SUBSTRING(Code,7,17),Code_str,SUBSTRING(Code,7,17),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_17_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_17_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_17_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011', 'Справочник источников (17 знаков)', 20, (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_IST_17_2011', NAME = 'Справочник источников (17 знаков)', ORDERS = '20', 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_IST_17_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_Long_name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_Long_name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_Long_name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011_Code_Ist')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_17_2011_Code_Ist', 'Код источника', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_17_2011_Code_Ist', NAME = 'Код источника', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_17_2011_Code_Ist'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011', 'TITLE', 'Справочник источников (17 знаков)'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_17_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_17_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_17_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_17_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_Ist', 'TITLE', 'Код источника'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_Ist', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_Ist', 'CONTROLSOURCE', 'm.cAlias + ".Code_Ist"'
GO
EXEC X_SET_PROP 'R_SPR_IST_17_2011_Code_Ist', 'FIELD_DATA', 'Code_Ist'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_17_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_17_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_17_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
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 #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), 25.01.2012

	справочник Справочник ВР (для организаций) (сгенерировано Редактором справочников)

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

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],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],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', 'Справочник ВР (для организаций)', 203, (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 = '203', 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
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 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


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник доходов (17 знаков) С КОДОМ R_SPR_DOH_17_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', 'Код', '', 4,17)

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, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 4, 'isnull(Long_name,'''')', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form=''ДОХОДЫ_2011'' and NOT exists(select * from dbo.[rk] KK where KK.Code_form=''ДОХОДЫ_2011_USER'' AND KK.Code = [rk].Code and(isnull(kk.[ed],''30000101'')>isnull([rk].[bd],''19000101'') and isnull([rk].[ed],''30000101'')>isnull(kk.[bd],''19000101'')))')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DOH_17_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DOH_17_2011', 'Справочник доходов (17 знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник доходов (17 знаков) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_DOH_17_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,17) as [CODE],Code_str as [CODE_STR],max(Name) as [NAME],max(isnull(Long_name,'')) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form='ДОХОДЫ_2011' and NOT exists(select * from dbo.report_kbk KK where KK.Code_form='ДОХОДЫ_2011_USER' AND KK.Code = report_kbk.Code and(isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101') and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) GROUP BY SUBSTRING(Code,4,17),Code_str,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,17) as [CODE],Code_str as [CODE_STR],max(Name) as [NAME],max(isnull(Long_name,'')) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011_USER' GROUP BY SUBSTRING(Code,4,17),Code_str,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DOH_17_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_17_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_17_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011', 'Справочник доходов (17 знаков)', 240, (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_DOH_17_2011', NAME = 'Справочник доходов (17 знаков)', ORDERS = '240', 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_DOH_17_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_17_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_17_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_17_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_17_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_17_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_17_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_17_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_17_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_17_2011_Long_name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_17_2011_Long_name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_17_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_17_2011_Long_name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011', 'TITLE', 'Справочник доходов (17 знаков)'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DOH_17_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DOH_17_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011', 'SERVER_TABLE_NAME', 'R_SPR_DOH_17_2011'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DOH_17_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_17_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_17_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_17_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_17_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Автозаполняемый справочник для формы 0503117G - Расходы С КОДОМ R_SPR_RASH_117_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 ('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_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_RASH_117_2011', 'Автозаполняемый справочник для формы 0503117G - Расходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Автозаполняемый справочник для формы 0503117G - Расходы (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_RASH_117_2011]

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_2011' GROUP BY Code,Code_str, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_RASH_117_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_117_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_117_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2011', 'Автозаполняемый справочник для формы 0503117G - Расходы', 36, (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_2011', NAME = 'Автозаполняемый справочник для формы 0503117G - Расходы', ORDERS = '36', 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_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_117_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_117_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_117_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_117_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011', 'TITLE', 'Автозаполняемый справочник для формы 0503117G - Расходы'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_RASH_117_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_RASH_117_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011', 'SERVER_TABLE_NAME', 'R_SPR_RASH_117_2011'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_RASH_117_2011'''
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_117_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_117_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник видов финансового обеспечения (деятельности) С КОДОМ R_SPR_ATR_VID_773------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ATR_VID_773'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ATR_VID_773', 'Справочник видов финансового обеспечения (деятельности)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник видов финансового обеспечения (деятельности) (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_ATR_VID_773]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ATR_VID_773' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_ATR_VID_773] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ATR_VID_773')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ATR_VID_773'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ATR_VID_773', 'Справочник видов финансового обеспечения (деятельности)', 194, (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_ATR_VID_773', NAME = 'Справочник видов финансового обеспечения (деятельности)', ORDERS = '194', 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_ATR_VID_773'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ATR_VID_773_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ATR_VID_773_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ATR_VID_773_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ATR_VID_773_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ATR_VID_773_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ATR_VID_773_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ATR_VID_773_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ATR_VID_773_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ATR_VID_773'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ATR_VID_773_Name'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773', 'TITLE', 'Справочник видов финансового обеспечения (деятельности)'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ATR_VID_773'')'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ATR_VID_773'')'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773', 'SERVER_TABLE_NAME', 'R_SPR_ATR_VID_773'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ATR_VID_773'''
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ATR_VID_773_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ATR_VID_773', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ATR_VID_773', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ATR_VID_773', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ATR_VID_773',0,'Справочник видов финансового обеспечения (деятельности)','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_ATR_VID_773',@link_self,'Справочник видов финансового обеспечения (деятельности)','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'b',@link_self,'деятельность с целевыми средствами, включающая','R_SPR_ATR_VID_773',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'t',@link_self,'средства во временном распоряжении','R_SPR_ATR_VID_773',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'v',@link_self,'деятельность по оказанию услуг (работ) (приносящая доход деятельность)','R_SPR_ATR_VID_773',0,'',0,'','','19000101','19000101'
GO

GO


GO

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

GO




/*
c Кейсистемс (Keysystems), 2010

	создание вьюхи для справочника
*/
CREATE            proc 	dbo.RO_SPR_MAKE_VIEW
	 @varKSiLink int, -- линк сохранного справочника в REPORT_SPR
	@varKSiTypeSpr tinyint  = 1 -- 1 - наследуемый справочник, 0 - новый справочник
as
	declare @cRunStr varchar(8000), @codeSpr varchar(50), @nameSpr varchar(254), @cRunStr1 varchar(8000),@cRunStr2 varchar(8000), @cGroupBy varchar(8000), @Link_Self varchar(254),
      @cBeginDate VARCHAR(8000), @cBeginDateG VARCHAR(8000), @cEndDate VARCHAR(8000), @cEndDateG VARCHAR(8000)      
	create table #RunStr (st varchar(8000), orders int IDENTITY(1,1))
-- данные о справочнике
	select @codeSpr = rtrim(Code), @nameSpr = rtrim(name) from dbo.REPORT_SPR where link = @varKSiLink
-------------------------------------------------------------------------------------------------
-- создаем вьюху
	set @cRunStr = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @codeSpr + ']'') and OBJECTPROPERTY(id, N''IsView'') = 1)
drop view [dbo].[' + @codeSpr + ']'
	execute(@cRunStr)

set @cRunStr1 = '/*******************************************************************************
	© Кейсистемс (Keysystems), ' + convert(varchar(10), getdate(), 104) + '
	справочник ' + @nameSpr + ' (сгенерировано Редактором справочников)
*******************************************************************************/
CREATE     VIEW dbo.[' + @codeSpr + ']
AS
'
	insert #RunStr (st)
	values (@cRunStr1)

	-- колонки
	set @cRunStr = ''
	select @cRunStr = @cRunStr + case when Const = '' then 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end 
			else rtrim(Const) end + ' as [' + UPPER(rtrim(Code)) + '],'
	from report_spr_col 
	where Link_Spr = @varKSiLink and (CHARINDEX('Name', Source) = 0 or Const <> '')
	order by orders

	set @cGroupBy = ''
	select @cGroupBy = @cGroupBy + case when LEFT(Source,1) = '''' and CHARINDEX('+', Source) = 0 then '' else 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end + ',' end
	from report_spr_col 
	where Link_Spr = @varKSiLink and Const = '' and CHARINDEX('Name', Source) = 0
	order by orders
   
   IF @cGroupBy LIKE '%select%'
      SET @cGroupBy = 'code,'

	select @cRunStr = @cRunStr + 'max(' + 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end 
			+ ') as [' + UPPER(rtrim(Code)) + '],'
	from report_spr_col 
	where Link_Spr = @varKSiLink and CHARINDEX('Name', Source) > 0
	order by orders

	if @varKSiTypeSpr = 0 -- новый справочник
	begin
			set @cRunStr2 = 'SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,' + @cRunStr + ' begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = ''' + @CodeSpr + ''' GROUP BY ' + @cGroupBy + ' begin_date, end_date' 
			print @cRunStr1 + @cRunStr2
			execute(@cRunStr1 + @cRunStr2)
	end
	else begin
		declare @TableFrom varchar(1000), @Filter varchar(1000), @Value varchar(8000), @orders int, @cLink_Self varchar(1000)
		set @cLink_Self = ', max(Link_Self) as Link_Self'
		declare cur_Spr cursor local static for
			select rtrim(Table_From), rtrim(Filter) from report_SPR_DATA where link_Spr = @varKSiLink

		open cur_Spr

		fetch next from cur_Spr into @TableFrom, @Filter

		while @@fetch_status = 0
		BEGIN
			IF COL_LENGTH(@TableFrom, 'begin_date') is NULL AND @TableFrom NOT LIKE '%report_kbk%'
         begin
				set @cBeginDate = ',convert(datetime, ''19000101'', 112) as begin_date'
            SET @cBeginDateG = ''
         END 
			ELSE begin
				set @cBeginDate =  ',begin_date'
            SET @cBeginDateG = ',begin_date'
         END 

			IF COL_LENGTH(@TableFrom, 'end_date') is NULL AND @TableFrom NOT LIKE '%report_kbk%'
         begin
				set @cEndDate = ',convert(datetime, ''30000101'', 112) as end_date'
            SET @cEndDateG = ''
         END 
			ELSE begin
				set @cEndDate = ',end_date'
            SET @cEndDateG = ',end_date'
         END 

			IF COLUMNPROPERTY(object_id(@TableFrom), 'Link_Self', 'AllowsNull') is NULL
				set @cLink_Self = ', 0 as Link_Self'
			else
				set @cLink_Self = ', max(Link_Self) as Link_Self'

         SET @TableFrom = REPLACE(REPLACE(REPLACE(@TableFrom, 'REPORT_KBK',  '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK]'), '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] K', '[dbo].[RO_KBK_HIST_VIEW] K'), '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK]_', 'REPORT_KBK_')
         SET @Filter = REPLACE(REPLACE(REPLACE(@Filter, '[bd]', 'begin_date'), '[ed]', 'end_date'), '[rk]', 'report_kbk')
                  
			set @cRunStr1 = 'SELECT max(LINK) as Link' + @cLink_Self +  ',' + LEFT(@cRunStr, LEN(@cRunStr)-1)
         + @cBeginDate
         + @cEndDate         
         + ' FROM ' + @TableFrom  + case when @Filter = '' then '' else  ' WHERE ' + @Filter end 
         + case when @cGroupBy <> '' then ' GROUP BY ' + LEFT(@cGroupBy, LEN(@cGroupBy)-1) + @cBeginDateG + @cEndDateG else '' end

			insert #RunStr (st) values (@cRunStr1)
			insert #RunStr (st) values ('
	UNION
	')
			fetch next from cur_Spr into @TableFrom, @Filter
		end

		deallocate cur_Spr

		if @cGroupBy = ''
			update #RunStr set st = REPLACE(st, 'max(', '(')

		-- добавленные значения
		declare cur_Value cursor local static for
			select Value, orders, Link_Self from report_spr_Value where  link_Spr = @varKSiLink

		open cur_Value

		fetch next from cur_Value into @Value, @orders, @Link_Self

		while @@fetch_status = 0
		begin
         if @Link_Self <> ''
			   set @cRunStr1 = 'select -' + LTRIM(STR(@orders)) + ' as Link, isnull((' + @Link_Self + '),0) as Link_Self'
         else
            set @cRunStr1 = 'select -' + LTRIM(STR(@orders)) + ' as Link, 0 as Link_Self'

			select @cRunStr1 = @cRunStr1 + ',''' +  dbo.[RA_GETWORDNUM](@Value, orders, '#') + ''' as ' + UPPER(Code)
			from report_spr_col
			where Link_Spr =  @varKSiLink
			order by orders
         
         
			set @cRunStr1 = @cRunStr1 + ',convert(datetime, ''19000101'', 112) as begin_date'
         set @cRunStr1 = @cRunStr1 + ',convert(datetime, ''30000101'', 112) as end_date'

			insert #RunStr (st) values (@cRunStr1)
			insert #RunStr (st) values ('
	UNION
	')

			fetch next from cur_Value into @Value, @orders, @Link_Self
		end
		
		close cur_Value
		deallocate cur_Value

		delete #RunStr where orders = (select max(orders) from #RunStr)

		exec ssp_execresultset @varKScmd = 'select st from #RunStr order by orders'--, @varKSdebug = 1

		drop table #RunStr 
	end

	set @cRunStr = 'GRANT SELECT ON dbo.[' + @codeSpr + '] TO PUBLIC'
	execute (@cRunStr)


GO


GRANT EXECUTE ON dbo.[RO_SPR_MAKE_VIEW] TO PUBLIC

GO


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


DECLARE @link int 
   
DECLARE cur CURSOR 
LOCAL STATIC FOR
SELECT Link
FROM dbo.report_spr
WHERE IsSystem = 1

OPEN cur

FETCH NEXT FROM cur INTO @link

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @link)
         EXEC dbo.RO_SPR_MAKE_VIEW @Link, 1
   ELSE 
      EXEC dbo.RO_SPR_MAKE_VIEW @Link, 0
               
   FETCH NEXT FROM cur INTO @link
END    
close cur
GO
DECLARE @link int 
   
DECLARE cur CURSOR 
LOCAL STATIC FOR
SELECT Link
FROM dbo.report_spr
WHERE IsSystem = 1

OPEN cur

FETCH NEXT FROM cur INTO @link

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @link)
         EXEC dbo.RO_SPR_MAKE_VIEW @Link, 1
   ELSE 
      EXEC dbo.RO_SPR_MAKE_VIEW @Link, 0
               
   FETCH NEXT FROM cur INTO @link
END    
close cur
GO
DECLARE @link int 
   
DECLARE cur CURSOR 
LOCAL STATIC FOR
SELECT Link
FROM dbo.report_spr
WHERE IsSystem = 1

OPEN cur

FETCH NEXT FROM cur INTO @link

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @link)
         EXEC dbo.RO_SPR_MAKE_VIEW @Link, 1
   ELSE 
      EXEC dbo.RO_SPR_MAKE_VIEW @Link, 0
               
   FETCH NEXT FROM cur INTO @link
END    
close cur
GO
DECLARE @link int 
   
DECLARE cur CURSOR 
LOCAL STATIC FOR
SELECT Link
FROM dbo.report_spr
WHERE IsSystem = 1

OPEN cur

FETCH NEXT FROM cur INTO @link

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @link)
         EXEC dbo.RO_SPR_MAKE_VIEW @Link, 1
   ELSE 
      EXEC dbo.RO_SPR_MAKE_VIEW @Link, 0
               
   FETCH NEXT FROM cur INTO @link
END    
close cur
GO
DECLARE @link int 
   
DECLARE cur CURSOR 
LOCAL STATIC FOR
SELECT Link
FROM dbo.report_spr
WHERE IsSystem = 1

OPEN cur

FETCH NEXT FROM cur INTO @link

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @link)
         EXEC dbo.RO_SPR_MAKE_VIEW @Link, 1
   ELSE 
      EXEC dbo.RO_SPR_MAKE_VIEW @Link, 0
               
   FETCH NEXT FROM cur INTO @link
END    
close cur
GO


GO
IF COLUMNPROPERTY(object_id('[dbo].[PERS_PENSION]'), 'CHECK_SZV', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[PERS_PENSION] ADD [CHECK_SZV] tinyint NOT NULL  DEFAULT ((0))
GO
		
IF COLUMNPROPERTY(object_id('[dbo].[PERS_PENSION]'), 'WORK_PENS', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[PERS_PENSION] ADD [WORK_PENS] tinyint NOT NULL  DEFAULT ((0))
GO

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

update T
set [SOURCE] = S.LINK
from dbo.ZAYAVKA_KR_TABLE T
inner join dbo.FIN_SOURCE S on S.CODE = '2' and T.VYD_SR = 2 or S.CODE = '1' and T.VYD_SR <> 2
where T.[SOURCE] is null
GO
EXEC ('ALTER TABLE [dbo].[ZAYAVKA_KR_TABLE] ALTER COLUMN [SOURCE] int NOT NULL')
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_ZAYAVKA_KR_TABLE_FIN_SOURCE]'))
	ALTER TABLE [dbo].[ZAYAVKA_KR_TABLE] 
	ADD CONSTRAINT [FK_ZAYAVKA_KR_TABLE_FIN_SOURCE] FOREIGN KEY ([SOURCE]) REFERENCES [dbo].[FIN_SOURCE] ([LINK])
GO
IF COLUMNPROPERTY(object_id('[dbo].[RECEPTION_CASH_TABLE]'), 'VID_SR', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[RECEPTION_CASH_TABLE] ADD [VID_SR] int NOT NULL CONSTRAINT [DF_RECEPTION_CASH_TABLE_VID_SR] DEFAULT ((1))
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE', 'Таблица сумм', 37, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE', NAME = 'Таблица сумм', ORDERS = '37', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_VYD_SR_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'Вид финансового обеспечения', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', NAME = 'Вид финансового обеспечения', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_VYD_SR_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_VYD_SR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'Вид средств', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_VYD_SR', NAME = 'Вид средств', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_VYD_SR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'Код по БК плательщика', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', NAME = 'Код по БК плательщика', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'Код ЭКР плательщика', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', NAME = 'Код ЭКР плательщика', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_DT_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'Субсчет дебет', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_DT_ACC', NAME = 'Субсчет дебет', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_DT_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_DCL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'Код Доп.кл. плательщика', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', NAME = 'Код Доп.кл. плательщика', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_DCL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_KBK_CODE_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'Код по БК получателя', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', NAME = 'Код по БК получателя', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_KBK_CODE_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_EKR_CODE_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'Код ЭКР получателя', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', NAME = 'Код ЭКР получателя', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_EKR_CODE_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'Сумма', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_SUMMA', NAME = 'Сумма', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_TARGET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_TARGET', 'Назначение платежа', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_TARGET', NAME = 'Назначение платежа', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_TARGET'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_DCL_CODE_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'Код Доп.кл. получателя', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', NAME = 'Код Доп.кл. получателя', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_DCL_CODE_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_TABLE_TITLE', 'Примечание', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_TABLE_TITLE', NAME = 'Примечание', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_TABLE_TITLE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''BB_SAVE_ZAYAVKA_KR_TABLE'', m.cAlias, ''LINK_UP, FS_LINK, VID_SR,KBK_LINK, SGU_LINK, SQLNULL(DCL_LINK), SQLNULL(DT_ACC_LINK),SQLNULL(KBK_LINK_D), SQLNULL(SGU_LINK_D), SQLNULL(DCL_LINK_D),  SUMMA,TARGET,TITLE'', ''BB_ZAYAVKA_KR_TABLE'')'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE', 'CLOSE_CODE', ''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BB_ZAYAVKA_KR_TABLE WHERE LINK_UP = '' + STR(m.nLink), m.cAlias) > 0'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE', 'SERVER_TABLE_NAME', 'ZAYAVKA_KR_TABLE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_CHECKED', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'TITLE', 'Вид финансового обеспечения'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'CONTROLSOURCE', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR_2', 'SHORT_CODE_OBJ', 'FS_NAME'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'TITLE', 'Вид средств'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'CONTROLSOURCE', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'SHORT_CODE_OBJ', 'VYD_SNAME'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_VYD_SR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BI_DICTION_KBK", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "KBK_LINK, KBK_CODE, KBK_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'TYPE_FIELD_DICT', 'char(20)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'TITLE', 'ЭКР плательщика'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "SGU_LINK, SGU_CODE, SGU_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".SGU_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE', 'SHORT_CODE_OBJ', 'SGU_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'TITLE', 'Субсчет Дт'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'EDIT_OBJECT_METHOD', 'n_vibor_01("PLAN_ACCOUNTS_LIST", oObj.parent.Parent.RECORDSOURCE, "LINK,ACCCODE", "DT_ACC_LINK,DT_ACC_CODE", "LINK", "","dbo.AccountsHasNoChild(LINK)=1 AND ZABALANS = 0",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'CONTROLSOURCE', 'm.cAlias + ".DT_ACC_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'STORAGE', 'S_ACCOUNTS'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'TYPE_FIELD_DICT', 'char(15)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DT_ACC', 'SHORT_CODE_OBJ', 'DT_ACC_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'TITLE', 'Доп.кл. плательщика'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "DCL_LINK, DCL_CODE, DCL_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'CONTROLSOURCE', 'm.cAlias + ".DCL_CODE"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'STORAGE', 'DOP_CLASSIF'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE', 'SHORT_CODE_OBJ', 'DCL_CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'TITLE', 'КБК получателя'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BI_DICTION_KBK", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "KBK_LINK_D, KBK_CODE_D, KBK_NAME_D", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE_D"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'TITLE', 'ЭКР получателя'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "SGU_LINK_D, SGU_CODE_D,SGU_NAME_D", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'CONTROLSOURCE', 'm.cAlias + ".SGU_CODE_D"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'SHORT_CODE_OBJ', 'KBK_CODE_D'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'TYPE_FIELD_DICT', 'char(20)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_KBK_CODE_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_EKR_CODE_D', 'SHORT_CODE_OBJ', 'SGU_CODE_D'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'EDIT_OBJECT_METHOD', 'bb_calc_summ_doc(oForm.Alias,oObj.Parent.parent.RecordSource)
oForm.CalcNds()'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_SUMMA', 'INPUT_MASK', '99999999999.99'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'TITLE', 'Назначение платежа'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'CONTROLSOURCE', 'm.cAlias+''.TARGET'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'SHORT_CODE_OBJ', 'TARGET'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TARGET', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.TARGET'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'TITLE', 'Доп.кл. получателя'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "DCL_LINK_D, DCL_CODE_D, DCL_NAME_D", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'CONTROLSOURCE', 'm.cAlias + ".DCL_CODE_D"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'STORAGE', 'DOP_CLASSIF'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_DCL_CODE_D', 'SHORT_CODE_OBJ', 'DCL_CODE_D'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'CONTROLSOURCE', 'm.cAlias+''.TITLE'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'SHORT_CODE_OBJ', 'TITLE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_TABLE_TITLE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.TITLE'''
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE', 'Таблица для заявки на получение денег', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECEPTION_CASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE', NAME = 'Таблица для заявки на получение денег', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECEPTION_CASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_REC_NO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_REC_NO', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_REC_NO', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_REC_NO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_FIN_S_L')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_FIN_S_L', 'Ссылка на источник финансирования', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_FIN_S_L', NAME = 'Ссылка на источник финансирования', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_FIN_S_L'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_FIN_S_C')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_FIN_S_C', 'Код источника финансирования', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_FIN_S_C', NAME = 'Код источника финансирования', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_FIN_S_C'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_FIN_S_N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_FIN_S_N', 'Наименование источника финансирования', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_FIN_S_N', NAME = 'Наименование источника финансирования', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_FIN_S_N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_VID_SR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_VID_SR', 'Наименование источника финансирования', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_VID_SR', NAME = 'Наименование источника финансирования', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_VID_SR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_KBK_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_KBK_LINK', 'Ссылка на КБК', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_KBK_LINK', NAME = 'Ссылка на КБК', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_KBK_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_KBK_CODE', 'Код КБК', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_KBK_CODE', NAME = 'Код КБК', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_KBK_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_KBK_NAME', 'Наименование КБК', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_KBK_NAME', NAME = 'Наименование КБК', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_KBK_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_EKR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_EKR_LINK', 'Ссылка на ЭКР', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_EKR_LINK', NAME = 'Ссылка на ЭКР', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_EKR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_EKR_CODE', 'Код ЭКР', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_EKR_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_EKR_NAME', 'Наименование ЭКР', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_EKR_NAME', NAME = 'Наименование ЭКР', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_EKR_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_DOP_CLASS_L')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_DOP_CLASS_L', 'Ссылка на доп. классификацию', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_DOP_CLASS_L', NAME = 'Ссылка на доп. классификацию', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_DOP_CLASS_L'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_DOP_CLASS_C')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_DOP_CLASS_C', 'Код доп. классификации', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_DOP_CLASS_C', NAME = 'Код доп. классификации', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_DOP_CLASS_C'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_T_DOP_CLASS_N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_T_DOP_CLASS_N', 'Наименование доп. классификации', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_T_DOP_CLASS_N', NAME = 'Наименование доп. классификации', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_T_DOP_CLASS_N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_ITOG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_ITOG', 'Сумма', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_ITOG', NAME = 'Сумма', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_ITOG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_KP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_KP', 'Символ КП', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_KP', NAME = 'Символ КП', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_KP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_REASON')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_REASON', 'Назначение платежа', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_REASON', NAME = 'Назначение платежа', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_REASON'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_TITLE', 'Примечание', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_TITLE', NAME = 'Примечание', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_TITLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE_DOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CASH_TABLE_DOC', 'Документ', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CASH_TABLE_DOC', NAME = 'Документ', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CASH_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CASH_TABLE_DOC'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_CHECKED', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE', 'SERVER_TABLE_NAME', 'RECEPTION_CASH_TABLE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE', 'SELECT_RECORDS_METHOD', 'ftable_reception_cash_select(m.cAlias, m.nLink, ''RECEPTION_CASH_TABLE_VIEW'')'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''X_UPDATE_RECEPTION_CASH_TABLE'', m.cAlias, ''LINK_UP, FS_CODE,VID_SR, KBK, EKR, D_CL_LINK, SUMMA, RECORD_NO, REASON, TITLE, KP'', ''RECEPTION_CASH_TABLE'')
'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'CONTROLSOURCE', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'TYPE_FIELD_DICT', 'NUMERIC(9)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'SHORT_CODE_OBJ', 'RECORD_NO'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REC_NO', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_L', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_L', 'REFERENCE_TO_DICT', 'DICTIONARY_FINANCE_SOURCE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_L', 'SHORT_CODE_OBJ', 'FS_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_L', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'TITLE', 'Источник фин-ия'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'CONTROLSOURCE', 'm.cAlias + ".FS_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_T_FIN_S_L'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'SHORT_CODE_OBJ', 'FS_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FS_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_C', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'TITLE', 'Источник финансирования'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'CONTROLSOURCE', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_T_FIN_S_L'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'TYPE_FIELD_DICT', 'varchar(150)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'SHORT_CODE_OBJ', 'FS_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_FIN_S_N', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'TITLE', 'Вид средств'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'CONTROLSOURCE', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'TYPE_FIELD_DICT', 'varchar(150)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_VID_SR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_LINK', 'SHORT_CODE_OBJ', 'KBK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("bi_diction_kbk", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "KBK, KBK_CODE, KBK_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'REFERENCE_TO_DICT', 'AVANCE_ACCEPT_TABLE_KBK_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'TITLE', 'Расш. ВКР'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'CONTROLSOURCE', 'm.cAlias + ".KBK_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'REFERENCE_TO_DICT', 'AVANCE_ACCEPT_TABLE_VKR_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'SHORT_CODE_OBJ', 'KBK_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KBK_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_LINK', 'SHORT_CODE_OBJ', 'EKR'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR, EKR_CODE, EKR_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_TABLE_EKR_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'SHORT_CODE_OBJ', 'EKR_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'TITLE', 'Расш. ВКР'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'CONTROLSOURCE', 'm.cAlias + ".EKR_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_TABLE_EKR_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'SHORT_CODE_OBJ', 'EKR_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".EKR_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_EKR_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_L', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_L', 'REFERENCE_TO_DICT', 'BD_DOP_CLASSIF'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_L', 'SHORT_CODE_OBJ', 'D_CL_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_L', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'TITLE', 'Доп. классиф-ия'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "D_CL_LINK, D_CL_CODE, D_CL_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'CONTROLSOURCE', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'TITLE', 'Доп. классификация'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'CONTROLSOURCE', 'm.cAlias + ".D_CL_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'SHORT_CODE_OBJ', 'D_CL_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_T_DOP_CLASS_L'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_C', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_T_DOP_CLASS_L'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'TYPE_FIELD_DICT', 'varchar(150)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'SHORT_CODE_OBJ', 'D_CL_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".D_CL_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_T_DOP_CLASS_N', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'TYPE_FIELD_DICT', 'NUMERIC(19,2)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_ITOG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'TITLE', 'Символ КП'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'CONTROLSOURCE', 'm.cAlias+".KP"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'TYPE_FIELD_DICT', 'varchar(2)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'SHORT_CODE_OBJ', 'KP'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_KP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KP"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'TITLE', 'Назначение'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'CONTROLSOURCE', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'SHORT_CODE_OBJ', 'REASON'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_REASON', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'CONTROLSOURCE', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'SHORT_CODE_OBJ', 'TITLE'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_TITLE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'TITLE', 'Документ'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'CONTROLSOURCE', 'm.cAlias + ".DOC_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'SHORT_CODE_OBJ', 'DOC_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CASH_TABLE_DOC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DOC_NAME"'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_OPTIONS_DETAIL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FINANS_ASSIGN_OPTIONS_DETAIL', 'Детализация КБК', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FINANS_ASSIGN_OPTIONS_DETAIL', NAME = 'Детализация КБК', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FINANS_ASSIGN_OPTIONS_DETAIL'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'TITLE', 'Детализировать КБК'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'CONTROLSOURCE', 'm.cAlias + ".DETAIL"'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'TYPE_FIELD_DICT', 'bit'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'SHORT_CODE_OBJ', 'DETAIL'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DETAIL"'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_OPTIONS_DETAIL', 'CONTROL_NAME_EDIT', 'aChkKBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_S_OPT_DETAIL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FINANS_ASSIGN_S_OPT_DETAIL', 'Детализация КБК', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_S_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FINANS_ASSIGN_S_OPT_DETAIL', NAME = 'Детализация КБК', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FINANS_ASSIGN_S_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FINANS_ASSIGN_S_OPT_DETAIL'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'TITLE', 'Детализировать КБК'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'CONTROLSOURCE', 'm.cAlias + ".DETAIL"'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'TYPE_FIELD_DICT', 'bit'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'SHORT_CODE_OBJ', 'DETAIL'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DETAIL"'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_S_OPT_DETAIL', 'CONTROL_NAME_EDIT', 'aChkKBK'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'FINANS_ASSIGN_OPTIONS'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'FINANS_ASSIGN_S_OPTIONS'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXBD100701' 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','Информация из расчетных документов','TXBD100701',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 = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		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, 5,'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 		= 6,
		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, 6,'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 = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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 		= 29,
		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, 29,'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 		= 30,
		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, 30,'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 		= 31,
		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, 31,'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 		= 32,
		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, 32,'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 		= 33,
		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, 33,'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 		= 34,
		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, 34,'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 		= 35,
		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, 35,'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 		= 36,
		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, 36,'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 		= 37,
		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, 37,'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 		= 38,
		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, 38,'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 		= 39,
		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, 39,'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 		= 40,
		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, 40,'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 		= 41,
		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, 41,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКАТО',
		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,'ОКАТО','ОКАТО','STRING',11,1,0,0,'ОКАТО','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2008.08' 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','Роспись','2008.08',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR','cObjCode','KOD_BPR','FB_import_nazn_127()',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',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'FB_import_nazn_127()',
		DEP_NAME   = 'KOD_BPR',
		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_BPR',
		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_BPR','',''
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_BPR',
		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_BPR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код ТОФК отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 0,
		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, 3,'KOD_TOFK','Код ТОФК отправителя','STRING',4,0,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование органа ФК – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 120,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_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, 4,'NAME_TOFK','Наименование органа ФК – отправителя','STRING',120,0,0,0,'NM_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_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_BPR',
		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_BPR','',''
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_BPR',
		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_BPR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код ТОФК  получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 0,
		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, 3,'KOD_TOFK','Код ТОФК  получателя','STRING',4,0,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование ТОФК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 120,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_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, 4,'NAME_TOFK','Наименование ТОФК получателя','STRING',120,0,0,0,'NM_TOFK','',''
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 = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		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, 1,'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 		= 2,
		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, 2,'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 		= 3,
		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, 3,'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 		= 4,
		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, 4,'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 		= 5,
		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, 5,'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 		= 6,
		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, 6,'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 		= 7,
		NAME   		= 'Код РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 7,'KOD_RBS','Код РБС','STRING',5,1,0,1,'KOD_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Наименование РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 8,'NAME_RBS','Наименование РБС','STRING',512,0,0,1,'NAME_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'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 		= 10,
		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, 10,'ACC_SEND','Номер счета отправителя','STRING',20,0,0,0,'ACC_SEND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		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, 11,'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 		= 12,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		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, 13,'ACC_RCP','Номен счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		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, 14,'IST','Источник финансирования','STRING',20,0,0,0,'IST','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'YEAR_GOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'YEAR_GOD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'YEAR_GOD'
else		
	INSERT INTO EXPORT_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,'YEAR_GOD','Сумма','NUMBER2',NULL,0,1,2,'YEAR_GOD','',''
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 	= 3,
		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',3,0,0,0,'VID_IZM','',''
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 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		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',10,0,0,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 	= 2000,
		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',2000,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 = '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	= 1,
		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,1,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	= 1,
		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,1,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	= 1,
		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,1,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 = 'KOD_DOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код дохода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_DOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOH'
else		
	INSERT INTO EXPORT_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_DOH','Код дохода','STRING',20,1,0,0,'KOD_DOH','',''
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 = 'SUM1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		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, 11,'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 		= 12,
		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, 12,'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 		= 13,
		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, 13,'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 		= 14,
		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, 14,'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 		= 15,
		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, 15,'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 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'SUM12','Сумма за декабрь','NUMBER2',NULL,1,0,0,'SUM12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		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, 23,'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 		= 24,
		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, 24,'SUM_YEAR03','Сумма на третий год','NUMBER2',NULL,1,0,0,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		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, 25,'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 = '2012.02' 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','Роспись','2012.02',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR_12','cObjCode','KOD_BP','bb_import_br()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Роспись',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'FB_EXPORT_BR_12',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'bb_import_br()',
		DEP_NAME   = 'KOD_BP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_BP','Код бюджетополучателя – отправителя','STRING',5,0,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_BP','Наименование бюджетополучателя – отправителя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_BP','Код бюджетополучателя - получателя','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя  - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_BP','Наименование бюджетополучателя  - получателя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RL',4,2,'Общая информация по ЛБО',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация по ЛБО',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		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, 1,'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 		= 2,
		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, 2,'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 		= 3,
		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, 3,'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 		= 4,
		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, 4,'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 		= 5,
		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, 5,'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 		= 6,
		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, 6,'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 		= 7,
		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, 7,'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 		= 8,
		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, 8,'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 		= 9,
		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, 9,'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 		= 10,
		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, 10,'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 		= 11,
		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, 11,'ACC_SEND_KIND','Вид средств счета отправителя','STRING',1,1,0,0,'ACC_SEND_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		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, 12,'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 		= 13,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		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, 14,'ACC_RCP','Номер счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		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, 15,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		NAME   		= 'Вид изменения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		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, 21,'VID_IZM','Вид изменения','STRING',3,0,0,0,'VID_IZM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		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, 22,'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 		= 23,
		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, 23,'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 		= 24,
		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, 24,'DATE_SIGN','Дата подписания руководителем','DATE',0,0,0,0,'DATE_SIGN','',''
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','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2008.08' 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','Лимиты бюджетных обязательств','2008.08',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR','cObjCode','KOD_BPR','',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',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_BPR',
		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_BPR',
		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_BPR','',''
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_BPR',
		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_BPR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код ТОФК отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 0,
		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, 3,'KOD_TOFK','Код ТОФК отправителя','STRING',4,0,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование органа ФК – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 120,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_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, 4,'NAME_TOFK','Наименование органа ФК – отправителя','STRING',120,0,0,0,'NM_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_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_BPR',
		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_BPR','',''
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_BPR',
		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_BPR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код ТОФК  получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 0,
		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, 3,'KOD_TOFK','Код ТОФК  получателя','STRING',4,0,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование ТОФК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 120,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_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, 4,'NAME_TOFK','Наименование ТОФК получателя','STRING',120,0,0,0,'NM_TOFK','',''
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 = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		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, 1,'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 		= 2,
		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, 2,'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 		= 3,
		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, 3,'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 		= 4,
		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, 4,'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 		= 5,
		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, 5,'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 		= 6,
		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, 6,'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 		= 7,
		NAME   		= 'Код РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 7,'KOD_RBS','Код РБС','STRING',5,1,0,1,'KOD_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Наименование РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 8,'NAME_RBS','Наименование РБС','STRING',512,0,0,1,'NAME_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'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 		= 10,
		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, 10,'ACC_SEND','Номер счета отправителя','STRING',20,0,0,0,'ACC_SEND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		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, 11,'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 		= 12,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		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, 13,'ACC_RCP','Номен счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		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, 14,'IST','Источник финансирования','STRING',20,0,0,0,'IST','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'YEAR_GOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'YEAR_GOD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'YEAR_GOD'
else		
	INSERT INTO EXPORT_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,'YEAR_GOD','Сумма','NUMBER2',NULL,0,1,2,'YEAR_GOD','',''
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 	= 3,
		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',3,0,0,0,'VID_IZM','',''
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',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	= 1,
		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,1,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	= 1,
		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,1,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	= 1,
		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,1,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 = 'KOD_DOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код дохода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_DOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOH'
else		
	INSERT INTO EXPORT_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_DOH','Код дохода','STRING',20,1,0,0,'KOD_DOH','',''
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 = 'SUM1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		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, 11,'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 		= 12,
		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, 12,'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 		= 13,
		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, 13,'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 		= 14,
		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, 14,'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 		= 15,
		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, 15,'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 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'SUM12','Сумма за декабрь','NUMBER2',NULL,1,0,0,'SUM12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		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, 23,'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 		= 24,
		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, 24,'SUM_YEAR03','Сумма на третий год','NUMBER2',NULL,1,0,0,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM_STR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		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, 25,'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 = '2012.02' 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','Лимиты бюджетных обязательств','2012.02',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR_12','cObjCode','KOD_BP','bb_import_br()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Лимиты бюджетных обязательств',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'FB_EXPORT_BR_12',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'bb_import_br()',
		DEP_NAME   = 'KOD_BP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_BP','Код бюджетополучателя – отправителя','STRING',5,0,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_BP','Наименование бюджетополучателя – отправителя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_BP','Код бюджетополучателя - получателя','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя  - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_BP','Наименование бюджетополучателя  - получателя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RL',4,2,'Общая информация по ЛБО',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация по ЛБО',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		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, 1,'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 		= 2,
		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, 2,'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 		= 3,
		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, 3,'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 		= 4,
		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, 4,'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 		= 5,
		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, 5,'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 		= 6,
		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, 6,'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 		= 7,
		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, 7,'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 		= 8,
		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, 8,'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 		= 9,
		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, 9,'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 		= 10,
		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, 10,'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 		= 11,
		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, 11,'ACC_SEND_KIND','Вид средств счета отправителя','STRING',1,1,0,0,'ACC_SEND_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		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, 12,'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 		= 13,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		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, 14,'ACC_RCP','Номер счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		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, 15,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		NAME   		= 'Вид изменения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		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, 21,'VID_IZM','Вид изменения','STRING',3,0,0,0,'VID_IZM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		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, 22,'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 		= 23,
		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, 23,'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 		= 24,
		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, 24,'DATE_SIGN','Дата подписания руководителем','DATE',0,0,0,0,'DATE_SIGN','',''
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','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2008.03' AND CODE = 'PF'
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPST'
UPDATE EXPORT_FIELDS	SET 	ORDERS 		= 12	where LINK_BLOCK = @varKSBlockLink and CODE = 'MON_FIN'
UPDATE EXPORT_FIELDS	SET 	ORDERS 		= 13	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_STR'
UPDATE EXPORT_FIELDS	SET 	ORDERS 		= 14	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
GO

update EXPORT_MODELS set DATE_END   = '01.02.2011' where MODEL_VER = 'TXPP100701' AND CODE = 'PP'
update EXPORT_MODELS set DATE_END   = '01.02.2011' where MODEL_VER = 'TXZR100701' AND CODE = 'ZR'
update EXPORT_MODELS set DATE_END = NULL, PROC_EXP   = 'BB_EXPORT_PP', PROC_DOP_PARAM   = 'cModelVer' where MODEL_VER = '2008.06' AND CODE = 'PP'
GO


DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXPP100701' AND CODE = 'PP'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'PP','Платежное поручение','TXPP100701',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_PP()','01.02.2011' 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Платежное поручение',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_PP()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = '01.02.2011'
	where @varKSModelLink = LINK_MODEL
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PPST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код источника финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KOD_FIN','Код источника финансирования','STRING',1,1,0,0,'KOD_FIN','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXPP120101' AND CODE = 'PP'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'PP','Платежное поручение','TXPP120101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_PP()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Платежное поручение',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_PP()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PP',4,0,'Пакет',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 = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'DATE','Дата','DATE',0,0,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPT'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PPT',5,2,'Платежное поручение',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Платежное поручение',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,1,1,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OPER','Вид операции.','STRING',2,1,1,1,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'INN_PAY','ИНН Плательщика','STRING',12,0,1,1,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'KPP_PAY','КПП Плательщика','STRING',9,1,1,1,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'CNAME_PAY','Наименование Плательщика','STRING',160,0,1,1,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,1,1,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'BIC_PAY','БИК банка Плательщика','STRING',9,1,1,1,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,1,1,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 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, 13,'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 		= 14,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= '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, 16,'NAME_RCP','Наименование получателя','STRING',160,0,1,1,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'BIC_RCP','БИК банка Получателя','STRING',9,1,1,1,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,1,1,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'ORDER_PAY','Очередность платежа','STRING',1,1,1,1,'ORDER_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		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, 23,'PURPOSE','Назначение платежа','STRING',210,0,1,1,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		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, 24,'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 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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 		= 29,
		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, 29,'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 		= 30,
		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, 30,'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 		= 31,
		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, 31,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'GUID_FK','Глобальный уни-кальный идентификатор','GUID',0,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Код ОрФК  клиента-плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'KOD_TOFK_PAY','Код ОрФК  клиента-плательщика','STRING',4,1,1,1,'KOD_TOFK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Наименование ОрФК клиента- плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'NAME_TOFK_PAY','Наименование ОрФК клиента- плательщика','STRING',2000,0,1,1,'NAME_TOFK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Код клиента - плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'KOD_UBP_PAY','Код клиента - плательщика','STRING',5,1,1,1,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		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, 36,'NAME_UBP_PAY','Полное наименование клиента - Плательщика','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Л/с клиента - плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'LS_PAY','Л/с клиента - плательщика','STRING',11,1,0,0,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Л/с клиента - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_PAY_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'LS_PAY_RCP','Л/с клиента - получателя','STRING',11,1,0,0,'LS_PAY_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRINT_KPP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Признак печати КПП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRINT_KPP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRINT_KPP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'PRINT_KPP','Признак печати КПП','STRING',1,1,0,0,'PRINT_KPP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIZ')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Признак наличия Расшифровки к платежному поручению',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PRIZ',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIZ'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'PRIZ','Признак наличия Расшифровки к платежному поручению','STRING',1,1,1,1,'PRIZ','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'PPST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'PPST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели плательщика','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код цели получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'ADD_KLASS_RCP','Код цели получателя','STRING',20,0,0,0,'ADD_KLASS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Код источника финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KOD_FIN','Код источника финансирования','STRING',1,1,0,0,'KOD_FIN','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXUF120101' 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','Уведомление об уточнении вида и принадлежности платежа','TXUF120101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_UF','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_UF',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Ссылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','Ссылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,1,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',2000,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'UF'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'UF',4,2,'Уведомление об уточнении вида и принадлежности платежа',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Уведомление об уточнении вида и принадлежности платежа',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер Уведомления',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_UF','Номер Уведомления','STRING',15,0,1,1,'NOM_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата Уведомления',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_UF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_UF','Дата Уведомления','DATE',NULL,0,1,1,'DATE_UF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_UBP','Наименование ПБС/АДБ/АИФДБ','STRING',2000,0,0,0,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по Сводному реестру ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KOD_UBP','Код по Сводному реестру ПБС/АДБ/АИФДБ','STRING',5,0,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Номер лицевого счета ПБС/АДБ/АИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LS_UBP','Номер лицевого счета ПБС/АДБ/АИФДБ','STRING',11,1,1,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRS','Наименование ГРБС/ГАДБ/ГАИФДБ','STRING',2000,0,0,0,'NAME_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Глава по БК ГРБС/ГАДБ/ГАИФДБ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'GLAVA_GRS','Глава по БК ГРБС/ГАДБ/ГАИФДБ','STRING',3,1,1,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_BUD','Наименование бюджета','STRING',512,0,1,1,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'NAME_UBP_FO','Наименование финансового органа','STRING',2000,0,0,0,'NAME_UBP_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = '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	= 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, 23,'NAME_RUK','ФИО руководителя','STRING',50,0,1,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 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	= 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, 27,'DATE_POD','Дата подписания документа','DATE',NULL,0,1,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 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 = 'TXVP100701' AND CODE = 'VP'
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 'VP','Выписка из лицевого счета получателя бюджетных средств','TXVP100701',0,'','','fb_file_name_doc','BB_EXPORT_VP','','','bb_import_VP()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Выписка из лицевого счета получателя бюджетных средств',
		NORM_DOC   = '',
		FILE_NAME_MASK   = '',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_VP',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = 'bb_import_VP()',
		DEP_NAME   = '',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = '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 = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		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,0,'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 = 'VP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'VP',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 = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 2,'LS','Номер лицевого счета клиента','STRING',11,0,0,1,'LS','',''
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 	= 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, 3,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'VPPP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'VPPP',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 = 'NUM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер документа, подтверждающего проведение операции',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_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, 1,'NUM_DOC','Номер документа, подтверждающего проведение операции','STRING',15,0,1,1,'NUM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC')
	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_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, 2,'DATE_DOC','Дата документа, подтверждающе-го проведение операции','DATE',0,1,1,1,'DATE_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	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',
		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, 3,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,1,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOC_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер доку-мента получателя бюд-жетных средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_DOC_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOC_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,'NUM_DOC_UBP','Номер доку-мента получателя бюд-жетных средств','STRING',15,0,0,0,'NUM_DOC_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC_UBP')
	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_DOC_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC_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,'DATE_DOC_UBP','Дата документа получателя бюд-жетных средств','DATE',0,0,0,0,'DATE_DOC_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OUT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Выплаты',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_OUT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OUT'
else		
	INSERT INTO EXPORT_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_OUT','Выплаты','NUMBER2',0,0,1,1,'SUM_OUT','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXVP120101' AND CODE = 'VP'
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 'VP','Выписка из лицевого счета получателя бюджетных средств','TXVP120101',0,'','','fb_file_name_doc','BB_EXPORT_VP','','','bb_import_VP()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Выписка из лицевого счета получателя бюджетных средств',
		NORM_DOC   = '',
		FILE_NAME_MASK   = '',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_VP',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = 'bb_import_VP()',
		DEP_NAME   = '',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = '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 = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		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,0,'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 = 'VP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'VP',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 = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		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, 2,'LS','Номер лицевого счета клиента','STRING',11,0,0,1,'LS','',''
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 	= 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, 3,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'VPPP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'VPPP',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 = 'NUM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер документа, подтверждающего проведение операции',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_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, 1,'NUM_DOC','Номер документа, подтверждающего проведение операции','STRING',15,0,1,1,'NUM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC')
	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_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, 2,'DATE_DOC','Дата документа, подтверждающе-го проведение операции','DATE',0,1,1,1,'DATE_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	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',
		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, 3,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,1,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOC_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер доку-мента получателя бюд-жетных средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_DOC_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_DOC_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,'NUM_DOC_UBP','Номер доку-мента получателя бюд-жетных средств','STRING',15,0,0,0,'NUM_DOC_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC_UBP')
	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_DOC_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC_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,'DATE_DOC_UBP','Дата документа получателя бюд-жетных средств','DATE',0,0,0,0,'DATE_DOC_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OUT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Выплаты',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_OUT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OUT'
else		
	INSERT INTO EXPORT_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_OUT','Выплаты','NUMBER2',0,0,1,1,'SUM_OUT','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZR120101' 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','Заявка на кассовый расход','TXZR120101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZKR','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',
		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 = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		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, 15,'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 		= 16,
		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, 16,'DATE_ISP','Предельная дата исполнения','DATE',0,1,1,0,'DATE_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		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, 17,'NOM_BO','Номер обязательства','STRING',16,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		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, 18,'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 		= 19,
		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, 19,'PR_ISP','Приоритет исполнения','STRING',250,0,0,0,'PR_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'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 		= 23,
		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, 23,'TYPE_AP','Признак авансового платежа','STRING',1,1,0,1,'TYPE_AP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_NDS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Сумма НДС в валюте заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_V_NDS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_NDS'
else		
	INSERT INTO EXPORT_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,'SUM_V_NDS','Сумма НДС в валюте заявки','NUMBER2',0,1,0,0,'SUM_V_NDS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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 		= 29,
		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, 29,'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 		= 30,
		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, 30,'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 		= 31,
		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, 31,'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 		= 32,
		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, 32,'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 		= 33,
		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, 33,'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 		= 34,
		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, 34,'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 		= 35,
		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, 35,'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 		= 36,
		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, 36,'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 		= 37,
		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, 37,'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 		= 38,
		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, 38,'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 		= 39,
		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, 39,'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 		= 40,
		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, 40,'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 		= 41,
		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, 41,'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 		= 42,
		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, 42,'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 		= 43,
		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, 43,'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 		= 44,
		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, 44,'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 		= 45,
		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, 45,'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 		= 46,
		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, 46,'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 		= 47,
		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, 47,'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 		= 48,
		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, 48,'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 		= 49,
		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, 49,'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 		= 50,
		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, 50,'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 		= 51,
		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, 51,'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 		= 52,
		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, 52,'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 		= 53,
		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, 53,'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 = 'VID_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		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, 1,'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 		= 2,
		NAME   		= 'Номер документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 45,
		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, 2,'NOM_OSN','Номер документа-основания','STRING',45,0,0,1,'NOM_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		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, 3,'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 		= 4,
		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, 4,'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
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZS120101' 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','Заявка на получение наличных денег','TXZS120101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZS','','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',
		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 = 'NAME_GRBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		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, 6,'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 		= 7,
		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, 7,'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 		= 8,
		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, 8,'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 		= 9,
		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, 9,'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 		= 10,
		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, 10,'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 		= 11,
		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, 11,'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 		= 12,
		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, 12,'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 		= 13,
		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, 13,'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 		= 14,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		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, 14,'NOM_BO','Номер обязательства','STRING',16,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		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, 15,'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 		= 16,
		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, 16,'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 		= 17,
		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, 17,'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 		= 18,
		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, 18,'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 		= 19,
		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, 19,'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 		= 20,
		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, 20,'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 		= 21,
		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, 21,'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 		= 22,
		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, 22,'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 		= 23,
		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, 23,'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 		= 24,
		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, 24,'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 		= 25,
		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, 25,'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 		= 26,
		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, 26,'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 		= 27,
		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, 27,'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 		= 28,
		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, 28,'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 		= 29,
		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, 29,'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 		= 30,
		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, 30,'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 		= 31,
		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, 31,'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	= 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, 6,'PURPOSE','Назначение платежа','STRING',210,0,0,1,'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
EXEC X_SET_PROP 'BB_IMPORT_VIP_LS', 'INIT_OBJECT_METHOD', 'bb_exch_brow(''fb_import_txt'',''VP'',.f.,''VP'')'
GO

GO
-- Отчет "Карточка учета госдолга"
-- Сгенерировано скриптом scriptObjectVar 'BB_P_CREDIT_CARD'

/*** Сам отчет ***/

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= 'BB_P_CREDIT_CARD'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'BB_P_CREDIT_CARD'
	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_CREDIT'),
	'BB_P_CREDIT_CARD',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD') 
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'EXEC BB_CREDIT_CARD_DOLG null,@dDateB1,@dDateE1,@nCheck1, @nOption1 ,@nSel_Spr1 ,@cVal1,@nOtborLink1,'''',0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#BB_P_CREDIT_CARD'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KIRREPMAKERMULTISHEET.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"BB_P_CREDIT_CARD.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #BB_P_CREDIT_CARD
	@dDateB1 datetime	/* Начало расч. периода */,
	@dDateE1 datetime	/* Конец расч. периода */,
	@nCheck1 int	/* Расчет остатков по счету 301 */,
	@nSel_Spr1 int	/* Организация */,
	@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_DEPART''))
	SELECT @cVal1 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink1 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

EXEC BB_CREDIT_CARD_DOLG null,@dDateB1,@dDateE1,@nCheck1, @nOption1 ,@nSel_Spr1 ,@cVal1,@nOtborLink1,'''',0

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'CREDIT_CARD_F0504057.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	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 = 'BB_P_CREDIT_CARD') 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 = 'BB_P_CREDIT_CARD'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_FILTER_DEP' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'BB_P_CREDIT_CARD'),
		'BB_P_CREDIT_CARD_FILTER_DEP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OTBOR' 
					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_DEPART'),
					'Отбор учреждений',1, 
					(Select link from object_var where code = 'BB_P_CREDIT_CARD_FILTER_DEP'),
					'BB_P_CREDIT_CARD_OTBOR',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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_DEPARTMENT'
						
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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(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 = 'BB_P_CREDIT_CARD_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',2, 
		(Select link from object_var where code = 'BB_P_CREDIT_CARD'),
		'BB_P_CREDIT_CARD_OPTIONS',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS_DATEB' 
					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'),
					'Начало расч. периода',3, 
					(Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS'),
					'BB_P_CREDIT_CARD_OPTIONS_DATEB',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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Начало расч. периода'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'01.01.2011'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'01.01.2006'
						
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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEB'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS_DATEE' 
					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'),
					'Конец расч. периода',4, 
					(Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS'),
					'BB_P_CREDIT_CARD_OPTIONS_DATEE',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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Конец расч. периода'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'31.12.2011'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'31.12.2011'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DATEE'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS_DEP' 
					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'),
					'Организация',6, 
					(Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS'),
					'BB_P_CREDIT_CARD_OPTIONS_DEP',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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'DICTIONARY_DEPARTMENT'
						
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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_DEP') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_DEP'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS_REST' 
					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'),
					'Расчет остатков по счету 301',5, 
					(Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS'),
					'BB_P_CREDIT_CARD_OPTIONS_REST',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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Расчет остатков по счету 301'
						
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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_REST') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_REST'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_P_CREDIT_CARD_OPTIONS_TYPE' 
					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 = 'BB_P_CREDIT_CARD_OPTIONS'),
					'BB_P_CREDIT_CARD_OPTIONS_TYPE',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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вид кредита'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(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 = 'BB_P_CREDIT_CARD_OPTIONS_TYPE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_P_CREDIT_CARD_OPTIONS_TYPE'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "Ведомость учета невыясненных поступлений"
-- Сгенерировано скриптом scriptObjectVar 'BB_REPORT_NEVIYASN'

/*** Сам отчет ***/

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= 'BB_REPORT_NEVIYASN'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'BB_REPORT_NEVIYASN'
	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_REPORTS_CATALOG_DTKT'),
	'BB_REPORT_NEVIYASN',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'BB_REPORT_NEVIYASN') 
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec BB_REPORT_NEVIYASN
	@dDateB1	/* Начало периода */,
	@dDateE1	/* Конец периода */'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#BB_REPORT_NEVIYASN'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.t.,"BB_REPORT_NEVIYASN.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #BB_REPORT_NEVIYASN
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */
AS
BEGIN

exec BB_REPORT_NEVIYASN
	@dDateB1	/* Начало периода */,
	@dDateE1	/* Конец периода */

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	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 = 'BB_REPORT_NEVIYASN') 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 = 'BB_REPORT_NEVIYASN'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'BB_REPORT_NEVIYASN_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 = 'BB_REPORT_NEVIYASN'),
		'BB_REPORT_NEVIYASN_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_REPORT_NEVIYASN_NASTR_DATEB' 
					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 = 'BB_REPORT_NEVIYASN_NASTR'),
					'BB_REPORT_NEVIYASN_NASTR_DATEB',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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'01.01.2012'
						
						
						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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEB'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_REPORT_NEVIYASN_NASTR_DATEE' 
					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 = 'BB_REPORT_NEVIYASN_NASTR'),
					'BB_REPORT_NEVIYASN_NASTR_DATEE',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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'20.12.2012'
						
						
						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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(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 = 'BB_REPORT_NEVIYASN_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_REPORT_NEVIYASN_NASTR_DATEE'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Ведомость учета невыясненных поступлений"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'BB_REPORT_NEVIYASN')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'REPORTS_CALCULATE')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'REPORTS_CALCULATE'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'BB_REPORT_NEVIYASN'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'BB_REPORT_NEVIYASN', 'Ведомость учета невыясненных поступлений', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO


GO
-- Отчет "Карточка учета государственного долга Российской Федерации в ценных бумагах"
-- Сгенерировано скриптом scriptObjectVar 'BB_CREDIT_CARD_CB'

/*** Сам отчет ***/

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= 'BB_CREDIT_CARD_CB'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'BB_CREDIT_CARD_CB'
	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_CREDIT'),
	'BB_CREDIT_CARD_CB',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'BB_CREDIT_CARD_CB') 
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'execute BB_CREDIT_CARD_CB
	@dDateB1 /* Дата начала расчета */,
	@dDateE1 /* Дата окончания расчета */'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#BB_CREDIT_CARD_CB'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KIRREPMAKERMULTISHEET.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.t.,"BB_CREDIT_CARD_CB.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #BB_CREDIT_CARD_CB
	@dDateB1 datetime	/* Дата начала расчета */,
	@dDateE1 datetime	/* Дата окончания расчета */
AS
BEGIN

execute BB_CREDIT_CARD_CB
	@dDateB1 /* Дата начала расчета */,
	@dDateE1 /* Дата окончания расчета */

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'CREDIT_CARD_F0504057.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	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 = 'BB_CREDIT_CARD_CB') 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 = 'BB_CREDIT_CARD_CB'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'BB_CREDIT_CARD_CB_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 = 'BB_CREDIT_CARD_CB'),
		'BB_CREDIT_CARD_CB_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_CREDIT_CARD_CB_NASTR_DATEB' 
					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 = 'BB_CREDIT_CARD_CB_NASTR'),
					'BB_CREDIT_CARD_CB_NASTR_DATEB',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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Начало расч. периода'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'01.01.2011'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEB') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEB'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'BB_CREDIT_CARD_CB_NASTR_DATEE' 
					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 = 'BB_CREDIT_CARD_CB_NASTR'),
					'BB_CREDIT_CARD_CB_NASTR_DATEE',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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Конец расч. периода'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'26.12.2012'
						
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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(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 = 'BB_CREDIT_CARD_CB_NASTR_DATEE') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'BB_CREDIT_CARD_CB_NASTR_DATEE'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Карточка учета государственного долга Российской Федерации в ценных бумагах"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'BB_CREDIT_CARD_CB')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'CREDITS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'CREDITS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'BB_CREDIT_CARD_CB'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'BB_CREDIT_CARD_CB', 'Карточка учета государственного долга Российской Федерации в ценных бумагах', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_817_69N_NASTR', 'Настройки уведомления', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_817_69N_NASTR', NAME = 'Настройки уведомления', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_817_69N_NASTR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR_DATE_B')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_817_69N_NASTR_DATE_B', 'Дата начала расчета', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_817_69N_NASTR_DATE_B', NAME = 'Дата начала расчета', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_817_69N_NASTR_DATE_B'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR_DATE_E')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_817_69N_NASTR_DATE_E', 'Дата окончания расчета', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_817_69N_NASTR_DATE_E', NAME = 'Дата окончания расчета', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_817_69N_NASTR_DATE_E'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_817_69N_NASTR_KBK', 'Использовать связанные КБК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_817_69N_NASTR_KBK', NAME = 'Использовать связанные КБК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_817_69N_NASTR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_817_69N_NASTR_KBK'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR', 'TITLE', 'Настройки'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR', 'EDIT_OBJECT_METHOD', 'finans_brow(''BB_UVED_817_69N_NASTR'')
'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'TITLE', 'Период расчета с'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'SHORT_CODE_OBJ', 'DATE_B'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DATE_B'''
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_B', 'CONTROL_NAME_EDIT', 'Aseldate1'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'TITLE', 'по'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'SHORT_CODE_OBJ', 'DATE_E'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DATE_E'''
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_DATE_E', 'CONTROL_NAME_EDIT', 'Aseldate2'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'TITLE', 'Использовать связанные КБК'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'SHORT_CODE_OBJ', 'KBK'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.KBK'''
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_NASTR_KBK', 'CONTROL_NAME_EDIT', 'aChk3'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'BB_UVED_817_69N_NASTR'
GO
EXEC X_SET_PROP 'BB_UVED_817_69N_P1', 'ROWSOURCE', '"неиспользованный остаток подлежит возврату,предусмотрено предоставление межбюджетного трансферта,зачтено расходов. подтвержденных документами,потребность в неиспользованом остатке подтверждена"'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_OPTIONS_KOR_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'Формат наименования получателя', 26, (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_KOR_NAME', NAME = 'Формат наименования получателя', ORDERS = '26', 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_KOR_NAME'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'TITLE', 'Формат наименования получателя'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'EDIT_OBJECT_METHOD', 'BB_VIBOR_SHABLON (oForm.Alias, "KOR_NAME", "DEP_NAME")'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'SHORT_CODE_OBJ', 'KOR_NAME'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KOR_NAME"'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME', 'CONTROL_NAME_EDIT', 'Pages.Page1.Asel_spr2'
GO
exec X_FORM_VIEW_OPTIONS  'BB_ZAYAVKA_KR_OPTIONS'
GO
exec X_SET_OPTION 'BB_ZAYAVKA_KR_OPTIONS_KOR_NAME',0,'<Наим_орг_полн>'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_DEPART_NAME_F')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_DEPART_NAME_F', 'Полное наименование организации', 82, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_DEPART_NAME_F', NAME = 'Полное наименование организации', ORDERS = '82', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_DEPART_NAME_F'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'COMMENTARY', 'Полное наименование организации'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 152px; POSITION: absolute; TOP: 80px"
Width="576px"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 113; LEFT: 24px; POSITION: absolute; TOP: 80px"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'FIELD_DATA', 'F_NAME_CHAR'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'SHORT_CODE_OBJ', 'F_NAME_CHAR'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'TYPE_FIELD_DICT', 'VARCHAR(2000)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'CONTROLSOURCE', 'm.cAlias + ".F_NAME_CHAR"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'VISIBLE', '5'
GO
EXEC X_SET_PROP 'COLUMN_DICT_DEPART_NAME_F', 'TITLE', 'Полное наименование организации'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DOC_PAY_OKATO1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DOC_PAY_OKATO1', 'Код ОКАТО', 41, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DOC_PAY_OKATO1', NAME = 'Код ОКАТО', ORDERS = '41', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DOC_PAY_OKATO1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'TITLE', 'Код ОКАТО'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTION_PAY_OKATO",oForm.Pages.Page3.ALIAS, " CODE", "OKATO", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'CONTROLSOURCE', 'm.cAlias+''.OKATO'''
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'TYPE_FIELD_DICT', 'varchar(11)'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.OKATO'''
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DOC_PAY_PERIOD_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DOC_PAY_PERIOD_1', 'Налоговый период', 42, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DOC_PAY_PERIOD_1', NAME = 'Налоговый период', ORDERS = '42', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DOC_PAY_PERIOD_1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'TITLE', 'НП'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'CONTROLSOURCE', 'm.cAlias+''.PERIOD'''
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'SHORT_CODE_OBJ', 'PERIOD'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_PERIOD_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.PERIOD'''
GO

GO
--Добавление колонки ISUSED таблицы DEPARTMENTS
IF COLUMNPROPERTY(object_id('[dbo].[DEPARTMENTS]'), 'ISUSED', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[DEPARTMENTS] ADD [ISUSED] tinyint NOT NULL CONSTRAINT [DF_DEPARTMENTS_USED] DEFAULT ((1))
GO
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_F0504833_OPT_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_F0504833_OPT_DATE', 'Выводить дату проводки при печати', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_F0504833_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_F0504833_OPT_DATE', NAME = 'Выводить дату проводки при печати', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_F0504833_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_F0504833_OPT_DATE'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'TITLE', 'Выводить дату проводки при печати'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'DOCUMENTS_F0504833_OPT_DATE', 'CONTROL_NAME_EDIT', 'aChkDATE'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'DOCUMENTS_F0504833_OPT'
GO

GO
-- Удаление констрейнта FK_SAL_DED_MONTH_DICTION1 из DICTION
IF  EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SAL_DED_MONTH_DICTION1]'))
--Констрэинт
ALTER TABLE [dbo].[SAL_DED_MONTH] 
drop CONSTRAINT [FK_SAL_DED_MONTH_DICTION1]
GO

-- Добавление констрейнта FK_SAL_DED_MONTH_DICTIONARY_TYP_DEDUCTION1 в таблицу DICTIONARY_TYP_DEDUCTION
IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SAL_DED_MONTH_DICTIONARY_TYP_DEDUCTION1]'))
--Констрэинт
ALTER TABLE [dbo].[SAL_DED_MONTH] 
ADD CONSTRAINT [FK_SAL_DED_MONTH_DICTIONARY_TYP_DEDUCTION1] FOREIGN KEY ([REF_DED]) REFERENCES [dbo].[DICTIONARY_TYP_DEDUCTION] ([LINK])
GO


GO
EXEC X_SET_PROP 'FINANS_ASSIGN', 'EXCH_MODEL_CODE', 'BR'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN', 'EXCHANGE', '7'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_SVOD', 'EXCH_MODEL_CODE', 'BR'
GO
EXEC X_SET_PROP 'FINANS_ASSIGN_SVOD', 'EXCHANGE', '7'
GO
EXEC X_SET_PROP 'FINANS_LIMIT', 'EXCH_MODEL_CODE', 'LB'
GO
EXEC X_SET_PROP 'FINANS_LIMIT', 'EXCHANGE', '7'
GO
EXEC X_SET_PROP 'FINANS_LIMIT_SVOD', 'EXCH_MODEL_CODE', 'LB'
GO
EXEC X_SET_PROP 'FINANS_LIMIT_SVOD', 'EXCHANGE', '7'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIN_RR_104N_OPTIONS', 'Настройки расходного расписания', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIN_RR_104N_OPTIONS', NAME = 'Настройки расходного расписания', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIN_RR_104N_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS_TYP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIN_RR_104N_OPTIONS_TYP_LINK', 'Ссылка на операцию  для ПБС', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK', NAME = 'Ссылка на операцию  для ПБС', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIN_RR_104N_OPTIONS_TYP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS_TYP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIN_RR_104N_OPTIONS_TYP_NAME', 'Наим тип. опер.  для ПБС', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIN_RR_104N_OPTIONS_TYP_NAME', NAME = 'Наим тип. опер.  для ПБС', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIN_RR_104N_OPTIONS_TYP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS_TYP_LINK1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'Ссылка на операцию для РБС', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK1', NAME = 'Ссылка на операцию для РБС', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIN_RR_104N_OPTIONS_TYP_LINK1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS_TYP_NAME1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'Наим тип. опер.  для РБС', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIN_RR_104N_OPTIONS_TYP_NAME1', NAME = 'Наим тип. опер.  для РБС', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_104N_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIN_RR_104N_OPTIONS_TYP_NAME1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS', 'TITLE', 'Настройки'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS', 'EDIT_OBJECT_METHOD', 'finans_brow(''FIN_RR_104N_OPTIONS'')'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK', 'TITLE', 'Ссылка на операцию  для ПБС'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK', 'SHORT_CODE_OBJ', 'TYP_LINK'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'TITLE', 'Типовая операция  для ПБС'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK", "TYP_NAME", "FIN_RR_104N")'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".TYP_NAME"'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'REFERENCE_TO_DICT', 'FIN_RR_104N_OPTIONS_TYP_LINK'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'SHORT_CODE_OBJ', 'TYP_NAME'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME"'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'TITLE', 'Ссылка на операцию для РБС'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'SHORT_CODE_OBJ', 'TYP_LINK1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_LINK1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'TITLE', 'Типовая операция  для РБС'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK1", "TYP_NAME1", "FIN_RR_104N")'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'CONTROLSOURCE', 'm.cAlias + ".TYP_NAME1"'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'REFERENCE_TO_DICT', 'FIN_RR_104N_OPTIONS_TYP_LINK1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'SHORT_CODE_OBJ', 'TYP_NAME1'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME1"'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'FIN_RR_104N_OPTIONS_TYP_NAME1', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'FIN_RR_104N_OPTIONS'  
GO
declare @iLinkTO int
select @iLinkTO = T.LINK_OPER 
from dbo.DOC_NASTR_T1 T
inner join dbo.S_OBJECTS SO ON T.LINK_UP = SO.LINK and T.OSN = 1 and SO.CODE = 'FIN_RR_104N'
if @iLinkTO is not null
begin
	if not exists(SELECT O.OPERATION FROM G_PROV1_OBJECT O inner join dbo.S_OBJECTS SO ON O.OBJECT = SO.LINK and SO.CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK')
		INSERT INTO G_PROV1_OBJECT(OBJECT,OPERATION)
		select LINK, @iLinkTO from dbo.S_OBJECTS where CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK'
	if not exists(SELECT O.OPERATION FROM G_PROV1_OBJECT O inner join dbo.S_OBJECTS SO ON O.OBJECT = SO.LINK and SO.CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK1')
		INSERT INTO G_PROV1_OBJECT(OBJECT,OPERATION)
		select LINK, @iLinkTO from dbo.S_OBJECTS where CODE = 'FIN_RR_104N_OPTIONS_TYP_LINK1'
end
GO
EXEC X_SET_PROP 'FIN_RR_104N', 'OPTIONS_OBJECT_CODE', 'FIN_RR_104N_OPTIONS'
GO


GO
--Добавление колонки VAC_KOMPENS_DAY таблицы ITEM_DIS_FACE
IF COLUMNPROPERTY(object_id('[dbo].[ITEM_DIS_FACE]'), 'VAC_KOMPENS_DAY', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[ITEM_DIS_FACE] ADD [VAC_KOMPENS_DAY] numeric(6, 2) NULL CONSTRAINT [DF__ITEM_DIS___VAC_K__20EFF2DA] DEFAULT ((0))
GO

--Измение колонки VAC_KOMPENS_DAY таблицы ITEM_DIS_FACE
ALTER TABLE [dbo].[ITEM_DIS_FACE] ALTER COLUMN [VAC_KOMPENS_DAY] numeric(6, 2) NULL 
GO


GO
IF EXISTS(SELECT * FROM S_NAVIGATOR WHERE code like '%STATYA67%')
	DELETE FROM S_NAVIGATOR WHERE code like '%STATYA67%'


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[STATYA67]') AND OBJECTPROPERTY(id, N'IsView') = 1)
	DROP VIEW dbo.[STATYA67]
GO
--Таблица punkt_postanov
IF not exists(select * from sysobjects where id = object_id('[dbo].[punkt_postanov]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[punkt_postanov] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[CODE] varchar(10) NOT NULL ,
	[NAME] varchar(2000) NOT NULL ,
	[PRIK_TYP] int NOT NULL )
GO

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK_punkt_postanov]'))
ALTER TABLE [dbo].[punkt_postanov] 
ADD CONSTRAINT [PK_punkt_postanov] PRIMARY KEY CLUSTERED ([LINK])
GO
--Триггеры


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_ORDERS', 'Порядок', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_ORDERS', NAME = 'Порядок', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_ORDERS'
GO
GO
--Добавление колонки EMAIL таблицы EMPL_PHONE
IF COLUMNPROPERTY(object_id('[dbo].[EMPL_PHONE]'), 'EMAIL', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[EMPL_PHONE] ADD [EMAIL] varchar(100) NULL 
GO

GO
--Добавление колонки io таблицы item_move
IF COLUMNPROPERTY(object_id('[dbo].[ITEM_MOVE]'), 'IO', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[ITEM_MOVE] ADD [IO] tinyint NOT NULL CONSTRAINT [DF_ITEM_MOVE_IO] DEFAULT ((0))
GO
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NASTR_PAY_LINKED_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NASTR_PAY_LINKED_KBK', 'Выводить связаный КБК', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NASTR_PAY_LINKED_KBK', NAME = 'Выводить связаный КБК', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NASTR_PAY_LINKED_KBK'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'CONTROL_NAME_EDIT', 'Pages.Page1.aChkLinkedKBK'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINKED_KBK"'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'SHORT_CODE_OBJ', 'LINKED_KBK'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'NASTR_PAY_LINKED_KBK', 'TITLE', 'Выводить связаный КБК'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'DOCUMENTS_PAY_OPTIONS'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DOC_PAY_SUMMA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DOC_PAY_SUMMA_NDS', 'Сумма НДС', 37, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DOC_PAY_SUMMA_NDS', NAME = 'Сумма НДС', ORDERS = '37', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_PAY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DOC_PAY_SUMMA_NDS'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'TITLE', 'Сумма НДС'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_NDS'''
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'SHORT_CODE_OBJ', 'SUMMA_NDS'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA_NDS'''
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'CONTROL_NAME_EDIT', 'ATxt15'
GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_SUMMA_NDS', 'INPUT_MASK', '99 999 999 999.99'
GO

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

GO
DELETE FROM [dbo].[FILES] 
WHERE NOT EXISTS (SELECT * FROM [dbo].[DOCUMENTS] WHERE [dbo].[DOCUMENTS].[LINK] = [dbo].[FILES].[LINK_DOC])
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_FILES_DOCUMENTS]'))
ALTER TABLE [dbo].[FILES] 
ADD CONSTRAINT [FK_FILES_DOCUMENTS] FOREIGN KEY ([LINK_DOC]) REFERENCES [dbo].[DOCUMENTS] ([LINK])
 ON DELETE CASCADE
GO


GO


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

GO

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

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

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

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_ACHILD_PAYS_LINK_PAY1]'))
ALTER TABLE [dbo].[SDOC_ACHILD] 
ADD CONSTRAINT [FK_SDOC_ACHILD_PAYS_LINK_PAY1] FOREIGN KEY ([LINK_PAY1]) REFERENCES [dbo].[PAYS] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_ACHILD_PAYS_LINK_PAY2]'))
ALTER TABLE [dbo].[SDOC_ACHILD] 
ADD CONSTRAINT [FK_SDOC_ACHILD_PAYS_LINK_PAY2] FOREIGN KEY ([LINK_PAY2]) REFERENCES [dbo].[PAYS] ([LINK])
GO
--Триггеры

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

GO



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



GO


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

GO



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

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



GO



GO
--Таблица SDOC_ACHILD_TABLE
IF not exists(select * from sysobjects where id = object_id('[dbo].[SDOC_ACHILD_TABLE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SDOC_ACHILD_TABLE] (
	[LINK_UP] int NOT NULL ,
	[ORDERS] int NOT NULL ,
	[LINK_VAC_CHILD] INT NOT NULL,
	[LINK_SFIN] INT NOT NULL,
	[DAYS] int NOT NULL ,
	[HOURS] numeric(18, 2) NOT NULL ,
	[DAYS_NORM] int NOT NULL ,
	[HOURS_NORM] numeric(18, 2) NOT NULL ,
	[SUMMA_NEW] numeric(18, 2) NOT NULL,
	[SUMMA_OLD] numeric(18, 2) NOT NULL,
	[SUMMA] numeric(18, 2) NOT NULL,
	[DATE_BEG] DATETIME NOT NULL,
	[DATE_END] DATETIME NOT NULL,
	[REGION] numeric(10, 2) NULL ,
	[REGSUM] numeric(18, 2) NOT NULL ,
	[NORTH] numeric(10, 2) NULL ,
	[NORTHSUM] numeric(18, 2) NOT NULL )
GO

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_ACHILD_TABLE1')
CREATE INDEX [IX_SDOC_ACHILD_TABLE1] ON [dbo].[SDOC_ACHILD_TABLE] ([LINK_VAC_CHILD]) ON [INDEX]
GO

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_ACHILD_TABLE_VAC_CHILD]'))
ALTER TABLE [dbo].[SDOC_ACHILD_TABLE] 
ADD CONSTRAINT [FK_SDOC_ACHILD_TABLE_VAC_CHILD] FOREIGN KEY ([LINK_VAC_CHILD]) REFERENCES [dbo].[VAC_CHILD] ([LINK])
GO

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

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

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

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

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

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

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

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

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

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

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

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

GO



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

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



GO


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

GO



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

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



GO



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

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

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

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


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


ALTER TABLE dbo.SDOC_DGH_TABLE DISABLE TRIGGER ALL

UPDATE dbo.SDOC_DGH_TABLE
	SET [OBJECT] = 1
WHERE
	[OBJECT] =(select LINK from s_objects where code = 'DOCUMENTS_DGH_T1')

UPDATE dbo.SDOC_DGH_TABLE
	SET [OBJECT] = 2
WHERE
	[OBJECT] =(select LINK from dbo.s_objects where code = 'DOCUMENTS_DGH_T2')

UPDATE dbo.SDOC_DGH_TABLE
	SET [OBJECT] = 3
WHERE
	[OBJECT] =(select LINK from s_objects where code = 'DOCUMENTS_DGH_T3')
	
ALTER TABLE dbo.SDOC_DGH_TABLE ENABLE TRIGGER ALL

GO

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

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

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

UPDATE [dbo].[SDOC_DOT_SKIDKI] SET [LINK_EKR] = @LINK_EKR213 WHERE [LINK_EKR] IS NULL

ALTER TABLE [dbo].[SDOC_DOT_SKIDKI] ENABLE TRIGGER ALL 

GO

ALTER TABLE [dbo].[SDOC_DOT_SKIDKI] ALTER COLUMN [LINK_EKR] int NOT NULL 
GO

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

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

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

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

UPDATE [dbo].[SDOC_DOT_TABLE] SET [LINK_EKR] = @LINK_EKR213 WHERE [LINK_EKR] IS NULL

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

GO

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

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

GO

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

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

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

UPDATE [dbo].[SDOC_DOT_VYCHET] SET [LINK_EKR] = @LINK_EKR213 WHERE [LINK_EKR] IS NULL

ALTER TABLE [dbo].[SDOC_DOT_VYCHET] ENABLE TRIGGER ALL 

GO

ALTER TABLE [dbo].[SDOC_DOT_VYCHET] ALTER COLUMN [LINK_EKR] int NOT NULL 
GO

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

GO
--Добавление колонки percent таблицы STO_WEEK_HOURS
IF COLUMNPROPERTY(object_id('[dbo].[STO_WEEK_HOURS]'), 'M_STAVKA', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[STO_WEEK_HOURS] ADD M_STAVKA numeric(18, 2) NULL
GO
EXEC ('UPDATE [dbo].[STO_WEEK_HOURS] SET [M_STAVKA] = 0 WHERE [M_STAVKA] IS NULL')
EXEC ('ALTER TABLE [dbo].[STO_WEEK_HOURS] ALTER COLUMN [M_STAVKA] INT NOT NULL')
GO
IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_STO_WEEK_HOURS_M_STAVKA]'))
ALTER TABLE [dbo].[STO_WEEK_HOURS] 
ADD CONSTRAINT [DF_STO_WEEK_HOURS_M_STAVKA] DEFAULT ((0)) FOR [M_STAVKA]
GO


GO

--Добавление колонки sum_dolg_str таблицы SZV4_svedenia
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_svedenia]'), 'sum_dolg_str', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_svedenia] ADD [sum_dolg_str] numeric(18, 2) NOT NULL CONSTRAINT [DF_SZV4_sum_dolg_str] DEFAULT ((0))
GO
--Добавление колонки sum_uplata_dolga_str таблицы SZV4_svedenia
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_svedenia]'), 'sum_uplata_dolga_str', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_svedenia] ADD [sum_uplata_dolga_str] numeric(18, 2) NOT NULL CONSTRAINT [DF_SZV4_sum_uplata_dolga_str] DEFAULT ((0))
GO
--Добавление колонки sum_dolg_nak таблицы SZV4_svedenia
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_svedenia]'), 'sum_dolg_nak', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_svedenia] ADD [sum_dolg_nak] numeric(18, 2) NOT NULL CONSTRAINT [DF_SZV4_sum_dolg_nak] DEFAULT ((0))
GO
--Добавление колонки sum_uplata_dolga_nak таблицы SZV4_svedenia
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_svedenia]'), 'sum_uplata_dolga_nak', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_svedenia] ADD [sum_uplata_dolga_nak] numeric(18, 2) NOT NULL CONSTRAINT [DF_SZV4_sum_uplata_dolga_nak] DEFAULT ((0))
GO
--Добавление колонки sum_uplata_dolga_nak таблицы SZV4_PACHKA
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_pachka]'), 'sum_uplata_dolga_nak', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_pachka] ADD [sum_uplata_dolga_nak] numeric(15, 2) NOT NULL CONSTRAINT [DF_SZV4_pachka_sum_uplata_dolga_nak] DEFAULT ((0))
GO
--Добавление колонки sum_uplata_dolga_str таблицы SZV4_PACHKA
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_pachka]'), 'sum_uplata_dolga_str', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_pachka] ADD [sum_uplata_dolga_str] numeric(15, 2) NOT NULL CONSTRAINT [DF_SZV4_pachka_sum_uplata_dolga_str] DEFAULT ((0))
GO
--Добавление колонки LINK_SELF2 таблицы SZV4_pachka
IF COLUMNPROPERTY(object_id('[dbo].[SZV4_pachka]'), 'LINK_SELF2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[SZV4_pachka] ADD [LINK_SELF2] int NULL 
GO
IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV4_pachka_LINK_SELF2]'))
ALTER TABLE [dbo].[SZV4_pachka] 
ADD CONSTRAINT [FK_SZV4_pachka_LINK_SELF2] FOREIGN KEY ([LINK_SELF2]) REFERENCES [dbo].[SZV4_pachka] ([link])
GO


GO
--ОТСУТСТВУЮЩИЕ ИНДЕКСЫ

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'BA_INDEX_EXTRA_NOMENLINK_DATESTART')
CREATE INDEX [BA_INDEX_EXTRA_NOMENLINK_DATESTART] ON [dbo].[BA_EXTRA] ([LINK_NOMEN], [DATE_START]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'EMPL_EXPIR_UNIQ')
CREATE UNIQUE INDEX [EMPL_EXPIR_UNIQ] ON [dbo].[EMPL_EXPIR] ([EMPL_LINK], [EXPIR_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'G_PROV_DATE')
CREATE CLUSTERED INDEX [G_PROV_DATE] ON [dbo].[G_PROV] ([OBJECT], [GET_STORE], [DATE])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'G_PROV_DATE_PROV')
CREATE INDEX [G_PROV_DATE_PROV] ON [dbo].[G_PROV] ([DATE_PROV], [LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'G_PROV_STORE_LINK_CARD_LINK_DOC')
CREATE INDEX [G_PROV_STORE_LINK_CARD_LINK_DOC] ON [dbo].[G_PROV_STORE] ([LINK_CARD], [LINK_DOC]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ASSETS_CARD_NO')
CREATE INDEX [IX_ASSETS_CARD_NO] ON [dbo].[ASSETS] ([CARD_NO]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CALCULATE_EMPL_PERIOD')
CREATE INDEX [IX_CALCULATE_EMPL_PERIOD] ON [dbo].[CALCULATE_JURNAL] ([LINK_EMPL], [PERIOD_BEGIN], [PERIOD_END]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CALCULATE_JURNAL_DBE')
CREATE INDEX [IX_CALCULATE_JURNAL_DBE] ON [dbo].[CALCULATE_JURNAL] ([LINK], [DATE_BEGIN], [DATE_END]) ON [INDEX]
GO

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

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_EMPLS')
CREATE INDEX [IX_CONST_PAYS_EMPLS] ON [dbo].[CONST_PAYS_EMPLS] ([link_empl]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_EMPLS_1')
CREATE INDEX [IX_CONST_PAYS_EMPLS_1] ON [dbo].[CONST_PAYS_EMPLS] ([date_begin]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_EMPLS_2')
CREATE INDEX [IX_CONST_PAYS_EMPLS_2] ON [dbo].[CONST_PAYS_EMPLS] ([link_empl], [date_begin]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_TAR_EMPLS')
CREATE INDEX [IX_CONST_PAYS_TAR_EMPLS] ON [dbo].[CONST_PAYS_TAR_EMPLS] ([link_empl]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_TAR_EMPLS_1')
CREATE INDEX [IX_CONST_PAYS_TAR_EMPLS_1] ON [dbo].[CONST_PAYS_TAR_EMPLS] ([date_begin]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CONST_PAYS_TAR_EMPLS_2')
CREATE INDEX [IX_CONST_PAYS_TAR_EMPLS_2] ON [dbo].[CONST_PAYS_TAR_EMPLS] ([link_empl], [date_begin]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_CORRECT_PROV_LINK_HOZ')
CREATE INDEX [IX_CORRECT_PROV_LINK_HOZ] ON [dbo].[CORRECT_PROV] ([LINK_HOZ]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DAYSHOURS_1')
CREATE INDEX [IX_DAYSHOURS_1] ON [dbo].[DAYSHOURS] ([HOURS]) ON [INDEX]
GO

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DEPARTMENTS_NAME')
CREATE INDEX [IX_DEPARTMENTS_NAME] ON [dbo].[DEPARTMENTS] ([NAME]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DEPARTMENTS_TYPE')
CREATE INDEX [IX_DEPARTMENTS_TYPE] ON [dbo].[DEPARTMENTS] ([TYPE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DICTION_APP_OBJECT')
CREATE INDEX [IX_DICTION_APP_OBJECT] ON [dbo].[DICTION_APP] ([OBJECT]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DICTION_MUNICIPAL')
CREATE UNIQUE INDEX [IX_DICTION_MUNICIPAL] ON [dbo].[DICTION_MUNICIPALS] ([CODE_MF]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DICTION_SUBJECTS_RF')
CREATE UNIQUE INDEX [IX_DICTION_SUBJECTS_RF] ON [dbo].[DICTION_SUBJECTS_RF] ([CODE_MF]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DOC_ANALIT_TABLE')
CREATE INDEX [IX_DOC_ANALIT_TABLE] ON [dbo].[DOC_ANALIT_TABLE] ([LINK_DOC], [ORDERS]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_DOCUMENTS_REF_RUO')
CREATE INDEX [IX_DOCUMENTS_REF_RUO] ON [dbo].[DOCUMENTS_REF] ([REF_UP], [OBJECT]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ECONOMY_OPER')
CREATE INDEX [IX_ECONOMY_OPER] ON [dbo].[ECONOMY_OPER] ([LINK_SELF]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ECONOMY_OPER_LEDGE_JURNAL')
CREATE INDEX [IX_ECONOMY_OPER_LEDGE_JURNAL] ON [dbo].[ECONOMY_OPER] ([LEDGER_JOURNAL]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_CONTROL')
CREATE INDEX [IX_EVENT_CONTROL] ON [dbo].[EVENT_CONTROL] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_CONTROL_1')
CREATE INDEX [IX_EVENT_CONTROL_1] ON [dbo].[EVENT_CONTROL] ([CONTROL_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECU')
CREATE INDEX [IX_EVENT_EXECU] ON [dbo].[EVENT_EXECU] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECU_1')
CREATE INDEX [IX_EVENT_EXECU_1] ON [dbo].[EVENT_EXECU] ([EXECU_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS')
CREATE INDEX [IX_EVENT_EXECUTORS] ON [dbo].[EVENT_EXECUTORS] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS_1')
CREATE INDEX [IX_EVENT_EXECUTORS_1] ON [dbo].[EVENT_EXECUTORS] ([SROK_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS_2')
CREATE INDEX [IX_EVENT_EXECUTORS_2] ON [dbo].[EVENT_EXECUTORS] ([EXECUTOR]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS_3')
CREATE INDEX [IX_EVENT_EXECUTORS_3] ON [dbo].[EVENT_EXECUTORS] ([ISP_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS_4')
CREATE INDEX [IX_EVENT_EXECUTORS_4] ON [dbo].[EVENT_EXECUTORS] ([RES_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_EXECUTORS_5')
CREATE INDEX [IX_EVENT_EXECUTORS_5] ON [dbo].[EVENT_EXECUTORS] ([LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_LINKS')
CREATE INDEX [IX_EVENT_LINKS] ON [dbo].[EVENT_LINKS] ([EVENT_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_REG')
CREATE INDEX [IX_EVENT_REG] ON [dbo].[EVENT_REG] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_REG_1')
CREATE INDEX [IX_EVENT_REG_1] ON [dbo].[EVENT_REG] ([EVENT_LINK_EMPL]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_REG_2')
CREATE INDEX [IX_EVENT_REG_2] ON [dbo].[EVENT_REG] ([REG_NUM]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_REG_3')
CREATE INDEX [IX_EVENT_REG_3] ON [dbo].[EVENT_REG] ([REG_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_ROU')
CREATE INDEX [IX_EVENT_ROU] ON [dbo].[EVENT_ROU] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_ROU_1')
CREATE INDEX [IX_EVENT_ROU_1] ON [dbo].[EVENT_ROU] ([EXECU_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_TASK')
CREATE INDEX [IX_EVENT_TASK] ON [dbo].[EVENT_TASK] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_TASK_1')
CREATE INDEX [IX_EVENT_TASK_1] ON [dbo].[EVENT_TASK] ([TASK_DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_TASK_2')
CREATE INDEX [IX_EVENT_TASK_2] ON [dbo].[EVENT_TASK] ([TASK_AUTH]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EVENT_TASK_3')
CREATE INDEX [IX_EVENT_TASK_3] ON [dbo].[EVENT_TASK] ([TASK_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EXCIES_OPER_DEP')
CREATE INDEX [IX_EXCIES_OPER_DEP] ON [dbo].[BSO_OPER] ([DEP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EXCIES_OPER_FULL')
CREATE INDEX [IX_EXCIES_OPER_FULL] ON [dbo].[BSO_OPER] ([TYPE_BSO], [RANGE_BEGIN], [RANGE_END]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EXCIES_OPER_link_doc')
CREATE INDEX [IX_EXCIES_OPER_link_doc] ON [dbo].[BSO_OPER] ([LINK_DOC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EXPORT_BLOCKS')
CREATE CLUSTERED INDEX [IX_EXPORT_BLOCKS] ON [dbo].[EXPORT_BLOCKS] ([Link_Model], [Orders])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_EXPORT_FIELDS')
CREATE CLUSTERED INDEX [IX_EXPORT_FIELDS] ON [dbo].[EXPORT_FIELDS] ([Link_Block], [Orders])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FIN_RR_SVOD')
CREATE INDEX [IX_FIN_RR_SVOD] ON [dbo].[FIN_RR_SVOD] ([FYEAR], [FORMAT], [LINK_G_PROV]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FIN_RR_TABLE')
CREATE UNIQUE CLUSTERED INDEX [IX_FIN_RR_TABLE] ON [dbo].[FIN_RR_TABLE] ([LINK_UP], [VKR], [EKR])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FINANSE_CRITERIA')
CREATE UNIQUE INDEX [IX_FINANSE_CRITERIA] ON [dbo].[FINANSE_CRITERIA] ([NAME]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FINANSE_HEAD')
CREATE INDEX [IX_FINANSE_HEAD] ON [dbo].[FINANSE_HEAD] ([LINK_REESTR]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FINANSE_NOT_CONTRACT')
CREATE UNIQUE INDEX [IX_FINANSE_NOT_CONTRACT] ON [dbo].[gz_doc_table] ([LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_FINANSE_SHABLON')
CREATE UNIQUE INDEX [IX_FINANSE_SHABLON] ON [dbo].[FINANSE_SHABLON] ([NAME]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_ACCOUNT')
CREATE INDEX [IX_G_PROV_AP_ACCOUNT] ON [dbo].[G_PROV_AP] ([ACCOUNT]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_DEP')
CREATE INDEX [IX_G_PROV_AP_DEP] ON [dbo].[G_PROV_AP] ([DEP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_EKR')
CREATE INDEX [IX_G_PROV_AP_EKR] ON [dbo].[G_PROV_AP] ([EKR]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_EMP')
CREATE INDEX [IX_G_PROV_AP_EMP] ON [dbo].[G_PROV_AP] ([EMP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_INDATE')
CREATE INDEX [IX_G_PROV_AP_INDATE] ON [dbo].[G_PROV_AP] ([INDATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_INV')
CREATE INDEX [IX_G_PROV_AP_INV] ON [dbo].[G_PROV_AP] ([INV]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_KAU')
CREATE INDEX [IX_G_PROV_AP_KAU] ON [dbo].[G_PROV_AP] ([KAU]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_MAIN')
CREATE INDEX [IX_G_PROV_AP_MAIN] ON [dbo].[G_PROV_AP] ([DB_KR]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_OS')
CREATE INDEX [IX_G_PROV_AP_OS] ON [dbo].[G_PROV_AP] ([NOMEN]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_SUB')
CREATE INDEX [IX_G_PROV_AP_SUB] ON [dbo].[G_PROV_AP] ([SUB]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_TMC')
CREATE INDEX [IX_G_PROV_AP_TMC] ON [dbo].[G_PROV_AP] ([TMC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_UNI')
CREATE INDEX [IX_G_PROV_AP_UNI] ON [dbo].[G_PROV_AP] ([DEP_ACC]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AP_VKR')
CREATE INDEX [IX_G_PROV_AP_VKR] ON [dbo].[G_PROV_AP] ([KBK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_AVANSE_LINK_UP')
CREATE INDEX [IX_G_PROV_AVANSE_LINK_UP] ON [dbo].[G_AVANSE_TABLE] ([LINK_UP], [NUMBER]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_COMISSION_HEAD')
CREATE UNIQUE INDEX [IX_G_PROV_COMISSION_HEAD] ON [dbo].[G_PROV_COMISSION_HEAD] ([DOC_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_OBJECT_DATE')
CREATE INDEX [IX_G_PROV_OBJECT_DATE] ON [dbo].[G_PROV] ([OBJECT], [DATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV_VALUE')
CREATE CLUSTERED INDEX [IX_G_PROV_VALUE] ON [dbo].[G_PROV_VALUE] ([DOC_LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV1_REF')
CREATE CLUSTERED INDEX [IX_G_PROV1_REF] ON [dbo].[G_PROV1_REF] ([OPER_RECEIPT], [OPER_OFF])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV2')
CREATE INDEX [IX_G_PROV2] ON [dbo].[G_PROV2] ([ECON_OPER]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_G_PROV2_LINK_UP_LINK')
CREATE INDEX [IX_G_PROV2_LINK_UP_LINK] ON [dbo].[G_PROV2] ([LINK_UP], [LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_GRAPH_VID_REF')
CREATE UNIQUE INDEX [IX_GRAPH_VID_REF] ON [dbo].[GRAPH_VID_REF] ([LINK_DICTION]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_GRAPH_VID_TABLE')
CREATE UNIQUE INDEX [IX_GRAPH_VID_TABLE] ON [dbo].[GRAPH_VID_TABLE] ([LINK_UP], [NUMBER], [TYPE_DAY]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_GRAPHICS')
CREATE INDEX [IX_GRAPHICS] ON [dbo].[GRAPHICS] ([GRAPH_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_GROUP_CHARS')
CREATE UNIQUE INDEX [IX_GROUP_CHARS] ON [dbo].[GROUP_CHARS] ([LINK_CHAR], [LINK_GROUP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_HISTORY')
CREATE INDEX [IX_HISTORY] ON [dbo].[HISTORY] ([LINK_UP], [TASK_CODE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_HISTORY_INV')
CREATE INDEX [IX_HISTORY_INV] ON [dbo].[HISTORY_INV] ([LINK], [LINK_INV]) ON [INDEX]
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_INVENTORY_GRP_LIST_1')
CREATE UNIQUE INDEX [IX_INVENTORY_GRP_LIST_1] ON [dbo].[INVENTORY_GRP_LIST] ([INV_MAIN], [INV_DEPEND]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_DIS_FACE_FACE_DATE')
CREATE INDEX [IX_ITEM_DIS_FACE_FACE_DATE] ON [dbo].[ITEM_DIS_FACE] ([EMPL_LINK], [DIS_DATE] DESC, [ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_DIS_FACE_ORDER')
CREATE INDEX [IX_ITEM_DIS_FACE_ORDER] ON [dbo].[ITEM_DIS_FACE] ([ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_DIS_FACE_REASON')
CREATE INDEX [IX_ITEM_DIS_FACE_REASON] ON [dbo].[ITEM_DIS_FACE] ([REASON]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_MOVE_FACE_NEW_DATE_BEGIN')
CREATE INDEX [IX_ITEM_MOVE_FACE_NEW_DATE_BEGIN] ON [dbo].[ITEM_MOVE] ([NEW_FACE] DESC, [EMPL_LINK], [DATE_BEGIN], [DATE_END], [ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_MOVE_ORDER_LINK')
CREATE INDEX [IX_ITEM_MOVE_ORDER_LINK] ON [dbo].[ITEM_MOVE] ([ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_TRAVEL_ORDER_LINK')
CREATE INDEX [IX_ITEM_TRAVEL_ORDER_LINK] ON [dbo].[ITEM_TRAVEL] ([ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_VACATION_DATE_BEGIN')
CREATE INDEX [IX_ITEM_VACATION_DATE_BEGIN] ON [dbo].[ITEM_VACATION] ([DATE_BEGIN], [EMPL_LINK], [ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_VACATION_DATE_END')
CREATE INDEX [IX_ITEM_VACATION_DATE_END] ON [dbo].[ITEM_VACATION] ([DATE_END], [EMPL_LINK], [ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_VACATION_FACE_LINK')
CREATE INDEX [IX_ITEM_VACATION_FACE_LINK] ON [dbo].[ITEM_VACATION] ([EMPL_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_VACATION_ORDER_LINK')
CREATE INDEX [IX_ITEM_VACATION_ORDER_LINK] ON [dbo].[ITEM_VACATION] ([ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_ITEM_VACATION_TYPE')
CREATE INDEX [IX_ITEM_VACATION_TYPE] ON [dbo].[ITEM_VACATION] ([TYPE_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_JURNAL')
CREATE INDEX [IX_JURNAL] ON [dbo].[JURNAL] ([SID]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_KL_ADMIN_BS')
CREATE CLUSTERED INDEX [IX_KL_ADMIN_BS] ON [dbo].[KL_ADMIN_BS] ([Code])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_KL_IVF')
CREATE CLUSTERED INDEX [IX_KL_IVF] ON [dbo].[KL_IVF] ([Code])
GO

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_KL_KD')
CREATE CLUSTERED INDEX [IX_KL_KD] ON [dbo].[KL_KD] ([Code])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_OBJECT')
CREATE INDEX [IX_OBJECT] ON [dbo].[DICTION] ([OBJECT], [BEGINDATE]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'PK_DICTION_APP')
CREATE UNIQUE CLUSTERED INDEX [PK_DICTION_APP] ON [dbo].[DICTION_APP] ([LINK_UP], [OBJECT])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'PK_INDEX_LUO')
CREATE INDEX [PK_INDEX_LUO] ON [dbo].[DOCUMENTS_APP] ([LINK_UP], [OBJECT]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'PX_REF_PRIMARY_OBJECT')
CREATE INDEX [PX_REF_PRIMARY_OBJECT] ON [dbo].[DOCUMENTS_REF2] ([REF_PRIMARY], [OBJECT]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'X_ITEM_TRAVEL_DATE_BEGIN')
CREATE INDEX [X_ITEM_TRAVEL_DATE_BEGIN] ON [dbo].[ITEM_TRAVEL] ([DATE_BEGIN], [EMPL_LINK], [ORDER_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'X_ITEM_TRAVEL_DATE_END')
CREATE INDEX [X_ITEM_TRAVEL_DATE_END] ON [dbo].[ITEM_TRAVEL] ([DATE_END]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'X_ITEM_TRAVEL_FACE_LINK')
CREATE INDEX [X_ITEM_TRAVEL_FACE_LINK] ON [dbo].[ITEM_TRAVEL] ([EMPL_LINK]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'X_ITEM_TRAVEL_TYPE')
CREATE INDEX [X_ITEM_TRAVEL_TYPE] ON [dbo].[ITEM_TRAVEL] ([TYPE_LINK]) ON [INDEX]
GO


GO

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

--Измение колонки SUMMA таблицы SDOC_WRIT
UPDATE [dbo].[SDOC_WRIT] SET [SUMMA] =(0) WHERE [SUMMA] IS NULL
ALTER TABLE [dbo].[SDOC_WRIT] ALTER COLUMN [SUMMA] numeric(18, 4) NOT NULL 
GO

GO
/****** Объект: Коды видов операций по НДС******/

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_TYPE_OPER_NDS', 'Коды видов операций по НДС', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASSIF_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_TYPE_OPER_NDS', NAME = 'Коды видов операций по НДС', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASSIF_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_TYPE_OPER_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_FNAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_FNAME', 'Полное наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_FNAME', NAME = 'Полное наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_FNAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_ISUSED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_ISUSED', 'Используется в учете', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_ISUSED', NAME = 'Используется в учете', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_ISUSED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_TYPE_OPER_NDS_ISUSED_COM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_TYPE_OPER_NDS_ISUSED_COM', 'Используется в учете (Коментарий)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_TYPE_OPER_NDS_ISUSED_COM', NAME = 'Используется в учете (Коментарий)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_TYPE_OPER_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_TYPE_OPER_NDS_ISUSED_COM'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'TITLE', 'Коды видов операций по НДС'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'INIT_OBJECT_METHOD', 'X_SPISOK(''DICTIONARY_TYPE_OPER_NDS'')'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_TYPE_OPER_NDS", "BK_DELETE_TYPE_OPER_NDS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'SAVE_OBJECT_METHOD', 'X_SAVE(''dbo.BK_UPDATE_TYPE_OPER_NDS'', m.cAlias," CODE, NAME, FULL_NAME, ISUSED","DICTIONARY_TYPE_OPER_NDS")'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("BK_TYPE_OPER_NDS",, "DICTIONARY_TYPE_OPER_NDS")'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("BK_TYPE_OPER_NDS",, "DICTIONARY_TYPE_OPER_NDS")'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'SERVER_TABLE_NAME', 'TYPE_OPER_NDS'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'HELP_TOPIC', 'Коды видов операций по НДС'
GO
EXEC X_SET_PROP 'DICTIONARY_TYPE_OPER_NDS', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".Checked"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'CONTROLSOURCE', 'm.cAlias+".Code"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'TYPE_FIELD_DICT', 'Char(2)'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Code"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'CONTROL_NAME_EDIT', 'ATxt1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_NAME', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'TITLE', 'Полное наименование'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'CONTROLSOURCE', 'm.cAlias+".FULL_NAME"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'SHORT_CODE_OBJ', 'FULL_NAME'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FULL_NAME"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_FNAME', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'TITLE', 'Используется в учете'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'CONTROLSOURCE', 'm.cAlias + ".ISUSED"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ISUSED"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED', 'CONTROL_NAME_EDIT', 'AChkBox4'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED_COM', 'TITLE', 'Используется в учете'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED_COM', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED_COM', 'CONTROLSOURCE', 'm.cAlias + ".ISUSED_COM"'
GO
EXEC X_SET_PROP 'DIC_TYPE_OPER_NDS_ISUSED_COM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ISUSED_COM"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_TYPE_OPER_NDS', 'Смета-КС', 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 = 'BUDJ_CLASS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_TYPE_OPER_NDS')

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 = 'BUDJ_CLASS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'DICTIONARY_TYPE_OPER_NDS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'DICTIONARY_TYPE_OPER_NDS', 'Коды видов операций по НДС', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


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

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
--Добавление колонки IO таблицы ITEM_MOVE
IF COLUMNPROPERTY(object_id('[dbo].[ITEM_MOVE]'), 'IO', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[ITEM_MOVE] ADD [IO] tinyint NULL CONSTRAINT [DF_ITEM_MOVE_IO] DEFAULT ((0))
GO

--Измение колонки IO таблицы ITEM_MOVE
ALTER TABLE [dbo].[ITEM_MOVE] ALTER COLUMN [IO] tinyint NULL 
GO


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='XD_DEPARTMENT_ISUSED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'XD_DEPARTMENT_ISUSED', 'Используется в учете', 80, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'XD_DEPARTMENT_ISUSED', NAME = 'Используется в учете', ORDERS = '80', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='XD_DEPARTMENT_ISUSED'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'CONTROL_NAME_EDIT', 'aChkUSED'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ISUSED"'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'CONTROLSOURCE', 'm.cAlias + ".ISUSED"'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED', 'TITLE', 'Используется в учете'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='XD_DEPARTMENT_ISUSED_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'XD_DEPARTMENT_ISUSED_COMMENT', 'Используется в учете (Коментарий)', 81, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'XD_DEPARTMENT_ISUSED_COMMENT', NAME = 'Используется в учете (Коментарий)', ORDERS = '81', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='XD_DEPARTMENT_ISUSED_COMMENT'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED_COMMENT', 'TITLE', 'Используется в учете'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED_COMMENT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".ISUSED_COM"'
GO
EXEC X_SET_PROP 'XD_DEPARTMENT_ISUSED_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ISUSED_COM"'
GO

GO
EXEC dbo.W_SPERM_WRITE 'DICTIONARY_PLACE_ND_IMU', 'Смета-КС', 63, 0
GO


GO
EXEC dbo.W_SPERM_WRITE 'DICTIONARY_REORG_DEP', 'Смета-КС', 63, 0
GO



GO
EXEC dbo.W_SPERM_WRITE 'DICTIONARY_TAX_PERIOD', 'Смета-КС', 63, 0
GO



GO

--ОБЪЕКТЫ БД 20.06.2012
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE VIEW dbo.[RO_TOTALS_DOH_17_2011] 
AS
	select SUBSTRING(Code, 4, 17) as Code, SUBSTRING(Code, 4, 17) as CD
	from report_kbk T
	where T.code_form = 'ДОХОДЫ_2011'
         AND isnull(T.begin_date, '19000101') <= '20111231' AND ISNULL(T.end_date, '30000101') >= '20111231' 
         and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= '20111231' AND ISNULL(T1.end_date, '30000101') >= '20111231')

GO
GRANT ALL ON dbo.[RO_TOTALS_DOH_17_2011] 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].[RO_NOT_TOTALS_DOH_17_2011]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RO_NOT_TOTALS_DOH_17_2011]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE VIEW dbo.[RO_NOT_TOTALS_DOH_17_2011] 
AS
	select SUBSTRING(Code, 4, 17) as Code, SUBSTRING(Code, 4, 17) as CD
	from report_kbk T
	where T.code_form = 'ДОХОДЫ_2011'
         AND isnull(T.begin_date, '19000101') <= '20111231' AND ISNULL(T.end_date, '30000101') >= '20111231' 
         and not exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= '20111231' AND ISNULL(T1.end_date, '30000101') >= '20111231')

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

CREATE   Function dbo.BB_DDELIM_DEL(@cShablon varchar(254), @cNAME varchar(254))
RETURNS varchar(8000)
AS
BEGIN
Declare @iDopPos int,
		@cLeft varchar(1000),
		@cRight varchar(1000),
		@iLen int

set @iDopPos = patindex('%' + rtrim(ltrim(@cNAME)) + '%', @cShablon)
if @iDopPos > 0
begin
	set @cRight = Right(rtrim(@cShablon), len(rtrim(@cShablon)) - @iDopPos + 1)
	set @cLeft = left(@cShablon, @iDopPos - 1)
	while Right(@cLeft, 1) not in ('>',')', ']') and @iDopPos > 0
	begin 
		set @iDopPos = @iDopPos - 1
		set @cLeft = left(@cLeft, @iDopPos - 1)
	end
	set @cShablon = @cLeft + left(@cRight, len(rtrim(ltrim(@cNAME))))
	set @cRight = Right(rtrim(@cRight), len(@cRight) - len(rtrim(ltrim(@cNAME))))
	set @iLen = len(rtrim(ltrim(@cRight)))
	while left(@cRight, 1) in ('>',')', ']') and @iLen > 0
	begin 
		set @iLen = @iLen - 1
		set @cRight = Right(@cRight, @iLen)
	end
	set @cShablon = rtrim(@cShablon) + @cRight
end
	
RETURN @cShablon
end
GO

GRANT ALL ON dbo.BB_DDELIM_DEL 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_TOTALS_IST_20_2011]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RO_TOTALS_IST_20_2011]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE VIEW dbo.[RO_TOTALS_IST_20_2011] 
AS
	select  LEFT(CODE,3) + SUBSTRING(Code, 7, 17) as CODE, LEFT(CODE,3) + SUBSTRING(Code, 7, 17) as CD
	from report_kbk T
	where T.code_form = 'ИСТОЧНИКИ_2011'
      AND isnull(T.begin_date, '19000101') <= '20111231' AND ISNULL(T.end_date, '30000101') >= '20111231' 
         and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= '20111231' AND ISNULL(T1.end_date, '30000101') >= '20111231')

GO
GRANT ALL ON dbo.[RO_TOTALS_IST_20_2011] 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].[RT_IS_GRBS]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RT_IS_GRBS]
GO

CREATE FUNCTION dbo.RT_IS_GRBS(@LSF int)
 	RETURNS INT
AS 
BEGIN
    declare @lts int,
			@link_FO int,
			@link_FO1 int,
			@link_FO2 int,
			@link_GRBS int,
			@link int,
			@link_self int,
			@res int

	set @link_FO = -1
	set @link_FO1 = -1
	set @link_FO2 = -1
	set @link_GRBS = -1

	select @link_FO  = isnull(link,-1) from dbo.kl_budg_type where code = 'МО'
	select @link_FO1 = isnull(link,-1) from dbo.kl_budg_type where code = 'МР'
	select @link_FO2 = isnull(link,-1) from dbo.kl_budg_type where code = 'ГО'
	select @link_GRBS = isnull(link,-1) from dbo.kl_budg_type where code IN ('С', 'Р')
	select @lts = isnull(link_type_svod,-1) from dbo.report_saved_forms where link_saved_form = @LSF

	if @lts not in (@link_FO, @link_FO1, @link_FO2, @link_GRBS, -1) begin
		select @link_self = link_self from dbo.report_svod_tree where link_budg = @lts
		while @link_self is not null and @lts not in (@link_FO,@link_FO1,@link_FO2,@link_GRBS) begin
			select @link_self = link_self, @lts = isnull(link_budg,-1) from dbo.report_svod_tree where link = @link_self
		end
	end
	set @res = case when @lts in (@link_FO,@link_FO1,@link_FO2) then 0 when @lts = @link_GRBS then 1 else -1 end
 
    return @res
END
GO

GRANT EXECUTE ON dbo.RT_IS_GRBS TO PUBLIC
GO
/*
select * from report_svod_tree
select * from kl_budg_type
print dbo.RT_IS_GRBS(19295)
*/


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))
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 
	(  	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_VKR = SD.LINK_VKR 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_VKR = SD.LINK_VKR  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	
	


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

GO

CREATE VIEW dbo.SDOC_DOT_VYCHET_FIO
AS
SELECT 
	LINK = LINK_UP,
	ORDERS = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.',120),
	LINK_TAX,
	LINK_DED,
	CODE_DED = D.SNAME,
	S.LINK_PERS,
	FIO = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.',120),
	S.LINK_VKR,
	CODE_S_FIN = F.CODE,
	S.LINK_EKR,
	CODE_EKR = G.CODE,
	S.[PERCENT],
	S.SUMMA
FROM 
	[dbo].[SDOC_DOT_VYCHET] S
	INNER JOIN dbo.PERSON P ON P.LINK = S.LINK_PERS
	INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION D ON D.LINK = S.LINK_DED
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = S.LINK_VKR
	INNER JOIN dbo.KOSGU G ON G.LINK = S.LINK_EKR


GO


GRANT SELECT ON dbo.[SDOC_DOT_VYCHET_FIO] TO PUBLIC

GO

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

GO
CREATE FUNCTION dbo.minutes_to_num(@nNum numeric(18,2), @mode tinyint = 0)
-- преобразование минут в вещественное число
-- при @mode = 0 число представляет собой часы и доли часов 
-- при @mode = 1 число представляет собой часы и минуты
returns numeric(18,2)
as
BEGIN
	DECLARE @RESULT numeric(18,2)
	SET @RESULT = convert(int,@nNum / 60) + (convert(NUMERIC(18,2),convert(int,@nNum) % 60) + (@nNum-convert(int,@nNum)) ) / (CASE WHEN @mode = 0 THEN 60 ELSE 100 END)
	RETURN @RESULT
END



GO


GRANT EXECUTE ON dbo.[minutes_to_num] 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_VIEW_SUB_2010]') AND 
                 OBJECTPROPERTY(ID, N'IsView') = 1)
   DROP VIEW dbo.[RN_VIEW_SUB_2010]
GO

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

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

CREATE VIEW dbo.[RN_VIEW_SUB_2010]
AS

SELECT	7 as link,'15.01.2010' as code
union
SELECT	8 as link,'22.01.2010' as code
union
SELECT	10 as link,'29.01.2010' as code
union
SELECT	11 as link,'31.01.2010' as code
union
SELECT	12 as link,'05.02.2010' as code
union
SELECT	13 as link,'12.02.2010' as code
union
SELECT	14 as link,'19.02.2010' as code
union
SELECT	15 as link,'26.02.2010' as code
union
SELECT	16 as link,'28.02.2010' as code
union
SELECT	17 as link,'05.03.2010' as code
union
SELECT	18 as link,'12.03.2010' as code
union
SELECT	19 as link,'19.03.2010' as code
union
SELECT	20 as link,'31.03.2010' as code
union
SELECT	21 as link,'02.04.2010' as code
union
SELECT	22 as link,'09.04.2010' as code
union
SELECT	23 as link,'16.04.2010' as code
union
SELECT	24 as link,'23.04.2010' as code
union
SELECT	25 as link,'30.04.2010' as code
union
SELECT	26 as link,'07.05.2010' as code
union
SELECT	27 as link,'14.05.2010' as code
union
SELECT	28 as link,'21.05.2010' as code
union
SELECT	29 as link,'28.05.2010' as code
union
SELECT	30 as link,'04.06.2010' as code
union
SELECT	31 as link,'11.06.2010' as code
union
SELECT	32 as link,'18.06.2010' as code
union
SELECT	33 as link,'25.06.2010' as code
union
SELECT	34 as link,'02.07.2010' as code
union
SELECT	35 as link,'09.07.2010' as code
union
SELECT	36 as link,'16.07.2010' as code
union
SELECT	37 as link,'23.07.2010' as code
union
SELECT	38 as link,'30.07.2010' as code
union
SELECT	39 as link,'06.08.2010' as code
union
SELECT	40 as link,'13.08.2010' as code
union
SELECT	41 as link,'20.08.2010' as code
union
SELECT	42 as link,'27.08.2010' as code
union
SELECT	43 as link,'03.09.2010' as code
union
SELECT	44 as link,'10.09.2010' as code
union
SELECT	45 as link,'17.09.2010' as code
union
SELECT	46 as link,'24.09.2010' as code

union
SELECT	39 as link,'06.08.2010' as code
union
SELECT	40 as link,'13.08.2010' as code
union
SELECT	41 as link,'20.08.2010' as code
union
SELECT	42 as link,'27.08.2010' as code
union
SELECT	43 as link,'03.09.2010' as code
union
SELECT	44 as link,'10.09.2010' as code
union
SELECT	45 as link,'17.09.2010' as code
union
SELECT	46 as link,'24.09.2010' as code
union
SELECT	47 as link,'01.10.2010' as code
union
SELECT	48 as link,'08.10.2010' as code
union
SELECT	49 as link,'15.10.2010' as code
union
SELECT	50 as link,'22.10.2010' as code
union
SELECT	51 as link,'29.10.2010' as code
union
SELECT	52 as link,'05.11.2010' as code
union
SELECT	53 as link,'12.07.2010' as code



GO
GRANT ALL ON dbo.[RN_VIEW_SUB_2010] 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].BB_ZAYAVKA_KR_SOURCE') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].BB_ZAYAVKA_KR_SOURCE
GO

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

CREATE             VIEW BB_ZAYAVKA_KR_SOURCE
AS
Select	LINK = 1, SNAME = 'Бюджет',NAME = 'Средства бюджета' union
Select	2,'Приносящая доход деят.','Средства от приносящей доход деятельности' union
Select	3, 'Доп. финансирование', 'Средства дополнительного бюджетного финансирования' union
Select	4, 'Оперативно-розыскная деят.','Средства для финансирования мероприятий по оперативно-розыскной деятельности' union
Select	5, 'Во врем. распоняжении','Средства, поступающие во временное распоряжение бюджетных учереждений' union
Select	6, 'Средства ЮЛ', 'Cредства юридических лиц'






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

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

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

CREATE VIEW dbo.[RN_VIEW_VID_171G]
AS

SELECT	1 as link,'депозиты' as name
union
SELECT	2 as link,'облигации' as name
union
SELECT	3 as link,'векселя' as name
union
SELECT	4 as link,'акции' as name
union
SELECT	5 as link,'уставные фонды' as name
union
SELECT	6 as link,'доли' as name
union
SELECT	7 as link,'паи' as name
union
SELECT	8 as link,'участие в государственных (муниципальных) учреждениях' as name
union
SELECT	9 as link,'иные формы участия в капитале' as name


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

GO
CREATE FUNCTION dbo.StatusImageByDoc (@varKSCurrentDate DATETIME)
RETURNS @RES TABLE (LINK INT, StatusImage TINYINT)
AS
BEGIN

INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage = 0
FROM 
	dbo.DOCUMENTS D
WHERE
	NOT EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)	

--
INSERT INTO @RES(LINK, StatusImage)	
SELECT
	D.LINK, StatusImage = 2
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)

-- документ исполнен	
INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage = 3
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	NOT EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)
	AND
	D.ISP = 1

-- документ зарегистрирован, поручений нет
INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage = 1
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	NOT EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)
	AND
	D.ISP <> 1
	AND
	NOT EXISTS(SELECT NULL FROM dbo.EVENT_TASK WHERE LINK_DOC = D.LINK)

-- документ зарегистрирован, находится на контроле
INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage = 2
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	NOT EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)
	AND
	D.ISP <> 1
	AND
	EXISTS(SELECT NULL FROM dbo.EVENT_TASK WHERE LINK_DOC = D.LINK)	
	AND
	( SELECT MIN(SROK_DATE)
		  FROM dbo.EVENT_EXECUTORS
		  WHERE (LINK_DOC = D.LINK) AND (ISP = 0) AND (CHECKED = 1)	
		 ) IS NULL 

-- документ не исполнен, проверим срок
INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage = 5 
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	NOT EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)
	AND
	D.ISP <> 1
	AND
	EXISTS(SELECT NULL FROM dbo.EVENT_TASK WHERE LINK_DOC = D.LINK)	
	AND
	( SELECT MIN(SROK_DATE)
		  FROM dbo.EVENT_EXECUTORS
		  WHERE (LINK_DOC = D.LINK) AND (ISP = 0) AND (CHECKED = 1)	
		 ) IS NOT NULL 		
	AND
	( SELECT MIN(SROK_DATE)
		  FROM dbo.EVENT_EXECUTORS
		  WHERE (LINK_DOC = D.LINK) AND (ISP = 0) AND (CHECKED = 1)	
		 ) <= @varKSCurrentDate -- EXPIRED

-- документ не исполнен, проверим срок
INSERT INTO @RES(LINK, StatusImage)
SELECT
	D.LINK, StatusImage =  4 -- WARNING
FROM 
	dbo.DOCUMENTS D
WHERE
	EXISTS(SELECT NULL FROM dbo.EVENT_REG WHERE LINK_DOC = D.LINK)
	AND
	NOT EXISTS( SELECT NULL 
			FROM 
				dbo.EVENT_CONTROL EC 
				INNER JOIN dbo.WF_DOCCONTROL DC ON EC.LINK_DOC = D.LINK AND EC.CONTROL_LINK = DC.LINK AND DC.NO_STAT = 1)
	AND
	D.ISP <> 1
	AND
	EXISTS(SELECT NULL FROM dbo.EVENT_TASK WHERE LINK_DOC = D.LINK)	
	AND
	( SELECT MIN(SROK_DATE)
		  FROM dbo.EVENT_EXECUTORS
		  WHERE (LINK_DOC = D.LINK) AND (ISP = 0) AND (CHECKED = 1)	
		 ) IS NOT NULL 		
	AND
	( SELECT MIN(SROK_DATE)
		  FROM dbo.EVENT_EXECUTORS
		  WHERE (LINK_DOC = D.LINK) AND (ISP = 0) AND (CHECKED = 1)	
		 )  > @varKSCurrentDate -- WARNING


RETURN 

END

GO


GRANT SELECT ON dbo.[StatusImageByDoc] 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_PRINT_COUNT_TABLES]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RO_PRINT_COUNT_TABLES]
GO








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

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

CREATE     VIEW dbo.RO_PRINT_COUNT_TABLES
AS

select '0503128G' as Code_Form, '20091231' as Start_Date, 1 as Count_Tables
union
select '0503128M' as Code_Form, '20100101' as Start_Date, 1 as Count_Tables
union
select '0503128M' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503128G' as Code_Form, '20101231' as Start_Date, 1 as Count_Tables
union
select '0503128G' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '574' as Code_Form, '20100101' as Start_Date, 1 as Count_Tables
union
select '574' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '574' as Code_Form, '20120101' as Start_Date, 1 as Count_Tables
union
select '0532161' as Code_Form, '20100401' as Start_Date, 3 as Count_Tables
union
select '0503125M' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503125M_AD' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '425M' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503125G' as Code_Form, '20101231' as Start_Date, 1 as Count_Tables
union
select '0503125G' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '425G' as Code_Form, '20101231' as Start_Date, 1 as Count_Tables
union
select '425G' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503125M_R' as Code_Form, '20091201' as Start_Date, 1 as Count_Tables
union
select '0503725M' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503725M' as Code_Form, '20120101' as Start_Date, 1 as Count_Tables
union
select '0503725G' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select 'PO_BA' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '(86н)001' as Code_Form, '20111101' as Start_Date, 1 as Count_Tables
union
select 'RS_14н_new' as Code_Form, '20110101' as Start_Date, 3 as Count_Tables
union
select '(86н)002_398' as Code_Form, '20111201' as Start_Date, 2 as Count_Tables
union
select '0503769G' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '0503769G_D' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '0503769G_K' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '0503769M_D' as Code_Form, '20120101' as Start_Date, 1 as Count_Tables
union
select '0503769M_K' as Code_Form, '20120101' as Start_Date, 1 as Count_Tables
union
select '0503125G_AD' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select '0503125M_R' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503125G_R' as Code_Form, '20110101' as Start_Date, 1 as Count_Tables
union
select '0503125GS' as Code_Form, '20111231' as Start_Date, 1 as Count_Tables
union
select 'rk_5_5_5' as Code_Form, '20120101' as Start_Date, 1 as Count_Tables


GO
GRANT ALL ON dbo.[RO_PRINT_COUNT_TABLES] 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].[rn_get_ppo_code]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].rn_get_ppo_code
GO

-- получение кода ППО по ОКАТО

CREATE FUNCTION dbo.rn_get_ppo_code  
(@cCode VARCHAR(100))

returns varchar(4000)
as
    begin
      declare @cstr varchar(1000), @cINN VARCHAR(100) 
      SET @cstr = ''
      SELECT @cstr = CODE FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_PPO' AND CODE_STR = @cCode
       
      return @cstr
    end
GO
GRANT ALL ON dbo.rn_get_ppo_code 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.[RN_VIEW_86n_SERVICE]') AND 
                 OBJECTPROPERTY(ID, N'IsView') = 1)
   DROP VIEW dbo.RN_VIEW_86n_SERVICE
GO

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

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

CREATE VIEW dbo.RN_VIEW_86n_SERVICE
AS

SELECT A.LINK, A.CODE, A.NAME AS PPO_NAME, A.CODE_STR AS PPO, A.add_info AS SERVICE_NAME, A.LONG_NAME AS SERVICE_NUMBER,
B.NAME AS e_name, B.Code_str AS e_date, B.add_info AS e_type, B.LONG_NAME AS e_number,
C.LONG_NAME AS e_author, C.ADD_INFO AS field,
D.LONG_NAME AS CATEGORY, A.[property] 
  FROM report_kbk A INNER JOIN report_kbk B ON A.CODE = B.CODE INNER JOIN report_kbk C ON A.CODE = C.CODE
INNER JOIN report_kbk D ON A.CODE = D.CODE
WHERE A.code_form = 'SPR_86n_SERVICE'
AND B.code_form = 'SPR_86n_SERVICE_2'
AND C.code_form = 'SPR_86n_SERVICE_3'
AND D.code_form = 'SPR_86n_SERVICE_4'

GO
GRANT ALL ON dbo.RN_VIEW_86n_SERVICE TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- select * from RN_VIEW_86n_SERVICE
--SELECT * FROM R_398_POTREB


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
© Кейсистемс (Keysystems), 2012
*/
CREATE  FUNCTION dbo.RO_EXP(@vcStr varchar(8000)) 
RETURNS VARCHAR(8000)
AS
BEGIN

	RETURN CASE WHEN isnull(@vcStr, '') = '' THEN '-' ELSE RTRIM(isnull(@vcStr, '')) END 
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT ALL ON dbo.RO_EXP 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.[RT_VIEW_RRO_NORM_L_1]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[RT_VIEW_RRO_NORM_L_1]

GO



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

********************************************************************************


*/
CREATE VIEW [dbo].[RT_VIEW_RRO_NORM_L_1]
AS
SELECT	[LINK],
		[NAME] = replace(ltrim(rtrim(isnull([TYPE],''))),'"','``')+' от '+ltrim(rtrim(isnull([DATE],'')))+' № '+ltrim(rtrim(isnull([NUMB],'')))+' "'+ltrim(rtrim(isnull([NAME],'')))+'"',
		[DATE], 
		[NUMB],
		[D_BE]  = case when len(isnull([N_DB],''))>0 then cast([N_DB] as varchar) else 'не установлен' end + ' - ' + case when len(isnull([N_DE],''))>0 then cast([N_DE] as varchar) else 'не установлен' end,
		[TYPE], 
		[N_DB],
		[N_DE],
		[N1] = ISNULL([N_ABZ],''), 
		[N2] = ISNULL([N_POD], ''),  
		[N3] = ISNULL([N_PUN], ''),  
		[N4] = ISNULL([N_CHA], ''),  
		[N5] = ISNULL([N_STA], '')
FROM  dbo.REPORT_DICTION_RRO_NORM
WHERE whose = 'L'
union
SELECT  [LINK]  = 0,
		[NAME]  = '',
		[DATE]  = '', 
		[NUMB]  = '',
		[D_BE]  = '',
		[TYPE]  = '', 
		[N_DB]  = '',
		[N_DE]  = '',
		[N1] = '', 
		[N2] = '',  
		[N3] = '',  
		[N4] = '',  
		[N5] = ''  
GO


GRANT SELECT ON dbo.[RT_VIEW_RRO_NORM_L_1] 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.[RT_VIEW_RRO_NORM_F_1]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[RT_VIEW_RRO_NORM_F_1]

GO



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

********************************************************************************


*/
CREATE VIEW [dbo].[RT_VIEW_RRO_NORM_F_1]
AS
SELECT	[LINK], 
		[NAME] = replace(ltrim(rtrim([TYPE])),'"','``')+' от '+ltrim(rtrim([DATE]))+' № '+ltrim(rtrim([NUMB]))+' "'+ltrim(rtrim([NAME]))+'"',
		[DATE],-- = convert(datetime, [DATE], 104), 
		[NUMB],
		[D_BE]  = case when len(isnull([N_DB],''))>0 then cast([N_DB] as varchar) else 'не установлен' end + ' - ' + case when len(isnull([N_DE],''))>0 then cast([N_DE] as varchar) else 'не установлен' end,
		[TYPE], 
		[N_DB],-- = convert(datetime, [N_DB], 104),
		[N_DE],-- = convert(datetime, [N_DE], 104),
		[N1] = ISNULL([N_ABZ],''), 
		[N2] = ISNULL([N_POD], ''),  
		[N3] = ISNULL([N_PUN], ''),  
		[N4] = ISNULL([N_CHA], ''),  
		[N5] = ISNULL([N_STA], ''),
      IS_SUB,
      IS_MO
FROM  dbo.REPORT_DICTION_RRO_NORM
WHERE whose = 'F'
union
SELECT  [LINK]  = 0,
		[NAME]  = '',
		[DATE]  = NULL, 
		[NUMB]  = '',
		[D_BE]  = '',
		[TYPE]  = '', 
		[N_DB]  = NULL,
		[N_DE]  = NULL,
		[N1] = '', 
		[N2] = '',  
		[N3] = '',  
		[N4] = '',  
		[N5] = '',
      IS_SUB = 1,
      IS_MO = 1 
GO


GRANT SELECT ON dbo.[RT_VIEW_RRO_NORM_F_1] TO PUBLIC

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
select NAME,D_BE, N1, N2, N3, N4, N5, TYPE, NUMB, DATE,N_DB, N_DE from [RT_VIEW_RRO_NORM_F_1]
*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

GO



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

********************************************************************************


*/
CREATE VIEW [dbo].[RT_VIEW_RRO_NORM_S_1]
AS
SELECT	[LINK],
		[NAME] = replace(ltrim(rtrim([TYPE])),'"','``')+' от '+ltrim(rtrim([DATE]))+' № '+ltrim(rtrim([NUMB]))+' "'+ltrim(rtrim([NAME]))+'"',
		[DATE], 
		[NUMB],
		[D_BE]  = case when len(isnull([N_DB],''))>0 then cast([N_DB] as varchar) else 'не установлен' end + ' - ' + case when len(isnull([N_DE],''))>0 then cast([N_DE] as varchar) else 'не установлен' end,
		[TYPE], 
		[N_DB],
		[N_DE],
		[N1] = ISNULL([N_ABZ],''), 
		[N2] = ISNULL([N_POD], ''),  
		[N3] = ISNULL([N_PUN], ''),  
		[N4] = ISNULL([N_CHA], ''),  
		[N5] = ISNULL([N_STA], ''),
      IS_SUB,
      IS_MO
FROM  dbo.REPORT_DICTION_RRO_NORM
WHERE whose = 'S'
union
SELECT  [LINK]  = 0,
		[NAME]  = '',
		[DATE]  = '', 
		[NUMB]  = '',
		[D_BE]  = '',
		[TYPE]  = '', 
		[N_DB]  = '',
		[N_DE]  = '',
		[N1] = '', 
		[N2] = '',  
		[N3] = '',  
		[N4] = '',  
		[N5] = '',
      IS_SUB = 1,
      IS_MO = 1

GO


GRANT SELECT ON dbo.[RT_VIEW_RRO_NORM_S_1] TO PUBLIC

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from [RT_VIEW_RRO_NORM_S_1]

 "NAME,D_BE, TYPE, NUMB, DATE,N_DB, N_DE", "COL5,COL6,COL12,COL13,COL14,COL15,COL16"
*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE  TRIGGER dbo.G_PROV_OSNOV_DELETE ON G_PROV
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		IF EXISTS(SELECT * FROM G_PROV_AP WHERE AP1 
				 IN (SELECT LINK FROM OSNOV WHERE LINK_G_PROV IN (SELECT LINK FROM DELETED)
				        AND TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1)))  or
		   EXISTS(SELECT * FROM ZAYAVKA_KR_OSNOV WHERE LINK_OSNOV 
				 IN (SELECT LINK FROM OSNOV WHERE LINK_G_PROV IN (SELECT LINK FROM DELETED)
				        AND TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1))) or
		   EXISTS(SELECT * FROM G_AVANSE_TABLE WHERE OSNOV 
				 IN (SELECT LINK FROM OSNOV WHERE LINK_G_PROV IN (SELECT LINK FROM DELETED)
				        AND TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1)))
			BEGIN
				raiserror('Документ не может быть удален. Используется в качестве основания!',11,1)
				ROLLBACK
				RETURN		
			END
		ELSE 
			IF EXISTS(SELECT * FROM OSNOV WHERE LINK_G_PROV IN (SELECT LINK FROM DELETED)
					AND TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1))

			DELETE FROM dbo.OSNOV WHERE LINK_G_PROV IN (SELECT [LINK] FROM DELETED)
	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.[ConcatEmplPhoneValues]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[ConcatEmplPhoneValues]

GO
CREATE FUNCTION dbo.ConcatEmplPhoneValues (@dataType int,@phoneType int, @empl_link int)
RETURNS varchar(256)
BEGIN
	DECLARE @CURSOR CURSOR
	/*Заполняем курсор*/

	IF @dataType = 1
	BEGIN
		IF @phoneType in (1,2,3)		
		BEGIN
			SET @CURSOR  = CURSOR SCROLL
			FOR
			SELECT  number
			FROM  empl_phone WHERE  empl_link = @empl_link AND number <>'' AND type = @phoneType 
		END
	END
	IF @dataType = 2
	BEGIN
		SET @CURSOR  = CURSOR SCROLL
		FOR
		SELECT  email
		FROM  empl_phone WHERE  empl_link = @empl_link AND email <>''
	END

	/*Открываем курсор*/
	OPEN @CURSOR
	/*Выбираем первую строку*/
	declare @values varchar(256)
	set @values = ''
	
	declare @value varchar(256)
	FETCH NEXT FROM @CURSOR INTO @value
	/*Выполняем в цикле перебор строк*/
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @values = @values + RTRIM(@value) +'; '
	/*Выбираем следующую строку*/
	FETCH NEXT FROM @CURSOR INTO @value
	END
	CLOSE @CURSOR

	RETURN  RTRIM(@values)
END


GO


GRANT EXECUTE ON dbo.[ConcatEmplPhoneValues] TO PUBLIC

GO


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


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

GO

CREATE VIEW dbo.FAST_EXEC AS
/*Справочни свойств
CODE - код подзадачи, для нужд которой делается эта подстановка
NAME - код свойства для использования в построителях выражений
COMMENTS - описание функции
VALUES - Вычислямое выражение
SOURCE - Откуда получать данные для вычисляемого выражения
*/
-----------ПОДСТАНОВКИ ДЛЯ ВЫГРУЗКИ ЗАРПЛАТЫ НА ПЛАСТИКОВЫЕ КАРТОЧКИ
SELECT 'PAYROLL' as CODE, 'Наим_орг' AS [NAME], 'Наименование организации' as [COMMENTS], 'ALLT(NVL(DEP_NAME,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'ИНН_Орг' AS [NAME], 'ИНН текущей организации' as [COMMENTS], 'ALLT(NVL(DEP_INN,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'КПП_Орг' AS [NAME], 'КПП текущей организации' as [COMMENTS], 'ALLT(NVL(DEP_KPP,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'ОКПО_орг' AS [NAME], 'ОКПО организации' as [COMMENTS], 'ALLT(NVL(DEP_OKPO,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'ОГРН_орг' AS [NAME], 'ОГРН организации' as [COMMENTS], 'ALLT(NVL(DEP_OGRN,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_выгр' AS [NAME], 'Порядковый номер выгрузки файла реестра на зачисление денежных средств' as [COMMENTS], 'ALLT(STR(NVL(EXRT,1)))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_выгр_день' AS [NAME], 'Порядковый номер за день выгрузки файла реестра на зачисление денежных средств для данной организации' as [COMMENTS], 'ALLT(STR(NVL(EXRT_D,1)))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_вед' AS [NAME], 'Номер ведомости' as [COMMENTS], 'ALLT(NVL(DOC_NUM,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Число_зап' AS [NAME], 'Число записей в ведомости' as [COMMENTS], 'ALLT(STR(NVL(COUNT_OP,"")))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Расчет_мес' AS [NAME], 'Расчетный месяц' as [COMMENTS], 'ALLT(NVL(month,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Расчет_год' AS [NAME], 'Расчетный год' as [COMMENTS], 'ALLT(NVL(YEAR,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'ЭКР' AS [NAME], 'ЭКР' as [COMMENTS], 'ALLT(NVL(m.cCODE_EKR,""))' as [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Наим_банка' AS [NAME], 'Наименование банка' as [COMMENTS], 'ALLT(NVL(BANK_NAME,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'БИК_банка' AS [NAME], 'БИК банка' as [COMMENTS], 'ALLT(NVL(BIK,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_ОСБ' AS [NAME], 'Номер ОСБ' as [COMMENTS], 'ALLT(NVL(NOSB,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_фил' AS [NAME], 'Номер филиала банка' as [COMMENTS], 'ALLT(NVL(NFSB,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Ном_дог' AS [NAME], 'Номер договора с банком' as [COMMENTS], 'ALLT(NVL(NDOG_SB,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Вид_карты' AS [NAME], 'Вид карты' as [COMMENTS], 'ALLT(NVL(CARD_NAME,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Код_вида_карты' AS [NAME], 'Код вида карты' as [COMMENTS], 'ALLT(NVL(CARD_CODE,""))' as [VALUES], 'C_DATA' as SOURCE
UNION
SELECT 'PAYROLL' as CODE, 'Постфикс_карты' AS [NAME], 'Постфикс карты' as [COMMENTS], 'ALLT(NVL(CARD_POSTF,""))' as [VALUES], 'C_DATA' as SOURCE
-----------ОБЩИЕ ПОДСТАНОВКИ
UNION
SELECT 'ALL' as CODE, 'День_как_ДД' AS [NAME], 'День сегодняшней даты в формате ДД (День)' as [COMMENTS], 'RIGHT("0"+ALLTRIM(STR(DAY(DATE()))),2)' [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'ALL' as CODE, 'Месяц_как_ММ' AS [NAME], 'Месяц сегодняшней даты в формате ММ (Месяц)' as [COMMENTS], 'RIGHT("0"+ALLTRIM(STR(MONTH(DATE()))),2)' [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'ALL' as CODE, 'Год_как_ГГГГ' AS [NAME], 'Год сегодняшней даты в формате ГГГГ (Год)' as [COMMENTS], 'ALLTRIM(STR(YEAR(DATE())))' [VALUES], 'MEMORY' as SOURCE
-----------СПЕЦИАЛЬНЫЕ ОБЩИЕ ФУНКЦИИ
UNION
SELECT 'SPEC' as CODE, 'РОВН_Л(выражение;длина_всего;"символ_заполнитель")' AS [NAME], 'Выровнить длину выражения, добавляя символы слева' as [COMMENTS], 'PADL("@1",@2,@3)' [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'SPEC' as CODE, 'РОВН_П(выражение;длина_всего;"символ_заполнитель")' AS [NAME], 'Выровнить длину выражения, добавляя символы справа' as [COMMENTS], 'PADR("@1",@2,@3)' [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'SPEC' as CODE, 'СЛЕВА(выражение;число_символов)' AS [NAME], 'Возвращает из символьного выражения заданное число символов, начиная с самого левого' as [COMMENTS], 'LEFT("@1",@2)' [VALUES], 'MEMORY' as SOURCE
UNION
SELECT 'SPEC' as CODE, 'СПРАВА(выражение;число_символов)' AS [NAME], 'Возвращает заданное число символов с правого конца символьной строки' as [COMMENTS], 'RIGHT("@1",@2)' [VALUES], 'MEMORY' as SOURCE
-----------Наименование организации для документов
UNION
SELECT 'DEP_NAME' as CODE, 'Наим_орг' AS [NAME], 'Наименование организации' as [COMMENTS], 'DEP_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Наим_орг_полн' AS [NAME], 'Наименование организации полное' as [COMMENTS], 'DEP_АNAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ИНН_орг' AS [NAME], 'ИНН текущей организации' as [COMMENTS], 'DEP_INN' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'КПП_орг' AS [NAME], 'КПП текущей организации' as [COMMENTS], 'DEP_KPP' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Счет' AS [NAME], 'Код счета' as [COMMENTS], 'ACC_CODE' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Счет_лиц' AS [NAME], 'Код лицевого счета в формате: "Л/C 00000000000"' as [COMMENTS], 'ACC_CODE' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ОФК' AS [NAME], 'Наименование отделения федерального казначейства(лицевой счет)' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ИНН_ОФК' AS [NAME], 'ИНН отделения федерального казначейства(лицевой счет)' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ОФК_полн' AS [NAME], 'Полное наименование отделения федерального казначейства полное(лицевой счет)' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Счет_ОФК' AS [NAME], 'Наименование счета ОФК в банке' as [COMMENTS], 'TOFK_FNAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Наим_банка' AS [NAME], 'Наименование банка' as [COMMENTS], 'BANK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'БИК_банка' AS [NAME], 'БИК банка' as [COMMENTS], 'BANK_BIK' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Филиал_банка' AS [NAME], 'Филиал банка' as [COMMENTS], 'BANK_FILIAL' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ОФК_орг' AS [NAME], 'Наименование отделения федерального казначейства(организация)' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'ОФК_полн_орг' AS [NAME], 'Полное наименование отделения федерального казначейства полное(организация)' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION
SELECT 'DEP_NAME' as CODE, 'Префикс_орг' AS [NAME], 'Префикс для организации' as [COMMENTS], 'TOFK_NAME' as [VALUES], '' as SOURCE
UNION

--Назначение платежа в ПП
SELECT 'PAY_LS_BK' as CODE, 'Счет' AS [NAME], 'Счет (лицевой\расчетный)' as [COMMENTS], 'DEP_ACC' as [VALUES], '' as SOURCE
UNION
SELECT 'PAY_LS_BK' as CODE, 'БК' AS [NAME], 'Бюджетная классификация' as [COMMENTS], 'BK' as [VALUES], '' as SOURCE
UNION
SELECT 'PAY_LS_BK' as CODE, 'БО' AS [NAME], '№ бюджетного обязательства' as [COMMENTS], 'BO' as [VALUES], '' as SOURCE
UNION
SELECT 'PAY_LS_BK' as CODE, 'Перевод_строки' AS [NAME], 'Перевод строки' as [COMMENTS], 'PS' as [VALUES], '' as SOURCE
UNION
SELECT 'PAY_LS_BK' as CODE, 'Руб' AS [NAME], 'Сумма документа - рубли' as [COMMENTS], 'RUB' as [VALUES], '' as SOURCE
UNION
SELECT 'PAY_LS_BK' as CODE, 'Коп' AS [NAME], 'Сумма документа - копейки' as [COMMENTS], 'KOP' as [VALUES], '' as SOURCE
UNION
--Классификация в ПП
SELECT 'KL_BK' as CODE, 'КБК' AS [NAME], 'Код бюджетной классификации' as [COMMENTS], 'KBK' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'КБКР' AS [NAME], 'Код бюджетной классификации c разделителем .' as [COMMENTS], 'KBK' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'КБК_наим' AS [NAME], 'Наименование бюджетной классификации' as [COMMENTS], 'KBK' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'АДМ' AS [NAME], 'Код администратора(ведомстава)' as [COMMENTS], 'ADM' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'АДМ_наим' AS [NAME], 'Наименование администратора(ведомстава)' as [COMMENTS], 'ADM' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'Раздел' AS [NAME], 'Код раздела\подраздела' as [COMMENTS], 'DIV' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'Раздел' AS [NAME], 'Наименование раздела\подраздела' as [COMMENTS], 'DIV' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ЦС' AS [NAME], 'Код целевой статьи' as [COMMENTS], 'TI' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ЦС_наим' AS [NAME], 'Наименование целевой статьи' as [COMMENTS], 'TI' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ВР' AS [NAME], 'Код вида расхода' as [COMMENTS], 'EXP' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ВР_наим' AS [NAME], 'Наименование вида расхода' as [COMMENTS], 'EXP' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ЭКР' AS [NAME], 'Код экономической статьи расхода' as [COMMENTS], 'EKR' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ЭКР_наим' AS [NAME], 'Наименование экономической статьи расхода' as [COMMENTS], 'EKR' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'СГУ' AS [NAME], 'Код операции сектора государственного управления' as [COMMENTS], 'SGU' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'СГУ_наим' AS [NAME], 'Наименование операции сектора государственного управления' as [COMMENTS], 'SGU' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ДОП_КЛ' AS [NAME], 'Код дополнительной классификации' as [COMMENTS], 'DOP_CL' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ДОП_КЛ_наим' AS [NAME], 'Наименование дополнительной классификации' as [COMMENTS], 'DOP_CL' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'ДОП_КЛ_наим' AS [NAME], 'Наименование дополнительной классификации' as [COMMENTS], 'DOP_CL' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'Руб' AS [NAME], 'Сумма проводки - рубли' as [COMMENTS], 'RUB' as [VALUES], '' as SOURCE
UNION
SELECT 'KL_BK' as CODE, 'Коп' AS [NAME], 'Сумма проводки - копейки' as [COMMENTS], 'KOP' as [VALUES], '' as SOURCE
--Исполнитель
UNION
SELECT 'USER' as CODE, 'ИП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в именительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'РП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в родительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ДП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в дательном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ВП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в винительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ТП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в творительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ПП_Исп_ФИО' AS [NAME], 'Фамилия И.О. исполнителя в предложном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ИП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в именительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'РП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в родительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ДП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в дательном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ВП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в винительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ТП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в творительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ПП_Исп_Фам' AS [NAME], 'Фамилия исполнителя в предложном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ИП_Исп_Имя' AS [NAME], 'Имя исполнителя в именительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'РП_Исп_Имя' AS [NAME], 'Имя исполнителя в родительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ДП_Исп_Имя' AS [NAME], 'Имя исполнителя в дательном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ВП_Исп_Имя' AS [NAME], 'Имя исполнителя в винительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ТП_Исп_Имя' AS [NAME], 'Имя исполнителя в творительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ПП_Исп_Имя' AS [NAME], 'Имя исполнителя в предложном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ИП_Исп_Отч' AS [NAME], 'Отчество исполнителя в именительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'РП_Исп_Отч' AS [NAME], 'Отчество исполнителя в родительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ДП_Исп_Отч' AS [NAME], 'Отчество исполнителя в дательном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ВП_Исп_Отч' AS [NAME], 'Отчество исполнителя в винительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ТП_Исп_Отч' AS [NAME], 'Отчество исполнителя в творительном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE
UNION
SELECT 'USER' as CODE, 'ПП_Исп_Отч' AS [NAME], 'Отчество исполнителя в предложном падеже' as [COMMENTS], '' as [VALUES], '' as SOURCE

--НДС в назначение платежа в ПП
UNION
SELECT 'NDS' as CODE, 'Процент' AS [NAME], 'Процент НДС' as [COMMENTS], 'DEP_ACC' as [VALUES], '' as SOURCE
UNION
SELECT 'NDS' as CODE, 'Руб' AS [NAME], 'Сумма документа - рубли' as [COMMENTS], 'RUB' as [VALUES], '' as SOURCE
UNION
SELECT 'NDS' as CODE, 'Коп' AS [NAME], 'Сумма документа - копейки' as [COMMENTS], 'KOP' as [VALUES], '' as SOURCE
UNION
SELECT 'NDS' as CODE, 'НДС_Руб' AS [NAME], 'Сумма НДС - рубли' as [COMMENTS], 'RUB' as [VALUES], '' as SOURCE
UNION
SELECT 'NDS' as CODE, 'НДС_Коп' AS [NAME], 'Сумма НДС - копейки' as [COMMENTS], 'KOP' as [VALUES], '' as SOURCE
UNION
SELECT 'NDS' as CODE, 'Перевод_строки' AS [NAME], 'Перевод строки' as [COMMENTS], 'PS' as [VALUES], '' as SOURCE

--Кадры. Приказ
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Дата_Приказа' AS [NAME], 'Дата приказа' as [COMMENTS], 'ISNULL(CONVERT(varchar(10),Date,104),'''')' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Номер_Приказа' AS [NAME], 'Номер приказа' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(NUMBER,'''')))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Новый_отдел' AS [NAME], 'Новый отдел' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(NEW_SUBDIV,'''')))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Новая_должность' AS [NAME], 'Новая должность' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(NEW_POST,'''')))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Ставка' AS [NAME], 'Ставка' as [COMMENTS], 'LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL(NUM_STAKE,0))))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Дата_начала_работы' AS [NAME], 'Дата начала работы' as [COMMENTS], 'ISNULL(CONVERT(varchar(10),DATE_BEGIN, 104),'''')' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDERS' as CODE, 'Оклад' AS [NAME], 'Оклад' as [COMMENTS], 'LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(OKLAD,0))))' as [VALUES], '' as SOURCE


--Кадры. Пункты постановления, распоряжения для приказа о приёме
--SUBDIV POST
UNION
SELECT 'KADRY_ORDER_TYP1' as CODE, 'ФИО' AS [NAME], 'Фамилия Имя Отчество' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(FIO,'''')))' as [VALUES], '' as SOURCE

--Кадры. Пункты постановления, распоряжения для приказа о переводе на другую должность
UNION
SELECT 'KADRY_ORDER_TYP2' as CODE, 'ФИО' AS [NAME], 'Фамилия Имя Отчество' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(FIO,'''')))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDER_TYP2' as CODE, 'Отдел' AS [NAME], 'Отдел' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(SUBDIV,'''')))' as [VALUES], '' as SOURCE
UNION
SELECT 'KADRY_ORDER_TYP2' as CODE, 'Должность' AS [NAME], 'Должность' as [COMMENTS], 'LTRIM(RTRIM(ISNULL(POST,'''')))' as [VALUES], '' as SOURCE

--Функции SQL
UNION
SELECT 'SQL_FUNC' as CODE, 'Склон_Стр(Строка,Ном_Падежа)' AS [NAME], 'Просклонять строку в падеже (Строка,Номер_Падежа)' as [COMMENTS], 'dbo.SklonStr(@1,@2)' as [VALUES], '' as SOURCE

GO


GRANT SELECT ON dbo.[FAST_EXEC] TO PUBLIC

GO

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

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

RETURN

	-- Форматы для налога на прибыль --
	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.02 (с 01.01.2009 г.)', PROC_NAME = 'BK_EXPORT_F1151006', 
		PRG_SKRIPT = CONVERT(VARCHAR(100),''),
		DIR = 'IMNS',
		TEST_PROC = ''
--		TEST_PROC = 'BK_TEST_EXP_F1152027'
	UNION ALL
	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.03 (с 01.01.2011 г.)', PROC_NAME = 'BK_EXPORT_F1151006_503', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	UNION ALL
	-- Форматы для транспортного налога --
	SELECT FORM_CODE = 'ND_TN',
		FNAME = 'Формат 4.01 (с 01.01.2007 г.)', PROC_NAME = 'BK_EXPORT_F1152004', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152027'

	UNION ALL

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

	UNION ALL

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

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

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

	UNION ALL
	-- Формат выгрузки П-4 --
	SELECT FORM_CODE = '0606010',
		FNAME = 'Формат выгрузки формы П-4 для Росстата', PROC_NAME = 'SK_EXPORT_F0606010', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''


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

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


GO


GRANT SELECT ON dbo.[BK_VIEW_EXPORT_FORMAT_NALOG_FN] TO PUBLIC

GO

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

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW [dbo].KU_EMPL_PHONE
AS
SELECT
	EP.LINK,
	EP.EMPL_LINK,
	EP.CODE,
	EP.NUMBER,
	EP.[ADD],
	EP.TYPE,
	EP.EMAIL
FROM EMPL_PHONE EP






GO


GRANT SELECT ON dbo.[KU_EMPL_PHONE] TO PUBLIC

GO


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


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

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW [dbo].RO_KBK_HIST
AS 
SELECT 
KH.LINK_UP,
KH.NAME,
KH.LONG_NAME,
[DATE_BEGIN] = KH.DATE,
[DATE_END] = ISNULL((SELECT TOP 1 DATE FROM dbo.[REPORT_KBK_HIST] 
 				 WHERE LINK_UP = KH.LINK_UP AND DATE > KH.DATE ORDER BY DATE ASC)-1,CONVERT(DATETIME,'30000101'))
FROM dbo.[REPORT_KBK_HIST] KH



GO


GRANT SELECT ON dbo.[RO_KBK_HIST] TO PUBLIC

GO


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


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

GO
CREATE VIEW dbo.DICTIONARY_COUNTRY
AS

SELECT	LINK,
	CONVERT (VARCHAR (3), CODE1) AS CODE,
	CONVERT (VARCHAR (3), CODE1) AS CODE1,
	CONVERT (VARCHAR (3), CODE2) AS CODE2,
	CONVERT (VARCHAR (3), CODE3) AS CODE3,
	[NAME],
	FULL_NAME
FROM dbo.KL_COUNTRY

GO


GRANT SELECT ON dbo.[DICTIONARY_COUNTRY] TO PUBLIC

GO


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


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

GO
CREATE FUNCTION dbo.QUOTED_STR(@WHERE VARCHAR(4000))
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @TMP1 VARCHAR(4000), @TMP2 VARCHAR(4000)

DECLARE @LEN INT

SET @TMP1 = ''
SET @TMP2 = LTRIM(RTRIM(@WHERE))
WHILE PATINDEX('%,%', @TMP2) > 0
BEGIN
	SET @LEN = PATINDEX('%,%', @TMP2) - 1
	SET @TMP1 = @TMP1 + CASE WHEN @TMP1 = '' THEN '' ELSE ',' END + '''' + SUBSTRING(@TMP2,1,@LEN) + ''''
	SET @TMP2 = SUBSTRING(@TMP2,@LEN+2,LEN(@TMP2)-@LEN)
END
IF @TMP2 <> ''
	SET @TMP1 = @TMP1 + CASE WHEN @TMP1 = '' THEN '' ELSE ',' END + '''' + @TMP2 + ''''

RETURN @TMP1

END

GO


GRANT EXECUTE ON dbo.[QUOTED_STR] TO PUBLIC

GO

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

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW [dbo].RO_KBK_HIST_VIEW
AS 

SELECT K.[link],
       K.[Code],
       K.[Link_self],
       K.[Code_Form],
       K.[Childrens],
       KH.Name,
       K.[ImageIndex],
       K.[Code_str],
       K.[property],
       K.[add_info],
       K.[orders],
       KH.[Long_Name],       
       KH.[begin_date], 
       KH.[end_date]
       
FROM dbo.REPORT_KBK K
      JOIN dbo.report_kbk_cashe KH ON KH.[LINK_UP] = K.[link]

GO


GRANT SELECT ON dbo.[RO_KBK_HIST_VIEW] TO PUBLIC

GO


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


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW dbo.DOCUMENTS_ADD_CHILD
AS
SELECT 
	[LINK]			= S.LINK,
	[NUMBER]		= S.NUMBER,
	[DATE]			= S.[DATE],
	[COMMENTARY]	= S.[COMMENTARY],
	[FLAG_JC]		= S.FLAG_JC,
	[PERIOD]		= S.DATE_CALC,
	[SUMMA]			= S.SUMMA_T,
	[MONTH]			= MONTH(S.DATE_CALC),
	[YEAR]			= YEAR(S.DATE_CALC),
	[LINK_DEP]  		= S.LINK_DEP,
	SD.LINK_SFIN,
	CODE_SFIN 		= KBK.CODE,
	NAME_SFIN		= KBK.[NAME],
	isREGION		= COALESCE(SD.LINK_PAY1,0) / COALESCE(SD.LINK_PAY1,1),
	SD.LINK_PAY1,	--начисление для районного коэф.
	[CODE_PAY1]		= P1.CODE,
	[NAME_PAY1]		= P1.[NAME],
	isNORTH		= COALESCE(SD.LINK_PAY2,0) / COALESCE(SD.LINK_PAY2,1),
	SD.LINK_PAY2,	--начисление для северного коэф.
	[CODE_PAY2]		= P2.CODE,
	[NAME_PAY2]		= P2.[NAME],
	dep.NAME as name_dep
FROM 
	dbo.SDOC S 
	INNER JOIN dbo.SDOC_ACHILD SD ON S.LINK = SD.LINK_UP
	INNER JOIN dbo.DEPARTMENTS dep ON dep.link = s.LINK_DEP
	LEFT JOIN dbo.SAL_SFIN KBK ON SD.LINK_SFIN = KBK.LINK
	LEFT JOIN dbo.PAYS P1 ON SD.LINK_PAY1 = P1.LINK
	LEFT JOIN dbo.PAYS P2 ON SD.LINK_PAY2 = P2.LINK

GO


GRANT SELECT ON dbo.[DOCUMENTS_ADD_CHILD] 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].[AccountsTableWithNoChild]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[AccountsTableWithNoChild]
GO




/*
© Кейсистемс (Keysystems), 2005
*/
CREATE FUNCTION dbo.AccountsTableWithNoChild()
RETURNS TABLE
AS
RETURN SELECT LINK from dbo.S_ACCOUNTS SA where not exists
(SELECT LINK From dbo.S_ACCOUNTS child Where Child.LINK_SELF = SA.link)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO


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

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

*******************************************************************************/
CREATE VIEW dbo.ATT_GRAPHIC
AS
SELECT	AG.LINK,
	AG.NUMBER,
	AG.DATE,
	AG.PERIOD,
	AG.COMMENT,
	AG.DEP_LINK as LINK_DEP,
	CODE = '№' + rtrim(AG.NUMBER) + ' от ' +  CONVERT(VARCHAR(10),AG.DATE,104)
FROM	dbo.ATTESTAT_GRAPHICS AG



GO


GRANT SELECT ON dbo.[ATT_GRAPHIC] TO PUBLIC

GO


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


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

GO

CREATE TRIGGER [dbo].[EVENT_ROU_XINSERT] ON [dbo].[EVENT_ROU]
FOR INSERT, UPDATE
AS
Declare   @varKSCountRel 	int
  IF @@ROWCOUNT>0 AND TRIGGER_NESTLEVEL()<2
        BEGIN
	Select @varKSCountRel=Count(*) 
		FROM INSERTED INS
		WHERE INS.[LINK_DOC] not in (SELECT [LINK] FROM dbo.DOCUMENTS WITH (NOLOCK))
		   OR	 INS.[LINK_ROU] not in (SELECT [LINK] FROM dbo.EVENT_ROUTED WITH (NOLOCK))
	    IF @varKSCountRel>0
		BEGIN
			raiserror('Ошибки при вставке или обновлении данных в таблице EVENT_ROU',11,1)
			ROLLBACK
			RETURN
		END
        END


GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE VIEW dbo.[RT_DICTION_581_ORG_TYPE]
AS

select 1 as link, 'г.о.' as name
union
select 2 as link, 'c.п.' as name
union
select 4 as link, 'г.п.' as name
union
select 3 as link, '' as name
	
GO
GRANT SELECT ON dbo.[RT_DICTION_581_ORG_TYPE] 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.[SALARY_REESTR_DGH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SALARY_REESTR_DGH]

GO

CREATE VIEW [dbo].SALARY_REESTR_DGH
AS 
SELECT 
	[LINK] 			= R.LINK,
	[NUMBER] 		= R.NUMBER,
	[DATE]			= R.[DATE],
	[PERS_LINK]		= R.PERS_LINK,
	[FIO] 			= rtrim(P.FM)+' '+left(P.IM,1)+'.'+left(P.OT,1)+'.',
	[DATE1] 		= R.DATE1,
	[DATE2] 		= R.DATE2,
	[TYPE] 			= R.TYPE,
	[PAYMENT]		= R.PAYMENT,
	[SUMMA]			= R.SUMMA,
	[COMMENT]		= R.COMMENT,
	[LINK_PAYS] 	= R.LINK_PAYS,
	[CODE_PAYS] 	= PS.CODE,
	[NAME_PAYS] 	= PS.[NAME],
	[VZNOS]			= R.VZNOS,
	[FLAG_NALOG]	= R.FLAG_NALOG,
	[FLAG_ESN]		= R.FLAG_ESN,
	[FLAG_TRAVMA]		= R.FLAG_TRAVMA,
	[DEP_LINK] 		= R.DEP_LINK,
	[NAME_DEP]		= d.[NAME],
	[BIRTHDATE] 	= P.BIRTHDATE,
	[SEX] = P.SEX,
	R.LINK_KBK,
	CODE_KBK = KBK.CODE,
	NAME_KBK = KBK.[NAME],
	P.RESIDENT
	
FROM dbo.REESTR_DGH R 
	LEFT JOIN dbo.PERSON P ON R.PERS_LINK=P.LINK
	left join dbo.departments D on R.DEP_LINK = D.LINK
	left join dbo.SAL_SFIN KBK on R.LINK_KBK = KBK.LINK 
	LEFT JOIN dbo.PAYS PS ON PS.LINK = R.LINK_PAYS


GO


GRANT SELECT ON dbo.[SALARY_REESTR_DGH] TO PUBLIC

GO

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

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

--Представление сформировано с помощью X_FORM_VIEW_DICTIONARY (Сергеев С.Н.)
--Feb 20 2012 12:11PM           
VIEW dbo.DICTIONARY_CHIN
AS
SELECT A.LINK,
	[CODE]=convert(CHAR(2),A.CODE),
	[NAME]=convert(VARCHAR(150),A.NAME),
	[MONTH]=convert(VARCHAR(3), (SELECT B.VALUE FROM  dbo.DICTION_APP B  WHERE  B.LINK_UP = A.LINK AND B.OBJECT= 42359) ),
	[ORDERS]=convert(VARCHAR(3), (SELECT B.VALUE FROM  dbo.DICTION_APP B  WHERE  B.LINK_UP = A.LINK AND B.OBJECT= 42360) )
		 FROM dbo.DICTION A  WHERE OBJECT=2309

GO


GRANT SELECT ON dbo.[DICTIONARY_CHIN] TO PUBLIC

GO


--Расширенные свойства--
--Свойство:SCRIPT значение: EXECUTE dbo.X_FORM_VIEW_DICTIONARY 'DICTIONARY_CHIN'


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW dbo.PLAN_ACCOUNTS_SGU
AS
SELECT SA_SGU.LINK,
	SA_SGU.ACCOUNT,
	SGU.LINK AS SGU_LINK, 
	SGU.CODE AS SGU_CODE,
	SGU.[NAME] AS SGU_NAME,
	SGU.DB_KR, 
	[DB_KR_VIS] = CASE
				WHEN DB_KR = 0 THEN 'Дт'
				ELSE 'Кт'
			END,
	SA_SGU.COMMENT
FROM dbo.S_ACCOUNTS_SGU SA_SGU
INNER JOIN dbo.KOSGU SGU ON SGU.LINK = SA_SGU.LINK_SGU


GO


GRANT SELECT ON dbo.[PLAN_ACCOUNTS_SGU] TO PUBLIC

GO


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


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

GO
CREATE VIEW dbo.BK_TYPE_OPER_NDS
AS
SELECT LINK,
	CODE,
	CONVERT (VARCHAR (254), SHORT_NAME) AS [NAME],
	CONVERT (VARCHAR (254), FULL_NAME) AS FULL_NAME,
	ISUSED,
	CASE
		WHEN ISUSED = 1 THEN CONVERT (VARCHAR (3), 'Да')
		ELSE CONVERT (VARCHAR (3), 'Нет')
	END AS ISUSED_COM
FROM dbo.TYPE_OPER_NDS


GO


GRANT SELECT ON dbo.[BK_TYPE_OPER_NDS] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

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

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

CREATE VIEW dbo.[RO_VIEW_KBK_TREE]
AS

	select T.Link, T.Link_Self, T.Code, 
         Name1 = T.Code + CASE WHEN isnull(T.begin_date, '19000101') >'20000101' 
                              THEN ' (' + CONVERT(VARCHAR(10), T.begin_date, 104) + '-'
                                    + CASE WHEN isnull(T.end_date, '30000101') <'20990101' 
                                          THEN CONVERT(VARCHAR(10), T.end_date, 104) + ')' ELSE ')' END
                              ELSE  CASE WHEN isnull(T.end_date, '30000101') <'20990101' 
                                          THEN ' (' + CONVERT(VARCHAR(10), T.end_date, 104) + ')' ELSE '' END
                           END  
                              
                  + ' ' + isnull(T.Name,'') ,
         isnull(RIGHT('00000000000' + ltrim(str(T.orders)),10), T.code) as orders, 
         T.code_form, 
         0 as imageindex,
			childrens = convert(bit, case when exists(select * from dbo.REPORT_KBK T3 where T3.Link_Self = T.Link) then 0 else 1 end),
			case when len(isnull(T2.Name, '')) > 5 then  Left(T2.Name,5) + '...\' else isnull(RTRIm(T2.Name) + '\','') end + RTRIM(isnull(T1.name,'')) as NameSpr
	from dbo.report_kbk T
		left join dbo.report_kbk T1 on T1.Code = T.Code_Form and T1.code_form = 'HEADER'
		left join dbo.report_kbk T2 on T2.link = T1.link_self
	where T.code_form <> 'HEADER'

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


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

GO

CREATE FUNCTION [dbo].REPLACE_VALUES_IN_STR (@lcEXPR VARCHAR(8000))
RETURNS VARCHAR(8000)
BEGIN
	
	DECLARE @Cur1 CURSOR, @lcEXPR1 VARCHAR(8000), 
			@lcNAME VARCHAR(1000), @lcFIELD VARCHAR(1000), @lcFIELD2 VARCHAR(1000), @lcFUNC  VARCHAR(1000),
			@nB1 INT, @nB2 INT, @B VARCHAR(8000), @lcVALUE VARCHAR(8000), @gnCount INT, @gc1 VARCHAR(1000), @nStartLocation INT
	
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT [NAME], [VALUES] FROM dbo.FAST_EXEC WHERE CODE = 'SQL_FUNC'
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @lcNAME, @lcFIELD
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			SET @lcEXPR1 = ''		

			WHILE @lcEXPR1 <> @lcEXPR
			BEGIN
				
				SET @lcNAME = LTRIM(RTRIM(@lcNAME))
				SET @lcFIELD = LTRIM(RTRIM(ISNULL(@lcFIELD,'')))
				SET @lcVALUE = ''
				SET @lcFUNC = LEFT(@lcNAME,CHARINDEX('(', @lcNAME, 1))

				SET @nStartLocation = 1

				WHILE PATINDEX('%'+@lcFUNC+'%', @lcEXPR) > 0
				BEGIN					
				
					SET @lcFIELD2 = @lcFIELD
					SET @nB1 = PATINDEX('%'+@lcFUNC+'%', @lcEXPR)

					IF @nB1 > 0 BEGIN
						SET @nB2 = CHARINDEX(')', @lcEXPR, @nStartLocation)
						SET @B = SUBSTRING (@lcEXPR, @nB1, @nB2-@nB1+1)
						SET @B = REPLACE (@B, @lcFUNC, '')
						SET @B = REPLACE (@B, '(', '')
						SET @B = REPLACE (@B, ')', '') --ПАРАМЕТРЫ ФУНКЦИИ					

						SET @gnCount = 1
						WHILE (CHARINDEX(',', @B, 1) > 0 OR @gnCount = 1) AND dbo.[SA_GET_WORD_NUM](@B,@gnCount,',') <> '' BEGIN
							SET @gc1 = dbo.[SA_GET_WORD_NUM](@B,@gnCount,',') --ОЧЕРЕДНОЙ ПАРАМЕТР
							
							--Определить параметр
							IF EXISTS (SELECT TOP 1 [VALUES] FROM dbo.FAST_EXEC WHERE @gc1 = NAME)
								SET @gc1 = (SELECT TOP 1 [VALUES] FROM dbo.FAST_EXEC WHERE @gc1 = NAME)
							ELSE
								SET @gc1 = '''' + @gc1 + ''''	
							
							WHILE PATINDEX('%@'+LTRIM(RTRIM(CONVERT(VARCHAR(20),@gnCount)) + '%'),@lcFIELD) > 0 BEGIN
								SET @lcFIELD= REPLACE(@lcFIELD,'@'+LTRIM(RTRIM(CONVERT(VARCHAR(20),@gnCount))),@gc1)
							END
								
							SET @gnCount = @gnCount + 1
								
						END
						
						IF CHARINDEX('@',@lcFIELD) = 0 BEGIN
							SET @lcEXPR = SUBSTRING(@lcEXPR,1,@nB1-1) + ''' + ' + @lcFIELD + ' + ''' + SUBSTRING(@lcEXPR,@nB2+1,LEN(@lcEXPR)-@nB2)
							SET @nStartLocation = LEN(SUBSTRING(@lcEXPR,1,@nB1-1) + ''' + ' + @lcFIELD + ' + ''') + 1							

						END
						
					END
					
					SET @lcFIELD = @lcFIELD2
				
				END

				SET @lcEXPR1 = LTRIM(RTRIM(@lcEXPR))				
			
			END		

		END
	
		FETCH NEXT FROM @Cur1 INTO @lcNAME, @lcFIELD
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1	

	DECLARE @Cur2 CURSOR, @NAME VARCHAR(254), @VALUES VARCHAR(254)

	SET @Cur2 = CURSOR FORWARD_ONLY

	FOR SELECT [NAME], [VALUES] FROM dbo.FAST_EXEC WHERE SOURCE = '' AND CODE <> 'SQL_FUNC'
	
	OPEN @Cur2
	FETCH NEXT FROM @Cur2 INTO @NAME, @VALUES
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			SET @lcEXPR = REPLACE(@lcEXPR, '<'+@NAME+'>', '''+' + @VALUES + '+''')
		END
	
		FETCH NEXT FROM @Cur2 INTO @NAME, @VALUES
	END
	
	CLOSE @Cur2
	DEALLOCATE @Cur2
	
	SET @lcEXPR = ''''+@lcEXPR+''''
	
	RETURN @lcEXPR
END




GO


GRANT EXECUTE ON dbo.[REPLACE_VALUES_IN_STR] TO PUBLIC

GO




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

GO

CREATE VIEW dbo.SDOC_DOT_SKIDKI_FIO
AS
SELECT 
	LINK = LINK_UP,
	ORDERS = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.',120),
	LINK_TAX,
	LINK_INC,
	CODE_INC = D.SNAME,
	S.LINK_PERS,
	FIO = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.',120),
	S.LINK_VKR,
	CODE_S_FIN = F.CODE,
	S.LINK_EKR,
	CODE_EKR = G.CODE,
	S.[PERCENT],
	S.SUMMA
FROM 
	[dbo].[SDOC_DOT_SKIDKI] S
	INNER JOIN dbo.PERSON P ON P.LINK = S.LINK_PERS
	INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = S.LINK_INC
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = S.LINK_VKR
	INNER JOIN dbo.KOSGU G ON G.LINK = S.LINK_EKR

GO


GRANT SELECT ON dbo.[SDOC_DOT_SKIDKI_FIO] 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].[RT_FORM_RRO_PNUM]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RT_FORM_RRO_PNUM]
GO



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

******************************************************************************


*/
CREATE VIEW dbo.[RT_FORM_RRO_PNUM]
AS
SELECT	link,
		Orders, 
		isnull(link_self,0) as link_self, 
		left(ltrim(code),patindex('%@@%',ltrim(code))-1) as pnum, 
		left(ltrim(code),patindex('%@@%',ltrim(code))-1) + ' (' + substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) + ') ' + left(ltrim([name]),230) as [name], 
		substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) as code, 
		left(ltrim([name]),250) as [short_name],
		rtrim([long_name]) as [true_name],
		childrens = convert(bit, case when exists(select top 1 * from dbo.REPORT_KBK K WHERE K.Code_Form = 'РРО' and K.link_self = report_kbk.link) then 0 else 1 end),
		imageindex, 
		0 as checked,
		right(ltrim(rtrim(add_info)),6) as add_info,
		begin_date,
		end_date
FROM  [dbo].[RO_KBK_HIST_VIEW] report_kbk
WHERE Code_Form = 'РРО'


GO
GRANT SELECT ON dbo.[RT_FORM_RRO_PNUM] 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].[RT_FORM_RRO_PNUM2]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RT_FORM_RRO_PNUM2]
GO



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

******************************************************************************


*/
CREATE VIEW dbo.[RT_FORM_RRO_PNUM2]
AS
SELECT	link,
		Orders, 
		isnull(link_self,0) as link_self, 
		left(ltrim(code),patindex('%@@%',ltrim(code))-1) as pnum, 
		left(ltrim(code),patindex('%@@%',ltrim(code))-1) + ' (' + substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) + ') ' + left(ltrim([name]),230) as [name], 
		substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) as code, 
		left(ltrim([name]),250) as [short_name],
		rtrim([long_name]) as [true_name],
		childrens = convert(bit, case when exists(select top 1 * from dbo.REPORT_KBK K WHERE K.Code_Form = 'РРО2' and K.link_self = report_kbk.link) then 0 else 1 end),
		imageindex, 
		0 as checked,
		right(ltrim(rtrim(add_info)),6) as add_info,
		begin_date,
		end_date
FROM [dbo].[RO_KBK_HIST_VIEW] report_kbk
WHERE Code_Form = 'РРО2'


GO
GRANT SELECT ON dbo.[RT_FORM_RRO_PNUM2] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
© Кейсистемс (Keysystems), 2009
входной параметр @nS: 
1 - для субъекта (таблица 1)
2 - для муниципалов (таблица 2)
@date - дата, т.к. справочник расходных обязательств зависит от периода
*/


CREATE FUNCTION dbo.RT_GET_RECORDS_RRO (@nS int = 1, @date datetime = NULL)

RETURNS @varKSRestTable TABLE (
	[link] [int] NOT NULL,
	[orders] [int] NULL,
	[link_self] [int] NULL,
	[pnum] [varchar](50) NULL,
	[name] [varchar](254) NULL,
	[code] [varchar](9) NOT NULL,
	[short_name] [varchar](250) NULL,
	[true_name] [varchar] (8000) NULL,
	[childrens] [bit] NULL, 
	[imageindex] [int] NULL, 
	[checked] [tinyint] NULL,
	[add_info] [varchar](6) NULL,
	[begin_date] [datetime] NULL,
	[end_date] [datetime] NULL
)
AS
BEGIN
	INSERT INTO @varKSRestTable (	
		[link],
		[orders],
		[link_self],
		[pnum],
		[name],
		[code],
		[short_name],
		[true_name],
		[childrens], 
		[imageindex], 
		[checked],
		[add_info],
		[begin_date],
		[end_date])
	SELECT	link,
			Orders, 
			isnull(link_self,0) as link_self, 
			cast(left(ltrim(code),patindex('%@@%',ltrim(code))-1) as varchar(50)) as pnum, 
			cast(left(ltrim(code),patindex('%@@%',ltrim(code))-1) + ' (' + substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) + ') ' + left(ltrim(name),230) as varchar(254)) as [name], 
			cast(substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) as varchar(9))as code, 
			cast(left(ltrim([name]),250) as varchar(250))as [short_name],
			cast(rtrim(long_name) as varchar(8000)) as [true_name],
			childrens, 
			imageindex, 
			0 as checked,
			cast(right(ltrim(rtrim(add_info)),6) as varchar(6)) as add_info,
			[begin_date],
			[end_date]
	FROM  [dbo].[RO_KBK_HIST_VIEW] K
	WHERE Code_Form = (case @nS when 1 then 'РРО' when 2 then 'РРО2' else '----------' end)
	and (((@date >= begin_date or begin_date is NULL) and (@date <= end_date or end_date is NULL)) or @date is null)
	and isnull(begin_date, '19000101') = (select isnull(max(begin_date), '19000101') from [dbo].[RO_KBK_HIST_VIEW] K1
		WHERE Code_Form = (case @nS when 1 then 'РРО' when 2 then 'РРО2' else '----------' end)
		and (((@date >= begin_date or begin_date is NULL) and (@date <= end_date or end_date is NULL)) or @date is null)
		and K1.Code = K.Code)

RETURN
END
GO
GRANT SELECT ON dbo.[RT_GET_RECORDS_RRO] 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].[RO_CHECK_KS_OUTSIDE_MDKS_125_STR]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RO_CHECK_KS_OUTSIDE_MDKS_125_STR]
GO




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

CREATE  FUNCTION dbo.RO_CHECK_KS_OUTSIDE_MDKS_125_STR(@cGroupKS CHAR(10), @cCodeRule CHAR(9))
RETURNS VARCHAR(1000)
AS
BEGIN
  DECLARE @cResult VARCHAR(1000), @cLeftPart VARCHAR(1000), @cRightPart VARCHAR(1000)
  
  SET @cLeftPart = ''
  SET @cRightPart = ''
  
  SELECT @cLeftPart = @cLeftPart + [SIGN] + ' ' + [KSBU] + '(' +  CASE WHEN [iDT_KT] = 1 THEN 'Дебет' ELSE 'Кредит' END + [FO_GRBS] + ')'
   FROM dbo.[RO_MDKS_125] rm 
   WHERE rm.[GROUP_MDKS] = @cGroupKS AND rm.[CODE_RULE] = @cCodeRule AND [iPART] = 1
  
  SELECT @cRightPart = @cRightPart + [SIGN] + ' ' + [KSBU] + '(' +  CASE WHEN [iDT_KT] = 1 THEN 'Дебет' ELSE 'Кредит' END + [FO_GRBS] + ')'
   FROM dbo.[RO_MDKS_125] rm 
   WHERE rm.[GROUP_MDKS] = @cGroupKS AND rm.[CODE_RULE] = @cCodeRule AND [iPART] <> 1
   
  SET @cResult = ISNULL(@cLeftPart, '') + '= ' + ISNULL(@cRightPart, '')   

  RETURN @cResult
END






GO
GRANT ALL ON dbo.[RO_AccessColByLink] 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].[AProvByBufferConditionsShortDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[AProvByBufferConditionsShortDate]
GO







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


CREATE       FUNCTION dbo.AProvByBufferConditionsShortDate

(	
	@varKSDateBegin DateTime, 
	@varKSDateEnd DateTime,
 	@varKSDT_Account	char(100) = null,
 	@varKSKT_Account	char(100) = null
)
RETURNS TABLE
AS
	RETURN
	SELECT 
		G.LINK, G.NUMBER, G.COMMENT, G.DATE_PROV, G.DEP AS DEP_LINK,
		G2.SUMMA, G2.QUANTITY, G2.STORNO,
		DT.ACCOUNT as DT_ACCOUNT, 
		ISNULL(DT.KBK, 0) AS DT_VKR, 
		ISNULL(DT.EKR, 0) AS DT_EKR,
		ISNULL(DT.DEP, 0) AS DT_DEP, 
		ISNULL(DT.SUB, 0) as DT_SUB, 
		ISNULL(DT.EMP, 0) AS DT_EMP,
		ISNULL(DT.NOMEN, 0) AS DT_NOMEN,
		ISNULL(DT.INV, 0) AS DT_INV,
		ISNULL(DT.KAU, 0) AS DT_KAU, 
		ISNULL(DT.DEP_ACC, 0) AS DT_DEP_ACC, 
		ISNULL(DT.TMC, 0) AS DT_TMC,
		ISNULL(DT.SGU, 0) AS DT_SGU,
		DT.INDATE as DT_INDATE,
		ISNULL(DT.AP1, 0) AS DT_AP1,
		ISNULL(DT.AP2, 0) AS DT_AP2,
		ISNULL(DT.AP3, 0) AS DT_AP3,

		KT.ACCOUNT as KT_ACCOUNT, 
		ISNULL(KT.KBK, 0) AS KT_VKR, 
		ISNULL(KT.EKR, 0) AS KT_EKR,
		ISNULL(KT.DEP, 0) AS KT_DEP, 
		ISNULL(KT.SUB, 0) as KT_SUB, 
		ISNULL(KT.EMP, 0) AS KT_EMP,
		ISNULL(KT.NOMEN, 0) AS KT_NOMEN,
		ISNULL(KT.INV, 0) AS KT_INV,
		ISNULL(KT.KAU, 0) AS KT_KAU, 
		ISNULL(KT.DEP_ACC, 0) AS KT_DEP_ACC, 
		ISNULL(KT.TMC, 0) AS KT_TMC,
		ISNULL(KT.SGU, 0) AS KT_SGU,
		KT.INDATE as KT_INDATE,
		ISNULL(KT.AP1, 0) AS KT_AP1,
		ISNULL(KT.AP2, 0) AS KT_AP2,
		ISNULL(KT.AP3, 0) AS KT_AP3,
		SA1.CODE AS CODE_DT,
		SA2.CODE AS CODE_KT
	FROM 
		dbo.G_PROV G 
		INNER JOIN dbo.G_PROV1 G1 ON G.LINK = G1.LINK_UP
		INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
		INNER JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
		INNER JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)
		INNER JOIN S_ACCOUNTS SA1 ON (DT.ACCOUNT = SA1.LINK)
		INNER JOIN S_ACCOUNTS SA2 ON (KT.ACCOUNT = SA2.LINK)
		LEFT JOIN dbo.SUBDIV SDT ON SDT.LINK = DT.SUB
		LEFT JOIN dbo.SUBDIV SKT ON SKT.LINK = KT.SUB
	WHERE  G.DATE_PROV is not null and
		(@varKSDT_Account IS NULL OR DT.ACCOUNT IN (select LINK from dbo.BufferGetTableByID(@varKSDT_Account)) )
		AND (@varKSKT_Account IS NULL OR KT.ACCOUNT IN (select LINK from dbo.BufferGetTableByID(@varKSKT_Account)) ) AND
		(DT.INDATE is null and KT.INDATE is null and G.DATE_PROV BETWEEN @varKSDateBegin AND @varKSDateEnd or 
		 DT.INDATE is null and KT.INDATE is not null and KT.INDATE BETWEEN @varKSDateBegin AND @varKSDateEnd or 
		 DT.INDATE is not null and KT.INDATE is null and DT.INDATE BETWEEN @varKSDateBegin AND @varKSDateEnd or 
		 DT.INDATE is not null and KT.INDATE is not null and DT.INDATE BETWEEN @varKSDateBegin AND @varKSDateEnd and KT.INDATE BETWEEN @varKSDateBegin AND @varKSDateEnd)
		 
						
		








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_OKDP]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[BB_OKDP]
GO





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

CREATE VIEW dbo.BB_OKDP

AS
/*SELECT  LINK,
	CODE, 
	NAME,
	LINK_SELF
FROM dbo.OKDP*/
select T.*, 
	CODE_UM = UM.CODE, 
	NAME_UM = UM.NAME, 
	0 as UPD,
	0 as CHECKED, 
	0 as DEL, 
	IMAGEINDEX = cast(case CHILDRENS when 0 then 'FOLDER' else 'NAIM' end as varchar(10))
from (select OKDP.LINK, 
	  	OKDP.USED,
		LINK_SELF 	= isnull(OKDP.LINK_SELF, 0),
	  	OKDP.CODE,
	  	CODE_SELF 	= (select isnull(OKDP1.CODE,'') FROM dbo.OKDP OKDP1 where OKDP1.LINK = OKDP.LINK_SELF),	  	
		[NAME_TABLE] 	= OKDP.[NAME],
	  	[NAME]    	= convert(varchar(254),RTRIM(OKDP.CODE) + ' ' + RTRIM(OKDP.[NAME])),
	  	[CHILDRENS] 	=	CASE  	when EXISTS(select * from dbo.OKDP OKDP2 where OKDP2.LINK_SELF = OKDP.LINK) 
		                   		then CONVERT(bit,0)
		             			else CONVERT(bit,1)
		                	end,
		[UM]
		
	from dbo.OKDP OKDP) T
left join dbo.DICTIONARY_DIGIT UM ON UM.LINK = T.UM





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE VIEW [dbo].SA_SZV4_PACHKA
as
SELECT
	P.link,
	CODE = 
	(case type when 1 then 'Исходные' when 2 then 'Назначение пенсии -' else '' end)
	+ SPACE(1) + (case vid_kor when 2 then '(корректирующие)'+ SPACE(1) when 3 then '(отменяющие)'+ SPACE(1) else '' end)
	+ 'cведения за' 
	+	CASE WHEN ISNULL([PER],4) >= 4 THEN
			SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'год'
		ELSE	
			SPACE(1) + (case ISNULL([PER],4) when 1 then 'I квартал' when 2 then 'I полугодие' when 3 then '9 месяцев' else '' end)
			+ SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'года'
		END
	+ 	SPACE(1) +  'от' + SPACE(1) + CONVERT(VARCHAR(10),date,104), 
	 
	numer, 
	[date], 
	[year_begin], [month_end], 
	[PER], PER_N = (case [PER] when 1 then 'I квартал' when 2 then 'I полугодие' when 3 then '9 месяцев' when 4 then 'год' else '' end), 
	YEAR_EDT,
	PER_EDT, PER_EDT_N = (case [PER_EDT] when 1 then 'I квартал' when 2 then 'I полугодие' when 3 then '9 месяцев' when 4 then 'год' else '' end), 
	P.[KATEG],
	[KATEG_CODE] = K.CODE,
	[type], n_type = (case type when 1 then 'исходные' when 2 then 'назначение пенсии' else '' end),
	vid_kor, 
	n_vid_kor = (case vid_kor when 1 then 'нет' when 2 then 'корректирующие' when 3 then 'отменяющие' else '' end),
	link_dep,
	proverka,
	nproverka = (case when proverka = 0 then 'Не выполнена' else 'Выполнена' end),
	
	sum_str = CASE WHEN year_begin < 2010 --Начисленно
			THEN CONVERT(NUMERIC(18,2),CASE WHEN P.[type] = 1 THEN sum(S.sum_str) ELSE COALESCE(ADV11.sum_str,0) END) 
			ELSE CONVERT(NUMERIC(18,2),sum(S.sum_doh)) END, 	
			
	sum_str1 = CASE WHEN year_begin < 2010 --Уплочено
			THEN 0 
			ELSE CONVERT(NUMERIC(18,2),sum(S.sum_str)) END, 	
			
	INSUR1 = CASE WHEN year_begin < 2010 --Уплочено
			THEN 0 ELSE ISNULL(P.INSUR1,0) END, 
	
	sum_nak = CONVERT(NUMERIC(18,2),CASE WHEN P.[type] = 1 THEN sum(S.sum_nak) ELSE COALESCE(ADV11.sum_nak,0) END),  --Начисленно
	
	sum_nak1 = CASE WHEN year_begin < 2010  --Уплочено
			THEN 0 
			ELSE CONVERT(NUMERIC(18,2),sum(S.sum_dop)) END,

	GAIN1 = CASE WHEN year_begin < 2010 --Уплочено
			THEN 0 ELSE ISNULL(P.GAIN1,0) END, 
				
	sum_dop = CASE WHEN year_begin < 2010 --Начисленно
			THEN CONVERT(NUMERIC(18,2),CASE WHEN P.[type] = 1 THEN sum(S.sum_dop) ELSE COALESCE(ADV11.sum_dop,0) END)
			ELSE 0 END,
	P.LINK_SELF,		
	CODE_SELF = 
				(
				select 
					(case type when 1 then 'Исходные' when 2 then 'Назначение пенсии -' else '' end)
					+ SPACE(1) + (case vid_kor when 2 then '(корректирующие)'+ SPACE(1) when 3 then '(отменяющие)'+ SPACE(1) else '' end)
					+ 'cведения за' 
					+	CASE WHEN ISNULL([PER],4) >= 4 THEN
							SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'год'
						ELSE	
							SPACE(1) + (case ISNULL([PER],4) when 1 then 'I квартал' when 2 then 'I полугодие' when 3 then '9 месяцев' else '' end)
							+ SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'года'
						END
					+ 	SPACE(1) +  'от' + SPACE(1) + CONVERT(VARCHAR(10),date,104) 
				from DBO.SZV4_PACHKA P2 where P2.link = P.LINK_SELF
				),
	P.sum_uplata_dolga_str,
	P.sum_uplata_dolga_nak,
	P.LINK_SELF2,
	CODE_SELF2 = 
				(
				select 
					(case type when 1 then 'Исходные' when 2 then 'Назначение пенсии -' else '' end)
					+ SPACE(1) + (case vid_kor when 2 then '(корректирующие)'+ SPACE(1) when 3 then '(отменяющие)'+ SPACE(1) else '' end)
					+ 'cведения за' 
					+	CASE WHEN ISNULL([PER],4) >= 4 THEN
							SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'год'
						ELSE	
							SPACE(1) + (case ISNULL([PER],4) when 1 then 'I квартал' when 2 then 'I полугодие' when 3 then '9 месяцев' else '' end)
							+ SPACE(1) + CONVERT(VARCHAR(4),year_begin) + SPACE(1) + 'года'
						END
					+ 	SPACE(1) +  'от' + SPACE(1) + CONVERT(VARCHAR(10),date,104) 
				from DBO.SZV4_PACHKA P2 where P2.link = P.LINK_SELF2
				)
FROM 
	dbo.SZV4_PACHKA P 
	INNER JOIN dbo.SA_PFR_KATEG K on K.LINK = P.KATEG AND [year_begin] BETWEEN YBEG AND YEND
	LEFT JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
	LEFT JOIN dbo.SZV4_ADV11 ADV11 ON P.link = ADV11.link_up AND tip = 3
group by 
		P.link, numer, [date], [year_begin], [month_end], [PER], PER_EDT, YEAR_EDT,
		P.INSUR1, P.GAIN1,
		P.KATEG,K.CODE, K.NAME, 
		[type], vid_kor, link_dep, proverka, 
		ADV11.sum_str, ADV11.sum_nak, ADV11.sum_dop, P.LINK_SELF,
		P.sum_uplata_dolga_str,
		P.sum_uplata_dolga_nak,
		P.LINK_SELF2

GO


GRANT SELECT ON dbo.[SA_SZV4_PACHKA] TO PUBLIC

GO




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

GO
CREATE VIEW DBO.ko_punkt_postanov
AS

SELECT 
	T.LINK,
	T.CODE,
	T.NAME,
	T.PRIK_TYP,
	OT.NAME as PRIK_TYP_N,
    SH_NAME = LEFT(T.NAME,254)
FROM
	DBO.punkt_postanov T
	INNER JOIN order_types OT ON OT.CODE = T.PRIK_TYP





GO


GRANT SELECT ON dbo.[ko_punkt_postanov] TO PUBLIC

GO


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


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

GO

CREATE FUNCTION dbo.BK_DOC_TAB_MZ_CHARGE
	(@intLINK_DOC INT = NULL)
RETURNS @RETURN_TABLE TABLE 
	(LINK	INT,
	LINK_UP	INT,
	ORDERS	INT,
	OPER_LINK	INT,

	ACCOUNT	INT,
	ACCT_CODE VARCHAR (20),

	NOMEN INT,
	NOMEN_CODE VARCHAR (20),
	NOMEN_NAME VARCHAR (254),

	UM	INT,
	UM_CODE	VARCHAR (5),
	UM_NAME VARCHAR (60),

	QTY NUMERIC (28,4),
	REST NUMERIC (28,4),
	PRICE NUMERIC (28,4),
	SUMMA NUMERIC (28,4),

	PRICE_FACT NUMERIC (28,4))
AS
BEGIN
	INSERT INTO @RETURN_TABLE 
	SELECT OTR.LINK,
		OTR.LINK_UP,
		OTR.ORDERS,
		OTR.LINK_OPER,
	
		SA.LINK,
		CONVERT (VARCHAR (20), SA.CODE),
	
		NOM.LINK,
		CONVERT (VARCHAR (20), NOM.CODE),
		CONVERT (VARCHAR (150), NOM.[NAME]),

		NOM.LINK_UM,
		CONVERT (VARCHAR (5), NOM.CODE_UM),
		CONVERT (VARCHAR (50), NOM.NAME_UM),

		OTMC.QTY,
		OTMC.QTY_REST,
		OTMC.PRICE,
		OTMC.SUMMA,

		OTMC.PRICE_FACT
	
	FROM dbo.S_OBJECTS SO 
	INNER JOIN dbo.OUT_TABLE_ROW OTR ON (OTR.OBJECT = SO.LINK)
	LEFT JOIN dbo.OUT_TABLE_MZ_CHARGE OTMC ON (OTMC.LINK_UP = OTR.LINK)
	LEFT JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OTMC.ACCOUNT)
	LEFT JOIN dbo.BV_NOMENCLATURE NOM ON (NOM.LINK = OTMC.NOMEN)
	WHERE SO.CODE = 'DOC_MZ_CHARGE_TABLE'
		AND (@intLINK_DOC IS NULL
			OR OTR.LINK_UP = @intLINK_DOC)
RETURN
END

GO


GRANT SELECT ON dbo.[BK_DOC_TAB_MZ_CHARGE] TO PUBLIC

GO


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


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

GO

CREATE function dbo.SA_BASE_SUM_ADDPAY (	
/*Определение базовой суммы для расчета вида оплаты @varKSRefPay по сотрудику @varKSlinkEmpl*/
	@varKSRefPay 	int,	/*Ссылка на вид оплаты (надбавки)*/
	@varKSlinkEmpl	 int,	/*Ссылка на работника*/
	@varKSdDate1	datetime, /*Даты начала и окончния периода,*/
	@varKSdDate2	datetime, /* за который определяется база для расчета*/
	@LINK_KBK	INT = NULL
) 
	returns numeric(9,2) as
begin

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

return (		
	SELECT 	SUM(SJ.summa) as summa			
	FROM S_J_C_Short SJ INNER JOIN dbo.group_pays(@varKSRefPay) T  ON SJ.link_PAYS=T.PAY_LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
	WHERE 
		SJ.LINK_EMPL = @varKSlinkEmpl 
		AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_BEGIN ELSE SJ.DATE1 END) >=@varKSdDate1 
		AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_END ELSE SJ.DATE2 END) <=@varKSdDate2
		AND 
		(COALESCE(@LINK_KBK,0) = 0 OR @LINK_KBK = SJ.LINK_VKR)
	)
end	

GO


GRANT EXECUTE ON dbo.[SA_BASE_SUM_ADDPAY] 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.KOSGU  SGU on SGU.LINK = T.LINK_SGU
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.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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

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

CREATE VIEW dbo.[RT_VIEW_DEPDICT_125]
AS
select 
	dp.link as link,
	dp.code,
	sh_name =ISNULL(DH.[NAME], dp.NAME), 
	name = ISNULL(DH.[FULL_NAME], dp.[FULL_NAME]), 
	isnull(kbs.code,'') as ppp,
	isnull( cast(replace(dp.okato,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as okato, 
	coalesce((
		select coalesce(kbt.code_el,'') 
		from kl_budg_type as kbt 
		where kbt.link = (
			select kab.link_budg 
			from kl_admin_bs as kab 
			where kab.link = dp.ved_link)
		),'') as code_el,
	right('0000000000' + cast(isnull(dp.link,'0') as varchar(10)),8) as UCS,
   isnull(DH.[DATE_BEGIN], '19000101') [DATE_BEGIN],
   isnull(DH.[DATE_END], '30000101') [DATE_END] 
	from dbo.Departments as dp 
	left join dbo.kl_admin_bs as kbs on dp.ved_link = kbs.link
   left JOIN dbo.DICTIONARY_DEPARTMENT_HIST DH ON DH.[LINK_UP] = DP.[LINK]
	where dp.link in (select convert(int, code) from dbo.report_kbk where code_form = 'RT_VIEW_DEPDICT_125' and isnumeric(code) = 1)
union 
select 
	dp.link as link,
	dp.code,
	sh_name = dp.NAME, 
	name = dp.[FULL_NAME], 
	isnull(kbs.code,'') as ppp,
	isnull( cast(replace(dp.okato,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as okato, 
	coalesce((
		select coalesce(kbt.code_el,'') 
		from kl_budg_type as kbt 
		where kbt.link = (
			select kab.link_budg 
			from kl_admin_bs as kab 
			where kab.link = dp.ved_link)
		),'') as code_el,
	right('0000000000' + cast(isnull(dp.link,'0') as varchar(10)),8) as UCS,
  '19000101',
   isnull(DH.[DATE_BegiN]-1,'30000101') 
	from dbo.Departments as dp 
	left join dbo.kl_admin_bs as kbs on dp.ved_link = kbs.link
   left JOIN (select min(date_begin) date_begin, link_up from dbo.DICTIONARY_DEPARTMENT_HIST GROUP BY link_up) DH ON DH.[LINK_UP] = DP.[LINK]
	where dp.link in (select convert(int, code) from dbo.report_kbk where code_form = 'RT_VIEW_DEPDICT_125' and isnumeric(code) = 1)
union
select -1 as link,'Итого' as code, 'Итого' as sh_name,'Итого' as name, '' as ppp,'99999999999' as okato, '' , '', '19000101', '30000101'

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

GO

CREATE FUNCTION [dbo].SklonWord (@word VARCHAR(2000), @pad INT)
RETURNS VARCHAR(2000)
BEGIN

	IF @pad > 1 BEGIN

		DECLARE @result varchar(2000), 
				@sklonRowsCount int, @WordLen int, @i int, @found int,
				@tail varchar(2000),  @tmpstr varchar(2000), 
				@TailLen int, @LENSPACEL int, @LENSPACER int

		DECLARE @IM varchar(2000),@ROD varchar(2000),@DAT varchar(2000),@VIN varchar(2000),@TVOR varchar(2000),@PRED varchar(2000)

		DECLARE contact_cursor CURSOR FOR
		SELECT IM,ROD,DAT,VIN,TVOR,PRED FROM DICTIONARY_SKLON
		ORDER BY LEN(IM)  desc;

		SET @sklonRowsCount= (select count(*) from DICTIONARY_SKLON )--wsd_s.QueryTables(1).ResultRange.Rows.Count-1)

		SET @LENSPACEL = LEN(@Word) - LEN(LTRIM(@Word))
		SET @LENSPACER = LEN(@Word) - LEN(RTRIM(@Word))
		SET @Word = RTRIM(@Word)
		SET @WordLen = LEN(RTRIM(@Word))
		SET @Found = 0
		SET @i = 1

		OPEN contact_cursor;

		FETCH NEXT FROM contact_cursor
		INTO @IM,@ROD,@DAT,@VIN,@TVOR,@PRED

		WHILE (@@FETCH_STATUS = 0 And @Found = 0)
		BEGIN
			SET @Tail = @IM
			SET @TailLen = LEN(@Tail)

			IF LEN(@Word) > 0 And LOWER(right(@Word, @TailLen)) = LOWER(@Tail) 
			BEGIN
				IF (@PAD = 2)
					SET @tmpstr = left(@Word, @WordLen - @TailLen) + @ROD
				IF (@PAD = 3)
					SET @tmpstr = left(@Word, @WordLen - @TailLen) + @DAT
				IF (@PAD = 4)
					SET @tmpstr = left(@Word, @WordLen - @TailLen) + @VIN
				IF (@PAD = 5)
					SET @tmpstr = left(@Word, @WordLen - @TailLen) + @TVOR
				IF (@PAD = 6)
					SET @tmpstr = left(@Word, @WordLen - @TailLen) + @PRED
				SET @Found = 1
			END        
			SET @i = @i + 1		
		   FETCH NEXT FROM contact_cursor
		   INTO @IM,@ROD,@DAT,@VIN,@TVOR,@PRED
		END

		CLOSE contact_cursor;
		DEALLOCATE contact_cursor;

		IF (@Found=0)  
			 SET @tmpstr = @Word
		SET @result = @tmpstr
	END
	ELSE
		SET @result = @word
	
	RETURN @result
END


GO


GRANT EXECUTE ON dbo.[SklonWord] 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].[Sklon]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[Sklon]
GO




/*
© Кейсистемс (Keysystems), 2005
*/
CREATE FUNCTION dbo.Sklon (@varKSword varchar(2000), @varKSnPad int)  
RETURNS varchar(2000) AS  
BEGIN 
	DECLARE @varKStail varchar(2000), @varKStaillen int, @varKSResult varchar(2000)

	SELECT TOP 1 @varKStaillen=len(im), @varKStail=case when @varKSnPad=1 then im when @varKSnPad=2 then rod when @varKSnPad=3 then dat 
						when @varKSnPad=4 then vin when @varKSnPad=5 then tvor when @varKSnPad=6 then pred end
	FROM dictionary_sklon
	WHERE im=right(@varKSword, len(im))
	ORDER BY len(im) DESC

	SET @varKSResult = isnull(left(@varKSword, len(@varKSword)-@varKStaillen)+@varKStail, @varKSword)

	RETURN @varKSResult

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.[GetProfKvalToEmpl_More]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[GetProfKvalToEmpl_More]

GO

/*
© Кейсистемс (Keysystems), 2008
Возвращает сведения о профессиональной переподготовке и повышении квалификации сотруднитка
*/
CREATE   FUNCTION dbo.GetProfKvalToEmpl_More(@empl_link int	-- ссылка на сотрудника
					)
RETURNS varchar(2000)
AS BEGIN
declare @prof_kv varchar(2000)
set @prof_kv = ''
declare @cur1 cursor
declare @cur2 cursor
declare @date_begin datetime,@date_end datetime
DECLARE @DOC_DATE DATETIME, @DOC_TYPE VARCHAR(60), @DOC_NUM VARCHAR(30),
		@PLACE_Name varchar(150), @Prog_NAME varchar(150), @TIME varchar(10)

SET @cur1 = CURSOR FAST_FORWARD FOR select DATE_BEGIN,DATE_END,DOC_TYPE,DOC_NUM,DOC_DATE,PLACE,Prog_NAME, [TIME] from KU_EMPL_INCQUAL where empl_link = @empl_link
OPEN @cur1
FETCH NEXT FROM @cur1 INTO @date_begin,@date_end,@DOC_TYPE,@DOC_NUM,@DOC_DATE,@PLACE_Name, @Prog_NAME, @TIME
WHILE @@FETCH_STATUS=0 BEGIN
	if ISNULL(@date_begin,0) != 0 begin
		set @prof_kv = @prof_kv + 'пов.квалиф. с ' + convert(varchar(20),@date_begin,104)
		if ISNULL(@date_end,0) != 0 set @prof_kv = @prof_kv + ' по ' + convert(varchar(20),@date_end,104)
		else set @prof_kv = @prof_kv + ''
		set @prof_kv = @prof_kv +  '' +
			ltrim(case when isnull(@PLACE_Name,'') = '' then ''
			       else ', ' + rtrim(ltrim(@PLACE_Name)) +' ' 
			  end
				) +
			case when len(rtrim(ltrim(@DOC_TYPE))) = 0 and len(rtrim(ltrim(@DOC_NUM))) = 0 and isnull(@DOC_DATE,0) = 0
			     then ''
			     else ' (' +
				case when len(rtrim(ltrim(@DOC_TYPE))) = 0 then ''
				     else rtrim(ltrim(@DOC_TYPE)) + ' '
				end +
				ltrim(
				case when len(rtrim(ltrim(@DOC_NUM))) = 0 then ''
				     else ' № ' + rtrim(ltrim(@DOC_NUM)) + ' '
				end
				) +
				ltrim(
				case when isnull(@DOC_DATE,0) = 0 then ''
				     else ' от ' + convert(varchar(20),@DOC_DATE,104)
				end
				) +

				  + ')'
			end  + ', ' 
			 +
			ltrim(case when isnull(@Prog_NAME,'') = '' then ''
					else ', ' + rtrim(ltrim(@Prog_NAME))
				  end
				  ) +
			ltrim(case when isnull(@TIME,'') = '' then ''
				     else ', ' + rtrim(ltrim(@TIME))
				  end
				  ) 
				
			
	end
	FETCH NEXT FROM @cur1 INTO @date_begin,@date_end,@DOC_TYPE,@DOC_NUM,@DOC_DATE,@PLACE_Name, @Prog_NAME, @TIME
END
CLOSE @cur1
DEALLOCATE @cur1
SET @cur2 = CURSOR FAST_FORWARD FOR select DATE_BEGIN,DATE_END,DOC_TYPE,DOC_NUM,DOC_DATE,PLACE,Prog_NAME,[TIME] from KU_EMPL_PROFP where empl_link = @empl_link
OPEN @cur2
FETCH NEXT FROM @cur2 INTO @date_begin,@date_end,@DOC_TYPE,@DOC_NUM,@DOC_DATE,@PLACE_Name, @Prog_NAME, @TIME
WHILE @@FETCH_STATUS=0 BEGIN
	if ISNULL(@date_begin,0) != 0 begin
		set @prof_kv = @prof_kv + 'проф.пер. с ' + convert(varchar(20),@date_begin,104)
		if ISNULL(@date_end,0) != 0 set @prof_kv = @prof_kv + ' по ' + convert(varchar(20),@date_end,104)
		else set @prof_kv = @prof_kv + ''
		set @prof_kv = @prof_kv + '' +
			ltrim(case when isnull(@PLACE_Name,'') = '' then ''
			       else ', ' + rtrim(ltrim(@PLACE_Name)) +' ' 
			  end
				) +
			case when len(rtrim(ltrim(@DOC_TYPE))) = 0 and len(rtrim(ltrim(@DOC_NUM))) = 0 and isnull(@DOC_DATE,0) = 0
			     then ''
			     else ' (' +
				case when len(rtrim(ltrim(@DOC_TYPE))) = 0 then ''
				     else rtrim(ltrim(@DOC_TYPE)) + ' '
				end +
				ltrim(
				case when len(rtrim(ltrim(@DOC_NUM))) = 0 then ''
				     else ' № ' + rtrim(ltrim(@DOC_NUM)) + ' '
				end
				) +
				ltrim(
				case when isnull(@DOC_DATE,0) = 0 then ''
				     else ' от ' + convert(varchar(20),@DOC_DATE,104)
				end
				) +
				  + ')'
			end  + ', ' 
			 +
			ltrim(case when isnull(@Prog_NAME,'') = '' then ''
					else ', ' + rtrim(ltrim(@Prog_NAME))
				  end
				  ) +
			ltrim(case when isnull(@TIME,'') = '' then ''
				     else ', ' + rtrim(ltrim(@TIME))
				  end
				  ) 
				
	end
	FETCH NEXT FROM @cur2 INTO @date_begin,@date_end,@DOC_TYPE,@DOC_NUM,@DOC_DATE ,@PLACE_Name, @Prog_NAME, @TIME
END
CLOSE @cur2
DEALLOCATE @cur2

if len(@prof_kv)>1 set @prof_kv = substring(@prof_kv,1,len(rtrim(@prof_kv))-1)
RETURN @prof_kv
END

GO


GRANT EXECUTE ON dbo.[GetProfKvalToEmpl_More] 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_SELECT_FORM_TOTALS_DOH_20]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RO_SELECT_FORM_TOTALS_DOH_20]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE FUNCTION dbo.[RO_SELECT_FORM_TOTALS_DOH_20] (
   @tMODE            TINYINT, -- 0 - Выбор итогов из КС, 1 - Выбор итогов из справочника REPORT_KBK, 2 - оба варианта.
   @iLINK_FORM       INT,
   @iPROPERTY_MASK   INT = 1   
)
RETURNS @tabReturn TABLE ([LINK_TABLE] INT, 
                          [CODE]       VARCHAR(250),
                          [CD]         VARCHAR(250))
AS
BEGIN
      
	declare @LinkTable int, @StartDate DATETIME, @Date DATETIME 
	select @LinkTable = Link_Table from report_tables where Link_Form = @iLINK_FORM and orders = 1 and Doschet_Tree = 1
	if @LinkTable is NOT NULL
	begin
		select @StartDate = Start_Date from report_forms where Link_Form = @iLINK_FORM
      SET @Date = CONVERT(DATETIME, '20111231') + ISNULL((SELECT top 1 link FROM dbo.[BufferGetTableByID]('RO_RAZMNOJ_KS_OUTSIDE') bgtbi), 0)

		insert @tabReturn(Link_Table, Code, CD)
		select @LinkTable, Code, Code
		from report_kbk T
		where T.code_form = 'ДОХОДЫ_' + LTRIM(STR(YEAR(@StartDate)))
            AND isnull(T.begin_date, '19000101') <= @Date  AND ISNULL(T.end_date, '30000101') >= @Date 
            and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= @Date AND ISNULL(T1.end_date, '30000101') >= @Date)
	end
   RETURN   
END

GO
GRANT ALL ON dbo.[RO_SELECT_FORM_TOTALS_DOH_20] 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].[RT_GET_LSF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RT_GET_LSF]
GO

CREATE FUNCTION dbo.[RT_GET_LSF](
	@link_f int,
	@period_type tinyint,
	@period_number tinyint,
	@period_date datetime,
	@ksbu varchar(9) = null,
	@is_grbs tinyint,
	@org_type tinyint = null,
	@ppp varchar(3) = null,
	@okato varchar(11) = null,
	@org_link int = null
)
 	RETURNS INT
AS 
BEGIN
	declare @lsf int, @link_f1 INT 
   
   IF @org_link IS NULL AND ISNULL(@ppp, '') = '' AND  ISNULL(@okato, '') = ''
      RETURN NULL

   SELECT @link_f1 = rf.link_form 
   FROM dbo.[REPORT_FORMS] rf 
         JOIN dbo.report_forms rf1 ON rf.link_form <> rf1.link_form 
                                       AND rf.start_date = rf1.start_date 
                                       AND rf1.link_form =  @link_f
                                       AND rf.code = CASE  WHEN rf1.code = '0503125G' THEN '425G' WHEN rf1.code = '0503125M' THEN '425M' WHEN rf1.code = '425G' THEN '0503125G' WHEN rf1.code = '425M' THEN '0503125M' END 
   IF @org_link IS NOT NULL
   BEGIN 
	   select 
      top 1 @lsf = link_saved_form		
	   from dbo.report_saved_forms as rsf
	   where rsf.link_form = @link_f
      AND rsf.del = 0
	   and rsf.period_type = @period_type
	   and rsf.period_number = @period_number
	   and rsf.begin_date = @period_date
	   and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	   and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	   and rsf.link_organization = @org_link 
	   and rsf.Version = (select max(rsf1.Version) 
		   from dbo.report_saved_forms as rsf1
		   where rsf1.link_form = rsf.link_form
         AND rsf1.del = 0
		   and rsf1.period_type = rsf.period_type
		   and rsf1.begin_date = rsf.begin_date
		   and rsf1.atr_code = rsf.atr_code
         and rsf1.link_organization = rsf.link_organization
         and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	   )
      
      IF @lsf IS NULL
      	   select 
         top 1 @lsf = link_saved_form		
	      from dbo.report_saved_forms as rsf
	      where rsf.link_form = @link_f1
         AND rsf.del = 0
	      and rsf.period_type = @period_type
	      and rsf.period_number = @period_number
	      and rsf.begin_date = @period_date
	      and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	      and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	      and rsf.link_organization = @org_link 
	      and rsf.Version = (select max(rsf1.Version) 
		      from dbo.report_saved_forms as rsf1
		      where rsf1.link_form = rsf.link_form
            AND rsf1.del = 0
		      and rsf1.period_type = rsf.period_type
		      and rsf1.begin_date = rsf.begin_date
		      and rsf1.atr_code = rsf.atr_code
            and rsf1.link_organization = rsf.link_organization
            and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	      )
   END  
   ELSE 
   BEGIN 
	   select 
      top 1 @lsf = link_saved_form		
	   from dbo.report_saved_forms as rsf
	   inner join dbo.departments as d
	   on rsf.link_organization = d.link
	   left join dbo.kl_admin_bs as kab
	   on d.ved_link = kab.link
	   where rsf.link_form = @link_f
      AND rsf.del = 0
	   and rsf.period_type = @period_type
	   and rsf.period_number = @period_number
	   and rsf.begin_date = @period_date
	   and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	   and (dbo.RT_IS_GRBS(rsf.link_saved_form) = @is_grbs OR @is_grbs IS NULL) -- грбс
	   and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	   and d.type = case isnull(@org_type,200) when 200 then d.type else @org_type end -- корреспондент
	   and isnull(kab.code,'') = case isnull(@ppp,'-1') when '-1' then isnull(kab.code,'') else rtrim(@ppp) end 
	   and left(ltrim(replace(d.okato,' ',''))+'           ',11) = case isnull(@okato,'-1') when '-1' then left(ltrim(replace(d.okato,' ',''))+'           ',11) else left(ltrim(replace(@okato,' ',''))+'           ',11) end 
	   and (len(d.okato)>0 or @okato is null)
	   and 1 = (select max([type]) from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
	   and rsf.Version = (select max(rsf1.Version) 
		   from dbo.report_saved_forms as rsf1
		   where rsf1.link_form = rsf.link_form
         AND rsf1.del = 0
		   and rsf1.period_type = rsf.period_type
		   and rsf1.begin_date = rsf.begin_date
		   and rsf1.atr_code = rsf.atr_code
         and rsf1.link_organization = rsf.link_organization
         and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	   )
      IF @lsf IS NULL 
	      select 
         top 1 @lsf = link_saved_form		
	      from dbo.report_saved_forms as rsf
	      inner join dbo.departments as d
	      on rsf.link_organization = d.link
	      left join dbo.kl_admin_bs as kab
	      on d.ved_link = kab.link
	      where rsf.link_form = @link_f1
         AND rsf.del = 0
	      and rsf.period_type = @period_type
	      and rsf.period_number = @period_number
	      and rsf.begin_date = @period_date
	      and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	      and (dbo.RT_IS_GRBS(rsf.link_saved_form) = @is_grbs OR @is_grbs IS NULL) -- грбс
	      and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	      and d.type = case isnull(@org_type,200) when 200 then d.type else @org_type end -- корреспондент
	      and isnull(kab.code,'') = case isnull(@ppp,'-1') when '-1' then isnull(kab.code,'') else rtrim(@ppp) end 
	      and left(ltrim(replace(d.okato,' ',''))+'           ',11) = case isnull(@okato,'-1') when '-1' then left(ltrim(replace(d.okato,' ',''))+'           ',11) else left(ltrim(replace(@okato,' ',''))+'           ',11) end 
	      and (len(d.okato)>0 or @okato is null)
	      and 1 = (select max([type]) from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
	      and rsf.Version = (select max(rsf1.Version) 
		      from dbo.report_saved_forms as rsf1
		      where rsf1.link_form = rsf.link_form
            AND rsf1.del = 0
		      and rsf1.period_type = rsf.period_type
		      and rsf1.begin_date = rsf.begin_date
		      and rsf1.atr_code = rsf.atr_code
            and rsf1.link_organization = rsf.link_organization
            and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	      )
   END 

	return @lsf
END
GO



GRANT EXECUTE ON dbo.[RT_GET_LSF] TO PUBLIC
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

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

CREATE VIEW dbo.[RA_VIEW_ZATO]
AS
   SELECT [LINK] = CAST([A].[CODE_SUBJ] AS INT)*100 + CAST([A].[CODE] AS INT),
          [A].[CODE_SUBJ],
          [A].[CODE],
          [A].[NAME],
          [NAME_SUBJ] = ISNULL([B].[NAME],'')
   FROM (
      SELECT [CODE_SUBJ] = '01', [CODE] = '23', [NAME] = 'Межгорье' UNION 
      SELECT '17','24','Сибирский' UNION 
      SELECT '19','25','Солнечный' UNION 
      SELECT '19','26','Кедровый' UNION 
      SELECT '19','41','Железногорск' UNION 
      SELECT '19','42','Зеленогорск' UNION 
      SELECT '20','28','Фокино' UNION 
      SELECT '20','29','Большой Камень' UNION 
      SELECT '23','30','Углегорск' UNION 
      SELECT '24','1','Мирный' UNION 
      SELECT '25','15','Знаменск' UNION 
      SELECT '28','44','Радужный' UNION 
      SELECT '38','32','Вилючинск' UNION 
      SELECT '40','14','Первомайский' UNION 
      SELECT '48','10','Краснознаменск' UNION 
      SELECT '48','11','Восход' UNION 
      SELECT '48','12','Молодежный' UNION 
      SELECT '49','2','Снежногорск' UNION 
      SELECT '49','3','Скалистый' UNION 
      SELECT '49','4','Островной' UNION 
      SELECT '49','5','Заозерск' UNION 
      SELECT '49','6','Полярный' UNION 
      SELECT '49','7','Североморск' UNION 
      SELECT '49','45','Видяево' UNION 
      SELECT '49','47','Александровск' UNION
      SELECT '32','33','Саров' UNION 
      SELECT '53','18','Комаровский' UNION 
      SELECT '55','34','Заречный' UNION 
      SELECT '56','19','Звездный' UNION 
      SELECT '60','16','Светлый' UNION 
      SELECT '60','17','Шиханы' UNION 
      SELECT '60','46','Михайловский' UNION 
      SELECT '62','20','Уральский' UNION
      SELECT '62','21','Свободный' UNION 
      SELECT '62','36','Лесной' UNION 
      SELECT '62','35','Новоуральск' UNION       
      SELECT '36','8','Озерный' UNION 
      SELECT '36','9','Солнечный' UNION 
      SELECT '65','40','Северск' UNION 
      SELECT '69','22','Локомотивный' UNION 
      SELECT '69','37','Трехгорный' UNION 
      SELECT '69','38','Озерск' UNION 
      SELECT '69','39','Снежинск' UNION 
      SELECT '91','27','Горный'
   ) [A]
   LEFT JOIN dbo.[RA_VIEW_SUBJECTS_RF] [B] ON [B].[CODE_MF]=[A].[CODE_SUBJ]
   
   
   
   




/*
select * from dbo.[RA_VIEW_ZATO]





select * from dbo.[RA_VIEW_SUBJECTS_RF]

select * into ant_base..#b from  access_import...[Лист1]

select * from antbase..tempdb.##b

select ' SELECT ''' + [Код зат123	01	23	Межгорье	Республика Башкортостано] + ''',''' + [наименование зато] + ''' UNION ' 
from #b 
where [наименование зато] is not null 
order by len([Код зато]),[Код зато]

*/

GO
GRANT ALL ON dbo.[RA_VIEW_ZATO] 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.[RO_SELECT_FORM_TOTALS_IST_23]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RO_SELECT_FORM_TOTALS_IST_23]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE FUNCTION dbo.[RO_SELECT_FORM_TOTALS_IST_23] (
   @tMODE            TINYINT, -- 0 - Выбор итогов из КС, 1 - Выбор итогов из справочника REPORT_KBK, 2 - оба варианта.
   @iLINK_FORM       INT,
   @iPROPERTY_MASK   INT = 1   
)
RETURNS @tabReturn TABLE ([LINK_TABLE] INT, 
                          [CODE]       VARCHAR(250),
                          [CD]         VARCHAR(250))
AS
BEGIN
	declare @LinkTable int, @StartDate DATETIME, @Date DATETIME
	select @LinkTable = Link_Table from report_tables where Link_Form = @iLINK_FORM and orders = 3 and Doschet_Tree = 1
	if @LinkTable is NOT NULL
	begin
		select @StartDate = Start_Date from report_forms where Link_Form = @iLINK_FORM
      SET @Date = CONVERT(DATETIME, '20111231') + ISNULL((SELECT top 1 link FROM dbo.[BufferGetTableByID]('RO_RAZMNOJ_KS_OUTSIDE') bgtbi), 0)

		insert @tabReturn(Link_Table, Code, CD)
		select @LinkTable, CODE, Code
		from report_kbk T
		where T.code_form = 'ИСТОЧНИКИ_' + LTRIM(STR(YEAR(@StartDate)))
            AND isnull(T.begin_date, '19000101') <= @Date AND ISNULL(T.end_date, '30000101') >= @Date 
            and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link  AND isnull(T1.begin_date, '19000101') <=@Date AND ISNULL(T1.end_date, '30000101') >= @Date )
	end
   RETURN   
END

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

GO

CREATE FUNCTION dbo.[RT_GET_LSF1](
	@link_f int,
	@period_type tinyint,
	@period_number tinyint,
	@period_date datetime,
	@ksbu varchar(9) = null,
	@is_grbs tinyint,
	@org_type tinyint = null,
	@ppp varchar(3) = null,
	@okato varchar(11) = null,
	@org_link int = null,
	@bgt varchar(2)
)
 	RETURNS INT
AS 
BEGIN
	declare @lsf INT, @link_f1 INT
   IF @org_link IS NULL AND ISNULL(@ppp, '') = '' AND  ISNULL(@okato, '') = ''
      RETURN NULL
    

	if @bgt <> '04' begin
		select top 1 @okato = replace(okato,' ','') 
		from dbo.departments as C
		where C.code in (
			select left(A.code,5)
			from dbo.departments as A
			where replace(A.okato,' ','')=rtrim(@okato)
		)
		and C.code in (
			select code 
			from dbo.departments 
			where link in (
				select link_org
				from dbo.report_svod_tree as rst
				where rst.link_self = (
					select top 1 link from report_svod_tree where link_budg = (select link from dbo.kl_budg_type where code = 'МР') and link_history = (select max(link) from dbo.report_svod_tree_history)
				)
				and exists(select top 1 * from dbo.report_svod_tree as B where B.link_self = rst.link)
			)
		)
	END
   
   SELECT @link_f1 = rf.link_form 
   FROM dbo.[REPORT_FORMS] rf 
         JOIN dbo.report_forms rf1 ON rf.link_form <> rf1.link_form 
                                       AND rf.start_date = rf1.start_date 
                                       AND rf1.link_form =  @link_f
                                       AND rf.code = CASE  WHEN rf1.code = '0503125G' THEN '425G' WHEN rf1.code = '0503125M' THEN '425M' WHEN rf1.code = '425G' THEN '0503125G' WHEN rf1.code = '425M' THEN '0503125M' END 
   

   IF @org_link IS NOT NULL
   BEGIN 
	   select 
      top 1 @lsf = link_saved_form		
	   from dbo.report_saved_forms as rsf
	   where rsf.link_form =  @link_f
      AND rsf.del = 0
	   and rsf.period_type = @period_type
	   and rsf.period_number = @period_number
	   and rsf.begin_date = @period_date
	   and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	   and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	   and rsf.link_organization = @org_link 
	   and rsf.Version = (select max(rsf1.Version) 
		   from dbo.report_saved_forms as rsf1
		   where rsf1.link_form = rsf.link_form
         AND rsf1.del = 0
		   and rsf1.period_type = rsf.period_type
		   and rsf1.begin_date = rsf.begin_date
		   and rsf1.atr_code = rsf.atr_code
         and rsf1.link_organization = rsf.link_organization
         and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	   )
      IF @lsf IS NULL 
      BEGIN
	      select 
         top 1 @lsf = link_saved_form		
	      from dbo.report_saved_forms as rsf
	      where rsf.link_form =  @link_f1
         AND rsf.del = 0
	      and rsf.period_type = @period_type
	      and rsf.period_number = @period_number
	      and rsf.begin_date = @period_date
	      and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	      and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	      and rsf.link_organization = @org_link 
	      and rsf.Version = (select max(rsf1.Version) 
		      from dbo.report_saved_forms as rsf1
		      where rsf1.link_form = rsf.link_form
            AND rsf1.del = 0
		      and rsf1.period_type = rsf.period_type
		      and rsf1.begin_date = rsf.begin_date
		      and rsf1.atr_code = rsf.atr_code
            and rsf1.link_organization = rsf.link_organization
            and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	      )
      END       
   END
   ELSE 
   BEGIN 
	   select top 1 @lsf = link_saved_form		
	   from dbo.report_saved_forms as rsf
	   inner join dbo.departments as d
	   on rsf.link_organization = d.link
	   left join dbo.kl_admin_bs as kab
	   on d.ved_link = kab.link
	   where rsf.link_form = @link_f
      AND rsf.del = 0
	   and rsf.period_type = @period_type
	   and rsf.period_number = @period_number
	   and rsf.begin_date = @period_date
	   and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	   and dbo.RT_IS_GRBS(rsf.link_saved_form) = @is_grbs -- грбс
	   and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	   and d.type = case isnull(@org_type,200) when 200 then d.type else @org_type end -- корреспондент
	   and isnull(kab.code,'') = case isnull(@ppp,'-1') when '-1' then isnull(kab.code,'') else rtrim(@ppp) end 
	   and left(ltrim(replace(d.okato,' ',''))+'00000000000',11) = case isnull(@okato,'-1') when '-1' then left(ltrim(replace(d.okato,' ',''))+'00000000000',11) else left(ltrim(replace(@okato,' ',''))+'00000000000',11) end 
	   and 1 = (select [type] from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
	   and rsf.Version = (select max(rsf1.Version) 
		   from dbo.report_saved_forms as rsf1
		   where rsf1.link_form = rsf.[Link_Form]
         AND rsf1.del = 0
		   and rsf1.period_type = rsf.period_type
		   and rsf1.begin_date = rsf.begin_date
		   and rsf1.atr_code = rsf.atr_code
         and rsf1.link_organization = rsf.link_organization
         and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	   )

     IF @lsf IS NULL 
      BEGIN
	   select top 1 @lsf = link_saved_form		
	   from dbo.report_saved_forms as rsf
	   inner join dbo.departments as d
	   on rsf.link_organization = d.link
	   left join dbo.kl_admin_bs as kab
	   on d.ved_link = kab.link
	   where rsf.link_form = @link_f1
      AND rsf.del = 0
	   and rsf.period_type = @period_type
	   and rsf.period_number = @period_number
	   and rsf.begin_date = @period_date
	   and rsf.atr_code like '%=' + rtrim(@ksbu) + '%'
	   and dbo.RT_IS_GRBS(rsf.link_saved_form) = @is_grbs -- грбс
	   and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
	   and d.type = case isnull(@org_type,200) when 200 then d.type else @org_type end -- корреспондент
	   and isnull(kab.code,'') = case isnull(@ppp,'-1') when '-1' then isnull(kab.code,'') else rtrim(@ppp) end 
	   and left(ltrim(replace(d.okato,' ',''))+'00000000000',11) = case isnull(@okato,'-1') when '-1' then left(ltrim(replace(d.okato,' ',''))+'00000000000',11) else left(ltrim(replace(@okato,' ',''))+'00000000000',11) end 
	   and 1 = (select [type] from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
	   and rsf.Version = (select max(rsf1.Version) 
		   from dbo.report_saved_forms as rsf1
		   where rsf1.link_form = rsf.[Link_Form]
         AND rsf1.del = 0
		   and rsf1.period_type = rsf.period_type
		   and rsf1.begin_date = rsf.begin_date
		   and rsf1.atr_code = rsf.atr_code
         and rsf1.link_organization = rsf.link_organization
         and isnull(rsf1.link_type_svod, 0) = isnull(rsf.link_type_svod, 0)
	   )      END       
      
   END

	return @lsf
END

GO


GRANT EXECUTE ON dbo.[RT_GET_LSF1] 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_SELECT_FORM_TOTALS_DOH_17]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RO_SELECT_FORM_TOTALS_DOH_17]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE FUNCTION dbo.[RO_SELECT_FORM_TOTALS_DOH_17] (
   @tMODE            TINYINT, -- 0 - Выбор итогов из КС, 1 - Выбор итогов из справочника REPORT_KBK, 2 - оба варианта.
   @iLINK_FORM       INT,
   @iPROPERTY_MASK   INT = 1   
)
RETURNS @tabReturn TABLE ([LINK_TABLE] INT, 
                          [CODE]       VARCHAR(250),
                          [CD]         VARCHAR(250))
AS
BEGIN
	declare @LinkTable int, @StartDate datetime, @Date DATETIME
	select @LinkTable = Link_Table from report_tables where Link_Form = @iLINK_FORM and orders = 1 and Doschet_Tree = 1
	if @LinkTable is NOT NULL
	begin
		select @StartDate = Start_Date from report_forms where Link_Form = @iLINK_FORM
      SET @Date = CONVERT(DATETIME, '20111231') + ISNULL((SELECT top 1 link FROM dbo.[BufferGetTableByID]('RO_RAZMNOJ_KS_OUTSIDE') bgtbi), 0)

		insert @tabReturn(Link_Table, Code, CD)
		select @LinkTable, SUBSTRING(Code, 4, 17), SUBSTRING(Code, 4, 17)
		from report_kbk T
		where T.code_form = 'ДОХОДЫ_' + LTRIM(STR(YEAR(@StartDate)))
            AND isnull(T.begin_date, '19000101') <= @Date AND ISNULL(T.end_date, '30000101') >= @Date
            and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= @Date AND ISNULL(T1.end_date, '30000101') >= @Date )
	end
   RETURN   
END

GO
GRANT ALL ON dbo.[RO_SELECT_FORM_TOTALS_DOH_17] 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.[RO_SELECT_FORM_TOTALS_IST_20]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RO_SELECT_FORM_TOTALS_IST_20]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE FUNCTION dbo.[RO_SELECT_FORM_TOTALS_IST_20] (
   @tMODE            TINYINT, -- 0 - Выбор итогов из КС, 1 - Выбор итогов из справочника REPORT_KBK, 2 - оба варианта.
   @iLINK_FORM       INT,
   @iPROPERTY_MASK   INT = 1   
)
RETURNS @tabReturn TABLE ([LINK_TABLE] INT, 
                          [CODE]       VARCHAR(250),
                          [CD]         VARCHAR(250))
AS
BEGIN
	declare @LinkTable int, @StartDate datetime, @Date DATETIME
	select @LinkTable = Link_Table from report_tables where Link_Form = @iLINK_FORM and orders in (2,3) and Doschet_Tree = 1
	if @LinkTable is NOT NULL
	begin
		select @StartDate = Start_Date from report_forms where Link_Form = @iLINK_FORM
      SET @Date = CONVERT(DATETIME, '20111231') + ISNULL((SELECT top 1 link FROM dbo.[BufferGetTableByID]('RO_RAZMNOJ_KS_OUTSIDE') bgtbi), 0)

		insert @tabReturn(Link_Table, Code, CD)
		select @LinkTable, LEFT(CODE,3) + SUBSTRING(Code, 7, 17), LEFT(CODE,3) + SUBSTRING(Code, 7, 17)
		from report_kbk T
		where T.code_form = 'ИСТОЧНИКИ_' + LTRIM(STR(YEAR(@StartDate)))
            AND isnull(T.begin_date, '19000101') <= @Date AND ISNULL(T.end_date, '30000101') >= @Date
            and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link  AND isnull(T1.begin_date, '19000101') <= @Date AND ISNULL(T1.end_date, '30000101') >= @Date )
	end
   RETURN   
END

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

GO
CREATE FUNCTION dbo.SA_EMPLS_INFO_PERIOD( @PERIOD_BEG DATETIME = NULL, @PERIOD_END DATETIME = NULL, @LINK_EMPL INT = NULL, @LINK_DEP INT = NULL )
RETURNS TABLE
RETURN

-- По каждому сотруднику выдать отделы и периоды работы, в которых он работал за заданный период 
SELECT DISTINCT
	SH.DEP_LINK,
	IM.EMPL_LINK,
	E.PERS_LINK,
	IM.num_stake, 
	IM.[status], 
	IM.ETS_RAZR, 
	S.LINK_KBK,
	PERIOD_BEG = 
		dbo.IS_MAX_DATE(
			(CASE WHEN IM.date_begin < ISNULL(@PERIOD_BEG,'19010101') THEN ISNULL(@PERIOD_BEG,'19010101') ELSE IM.date_begin END),
			(CASE WHEN S.date_begin < ISNULL(@PERIOD_BEG,'19010101') THEN ISNULL(@PERIOD_BEG,'19010101') ELSE S.date_begin END)
		),
	PERIOD_END = 
		dbo.IS_MIN_DATE(
			(CASE WHEN (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) > ISNULL(@PERIOD_END,'29990101') THEN ISNULL(@PERIOD_END,'29990101') ELSE (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) END),
			(CASE WHEN ISNULL(S.date_end,'19010101') < ISNULL(@PERIOD_END,'19010101') THEN ISNULL(S.date_end,'19010101') ELSE ISNULL(@PERIOD_END,'19010101') END)
		),			
	STAFF_HEAD = S.LINK_UP,
	STAFF_LINK = S.LINK,
	S.SUBDIV_LINK,
	S.POST_LINK,
	E.NOTWORK	
FROM 
	dbo.sa_item_move IM
	INNER JOIN dbo.STAFF_HEAD SH ON SH.LINK = IM.STAFF_LINK
	INNER JOIN dbo.EMPL E ON E.LINK = IM.EMPL_LINK
	LEFT JOIN DBO.ITEM_DIS_FACE IDF ON IDF.EMPL_LINK = E.LINK AND IDF.ACTIVE=1 AND COALESCE(IDF.DIS_DATE,'29990101') < ISNULL(@PERIOD_END,'29990101')
	LEFT JOIN dbo.staff S on IM.STAFF_LINK = S.LINK_UP 
		AND 
		(
			(case when IM.date_begin < ISNULL(@PERIOD_BEG,'19010101') THEN ISNULL(@PERIOD_BEG,'19010101') ELSE IM.date_begin END) 
			BETWEEN 
				CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_begin,104),104) 
			AND 
				ISNULL(CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_end,104),104),'29990101')
		OR
			(CASE WHEN (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) > ISNULL(@PERIOD_END,'29990101') THEN ISNULL(@PERIOD_END,'29990101') ELSE (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) END)
			BETWEEN 
				CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_begin,104),104) 
			AND 
				ISNULL(CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_end,104),104),'29990101')
		OR
			((CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_begin,104),104) BETWEEN 
					CONVERT(DATETIME,CONVERT(VARCHAR(10),@PERIOD_BEG,104),104) 
				AND 
					CONVERT(DATETIME,CONVERT(VARCHAR(10),@PERIOD_END,104),104))
			 and 
			 (CONVERT(DATETIME,CONVERT(VARCHAR(10),S.date_end,104),104) BETWEEN 
					CONVERT(DATETIME,CONVERT(VARCHAR(10),@PERIOD_BEG,104),104) 
				AND 
					CONVERT(DATETIME,CONVERT(VARCHAR(10),@PERIOD_END,104),104))		
			)
		
		)						
	LEFT JOIN dbo.subdiv D on S.SUBDIV_LINK = D.LINK_UP 
		AND 
		(
			(case when IM.date_begin < ISNULL(@PERIOD_BEG,'19010101') THEN ISNULL(@PERIOD_BEG,'19010101') ELSE IM.date_begin END) 
			BETWEEN 
				CONVERT(DATETIME,CONVERT(VARCHAR(10),D.date_begin,104),104) 
			AND 
				ISNULL(CONVERT(DATETIME,CONVERT(VARCHAR(10),D.date_end,104),104),'29990101')
		OR
			(CASE WHEN (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) > ISNULL(@PERIOD_END,'29990101') THEN ISNULL(@PERIOD_END,'29990101') ELSE (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) END)
			BETWEEN 
				CONVERT(DATETIME,CONVERT(VARCHAR(10),D.date_begin,104),104) 
			AND 
				ISNULL(CONVERT(DATETIME,CONVERT(VARCHAR(10),D.date_end,104),104),'29990101')
		)								
WHERE
	( @LINK_EMPL IS NULL OR E.LINK = @LINK_EMPL) 
	AND 
	(@LINK_DEP IS NULL OR E.DEP_LINK = @LINK_DEP)
	AND
	IM.active = 1 
	AND
	(case when IM.date_begin < ISNULL(@PERIOD_BEG,'19010101') THEN ISNULL(@PERIOD_BEG,'19010101') ELSE IM.date_begin END) BETWEEN ISNULL(@PERIOD_BEG,'19010101') AND ISNULL(@PERIOD_END,'29990101')
	AND
	(CASE WHEN (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) > ISNULL(@PERIOD_END,'29990101') THEN ISNULL(@PERIOD_END,'29990101') ELSE (CASE WHEN IDF.DIS_DATE < IM.date_end3 THEN IDF.DIS_DATE ELSE IM.date_end3 END) END) BETWEEN ISNULL(@PERIOD_BEG,'19010101') AND ISNULL(@PERIOD_END,'29990101')




GO


GRANT SELECT ON dbo.[SA_EMPLS_INFO_PERIOD] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.[sysobjects]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_SELECT_FORM_TOTALS]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RA_SELECT_FORM_TOTALS]
GO

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

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

*******************************************************************************/
-- Функция получения таблицы итогов формы.
CREATE FUNCTION dbo.[RA_SELECT_FORM_TOTALS] (
   @tMODE            TINYINT, -- 0 - Выбор итогов из КС, 1 - Выбор итогов из справочника REPORT_KBK, 2 - оба варианта.
   @iLINK_FORM       INT,
   @iPROPERTY_MASK   INT = 1   
)
RETURNS @tabReturn TABLE ([LINK_TABLE] INT, 
                          [CODE]       VARCHAR(250),
                          [CD]         VARCHAR(250))
AS
BEGIN
	declare @LinkTable int, @StartDate DATETIME, @Date DATETIME 
	select @LinkTable = Link_Table from report_tables where Link_Form = @iLINK_FORM and orders = 2 and Doschet_Tree = 1
	if @LinkTable is NOT NULL and @tMODE in (0, 2) -- досчет по дереву расходы
	begin
		select @StartDate = Start_Date from report_forms where Link_Form = @iLINK_FORM
      SET @Date = CONVERT(DATETIME, '20111231') + ISNULL((SELECT top 1 link FROM dbo.[BufferGetTableByID]('RO_RAZMNOJ_KS_OUTSIDE') bgtbi), 0)


		if YEAR(@StartDate) > 2010
		begin
			insert @tabReturn(Link_Table, Code, CD)
			select @LinkTable, Code, Code
			from report_kbk T
			where T.code_form = 'R_SPR_RASH_317_2011'
               AND isnull(T.begin_date, '19000101') <= @Date AND ISNULL(T.end_date, '30000101') >= @Date 
               and exists(select top 1 * from report_kbk T1 where T1.Link_Self = T.Link AND isnull(T1.begin_date, '19000101') <= @Date AND ISNULL(T1.end_date, '30000101') >= @Date )
			return
		end
	end


   DECLARE @lcFORM_CODE CHAR(20), @Region varchar(100)
   
   DECLARE @tabCODE_FORMS TABLE ([TAB_ORDER] INT,
                                 [CODE_FORM] VARCHAR(50)) 


	 set @Region = isnull((SELECT VALUE
					FROM S_OPTIONS
						WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'OBJ_FTP_REGION')
								AND SID IS NULL ),'')

                          
   IF @tMODE IN (0,2)
   BEGIN
      INSERT @tabReturn([LINK_TABLE], 
                        [CODE])
      SELECT DISTINCT [C].[LINK_TABLE],
                      [CODE] = RTRIM(ISNULL([D].[FORMULA],[B].[CODE_ROW]))
      FROM dbo.[REPORT_CONTROL_RULES] [A]
      JOIN dbo.[REPORT_CONTROL_ROWS]  [B] ON [A].[LINK_RULE] = [B].[LINK_RULE]
      JOIN dbo.[REPORT_TABLES]        [C] ON [C].[LINK_TABLE] = [B].[LINK_TABLE]
      LEFT JOIN dbo.[REPORT_FORMULA]  [D] ON [D].[LINK_ROW] = [B].[LINK_ROW] AND
                                             [D].[LINK_COL] = [C].[LINK_CODE_COL]                      
      WHERE /*(@tVAL_TYPE = 2 OR [C].[VAL_TYPE] = @tVAL_TYPE) AND */
            [A].[LINK_FORM] = @iLINK_FORM AND
            [A].[IsDoschet] = 1       AND
            [A].[SIGN_SR] = '='          AND
            [B].[VAL_TYPE] IN (0,3)   AND                                       
            ISNULL([D].[FORMULA],[B].[CODE_ROW]) <> ''
			and orderrow=1
			and (isnull(A.Region,'') = @Region or isnull(A.Region,'') = '')

      INSERT @tabReturn([LINK_TABLE], 
                        [CODE])
      SELECT DISTINCT [C].[LINK_TABLE],
                      [CODE] = SUBSTRING(RTRIM([B].[Maska]),2, LEN([B].[Maska]) - 2)
      FROM dbo.[REPORT_CONTROL_RULES] [A]
      JOIN dbo.[REPORT_CONTROL_ROWS]  [B] ON [A].[LINK_RULE] = [B].[LINK_RULE]
      JOIN dbo.[REPORT_TABLES]        [C] ON [C].[LINK_TABLE] = [B].[LINK_TABLE]
      LEFT JOIN dbo.[REPORT_FORMULA]  [D] ON [D].[LINK_ROW] = [B].[LINK_ROW] AND
                                             [D].[LINK_COL] = [C].[LINK_CODE_COL]                      
      WHERE /*(@tVAL_TYPE = 2 OR [C].[VAL_TYPE] = @tVAL_TYPE) AND */
            [A].[LINK_FORM] = @iLINK_FORM AND
            [A].[IsDoschet] = 1       AND
            [A].[SIGN_SR] = '='          AND
            [B].[VAL_TYPE] =4   AND                                       
            RTRIM([B].[Maska]) LIKE '''%'''
			and orderrow>1
			and (isnull(A.Region,'') = @Region or isnull(A.Region,'') = '')

   END
   
   IF @tMODE IN (1,2)
   BEGIN
         
      SELECT @lcFORM_CODE = [CODE]
      FROM dbo.[REPORT_FORMS]
      WHERE [LINK_FORM] = @iLINK_FORM
   
      IF @lcFORM_CODE IN ('0503110G','0503110M')
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (1,'110_01')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'110_02')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'110_03')
      END

      IF @lcFORM_CODE IN ('(72н)0503317M')
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'0503317M_02')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'0503317M_03')
      END
   
      IF @lcFORM_CODE = '(72н)0503317G'
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (1,'0503317G_01')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'0503317G_03')
      END
     
      IF @lcFORM_CODE IN ('0503317G','0503317M')
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'0503317M_02_2009')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'R_SPR_RASH_317_2011')

      END
/*
      IF @lcFORM_CODE IN ('0503317G')
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'0503317M_03_2009')
		END
*/
      IF @lcFORM_CODE IN ('0503314G','0503314M')
      BEGIN   
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'0503314G_02')       
		END

		

      IF @lcFORM_CODE IN ('(72н)0503314G','(72н)0521441')
      BEGIN                  
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (1,'0503314G_01')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'0503314G_03')
      END                 

      IF @lcFORM_CODE IN ('(72н)0521429')
      BEGIN                  
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (1,'0503317G_01')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'0503317G_01')
      END                 
            
		IF @lcFORM_CODE IN ('410G','410Gf','410Gm','410Gs')
		BEGIN
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (1,'410_01')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (2,'410_02')
         INSERT @tabCODE_FORMS([TAB_ORDER], [CODE_FORM]) VALUES (3,'410_03')
		END
            
      IF @lcFORM_CODE IN ('(72н)0503127M','(72н)0503117M')
      BEGIN                  
         INSERT @tabReturn([LINK_TABLE], 
                           [CODE])
         SELECT [B].[LINK_TABLE],
                [A].[CODE]                     
         FROM dbo.[REPORT_KBK]    [A]
         JOIN dbo.[REPORT_TABLES] [B] ON [B].[LINK_FORM] = @iLINK_FORM
         WHERE [A].[CODE_FORM] = '117M_02' AND
               [B].[ORDERS]    = 2         AND 
               RIGHT(RTRIM([CODE]),3) IN ('600','500','300','260','250','230','220','210','200','000','240')
               
      END
           
      IF @lcFORM_CODE IN ('0503314M')
      BEGIN
         DELETE @tabReturn
         WHERE [CODE] IN ('00085000000000000000',
                          '00087000000000000000',
                          '00087000000000000120',
                          '00087000000000000151',
                          '00087000000000001151',
                          '00087000000000002151',                          
                          '00096000000000000000',
                          '00097000000000000000',
                          '00097000000000000251',
                          '00097000000000000231',
                          '00079000000000000000',
                          '50000090000000000000000',
                          '52000001000000000000000',
                          '62000002000000000000000',
                          '70000001050000000000000',
                          '75000057000000000000000',
                          '75100057000000000000710',
                          '75200057000000000000810',
                          '75300057000000000000540',
                          '75400057000000000000640',
                          '75500057000000000000510',
                          '75600057000000000000610')
      END
            
      INSERT @tabReturn([LINK_TABLE], 
                        [CODE])
      SELECT [C].[LINK_TABLE],
             [A].[CODE]
      FROM dbo.[REPORT_KBK]    [A]
      JOIN @tabCODE_FORMS      [B] ON [A].[CODE_FORM] = [B].[CODE_FORM]
      JOIN dbo.[REPORT_TABLES] [C] ON [C].[LINK_FORM] = @iLINK_FORM AND
                                      [C].[ORDERS] = [B].[TAB_ORDER]
      WHERE [A].[PROPERTY] & @iPROPERTY_MASK = @iPROPERTY_MASK
      
   END

   UPDATE @tabReturn
   SET [CD] = [CODE]
   
   RETURN   
END

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

/*
   select * from report_forms where code = '(72н)0503127M'
   
select * from RN_VIEW_KBK_0503317M_03        where code like '%01050200000000600%'


   
   select distinct * from dbo.[RA_SELECT_FORM_TOTALS](1,1640,1)
   
   SELECT [LINK_TABLE],
          [CODE]
   FROM dbo.[RA_SELECT_FORM_TOTALS](1, 1530)
*/

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

GO

CREATE VIEW dbo.DOCUMENTS_DGH_T1

AS
SELECT 	[link] = LINK_UP,
	ORDERS,
	PERS_LINK,
	[FIO] = (SELECT rtrim(fm)+' '+left(im,1)+'.'+left(ot,1)+'.' FROM person WHERE LINK = PERS_LINK),
	LINK_PAY,
	[CODE_PAY] = P.CODE,
	[NAME_PAY] = P.[NAME],
	[SUMMA]	  = SUMMA,
	[NAME_DOG] = (SELECT '№ '+rtrim(NUMBER)+' от '+convert(varchar(20),DATE,104)  FROM SALARY_REESTR_DGH WHERE LINK = LINK_DOG),
	LINK_DOG,
	link_vkr,
	[name_vkr]= F.CODE,
	T.link_ekr,
	[code_ekr]= EKR.CODE,
	KATEG = 0
FROM 
	dbo.SDOC_DGH_TABLE T 
	left 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.DICTIONARY_ITEM EKR on EKR.LINK = T.LINK_EKR
WHERE T.[OBJECT] = 1

GO


GRANT SELECT ON dbo.[DOCUMENTS_DGH_T1] TO PUBLIC

GO


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

GO

CREATE VIEW dbo.DOCUMENTS_DGH_T2
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,
	T.link_ekr,
	[code_ekr]= EKR.CODE,
	LINK_DOG
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.DICTIONARY_ITEM EKR on EKR.LINK = T.LINK_EKR
WHERE 
	T.[OBJECT] = 2


GO


GRANT SELECT ON dbo.[DOCUMENTS_DGH_T2] 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
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.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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



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

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

CREATE     VIEW dbo.RO_DEP_RZPR_ACC_2011
AS

SELECT     K.Link, SUBSTRING(K.CODE, 4, 4) AS RzPr, A.Code AS Acc, A.Code
FROM         R_SPR_RASH_317_2011 K INNER JOIN
                      R_SPR_110_02_2011 A ON RIGHT(RTRIM(K.CODE), 3) = RIGHT(RTRIM(A.CODE), 3)
WHERE     ((RIGHT(rtrim(A.code), 3) IN ('251', '241') AND substring(ltrim(K.code), 4, 4) LIKE '14%') OR
                      (RIGHT(rtrim(A.code), 3) <> '251') AND NOT (substring(ltrim(K.code), 4, 4) LIKE '14%') OR
                      (RIGHT(rtrim(A.code), 3) = '251') AND NOT (substring(ltrim(K.code), 4, 4) LIKE '14%')) AND A.Code NOT IN ('240120211', '240120212', '240120213', 
                      '240120221', '240120222', '240120223', '240120224', '240120225', '240120226', '240120290', '240120241', '240120226', '240120263')AND substring(ltrim(A.code), 1, 6)not in ('140220','240220','740120')
UNION
SELECT     - 1, '0000', '000000960', '000000960'
UNION
SELECT     - 2, '0000', '240120211', '240120211'
UNION
SELECT     - 3, '0000', '240120212', '240120212'
UNION
SELECT     - 4, '0000', '240120213', '240120213'
UNION
SELECT     - 5, '0000', '240120221', '240120221'
UNION
SELECT     - 6, '0000', '240120222', '240120222'
UNION
SELECT     - 7, '0000', '240120223', '240120223'
UNION
SELECT     - 8, '0000', '240120224', '240120224'
UNION
SELECT     - 9, '0000', '240120225', '240120225'
UNION
SELECT     - 10, '0000', '240120226', '240120226'
UNION
SELECT     - 11, '0000', '240120290', '240120290'
UNION
SELECT     - 12, '0000', '240120273', '240120273'
UNION
SELECT     - 13, '0000', '240120241', '240120241'
UNION
SELECT     - 14, '0000', '240120226', '240120226'
UNION
SELECT     - 15, '0000', '240120263', '240120263'
UNION
SELECT     - 16, '0115', '140120271', '140120271'
UNION
SELECT     - 17, '0000', '140201000', '140201000'
UNION
SELECT     - 18, '0000', '240120262', '240120262'
UNION
SELECT     - 19, '0000', '240120261', '240120261'
UNION
SELECT     - 20, '0000', '240120242', '240120242'
UNION
SELECT     Link, CODE, '140120271', '140120271'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '140120272', '140120272'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '140120273', '140120273'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '240120271', '240120271'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '240120272', '240120272'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '121200000', '121200000'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '221200000', '221200000'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '130900000', '130900000'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT     Link, CODE, '230900000', '230900000'
FROM         dbo.R_SPR_RZPR_2011
WHERE     code NOT LIKE '14%'
UNION
SELECT link, '0000', CODE,CODE
FROM R_SPR_110_02_2011 
where substring(CODE,2,5)='40220'
UNION
SELECT link, '0000', CODE,CODE
FROM R_SPR_110_02_2011 
where substring(CODE,1,6)='740120'
GO
GRANT ALL ON dbo.[RO_DEP_RZPR_ACC_2011] 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.[ARestCalcSaldoChanges]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[ARestCalcSaldoChanges]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE     FUNCTION dbo.ARestCalcSaldoChanges ()
RETURNS @RET_TABLE	TABLE
	(
	[D_SUMMA]	[NUMERIC] (28,2),
	[K_SUMMA]	[NUMERIC] (28,2),
	[R_SUMMA]	[NUMERIC] (28,2),
	[D_QUANTITY]	[NUMERIC] (28,4),
	[K_QUANTITY]	[NUMERIC] (28,4),
	[DATE_PROV]	[DATETIME],
	[ACCOUNT]	[INT],
	[KBK]		[INT],
	[EKR]		[INT],
	[DEP]	[INT],
	[SUB]	[INT],
	[EMP]	[INT],
	[NOMEN]	[INT],
	[INV]	[INT],
	[KAU]	[INT],
	[DEP_ACC]	[INT],
	[TMC]	[INT],
	[INDATE]	[DATETIME],
	[AP1]	[INT],
	[AP2]	[INT],
	[AP3]	[INT],
	[SGU]	[INT],
	[DEP_LINK]	[INT],
	[PRICE]	[NUMERIC] (28,6),
	[PRICE_TYPE] [TINYINT]
	)
AS
BEGIN
	DECLARE @intPRICE_TYPE	INT
	SET @intPRICE_TYPE = ISNULL (dbo.BK_GET_NASTR_PRICE_TYPE_MZ (), 0)

	DECLARE @tSaldoChanges	TABLE (date datetime, account int)
	insert into @tSaldoChanges
	select DATE, ACCOUNT from dbo.SALDO_CHANGES group by DATE, ACCOUNT

	INSERT INTO @RET_TABLE
	SELECT 
	D_SUMMA = SUM(D_SUMMA),
	K_SUMMA = SUM(K_SUMMA),
	R_SUMMA = SUM(R_SUMMA),
	D_QUANTITY = SUM(D_QUANTITY),
	K_QUANTITY = SUM(K_QUANTITY),
	AP.DATE_PROV, AP.ACCOUNT,
	AP.KBK, AP.EKR, AP.DEP, AP.SUB, AP.EMP, AP.NOMEN, AP.INV, AP.KAU, AP.DEP_ACC, AP.TMC, AP.INDATE, AP.AP1, AP.AP2, AP.AP3, AP.SGU, AP.DEP_LINK,
	PRICE, PRICE_TYPE
	FROM
	(
		SELECT G.DATE_PROV, AP.ACCOUNT,
		[D_SUMMA] = CASE 
				WHEN SA.s_active = 0 THEN 0
				WHEN AP.DB_KR = 0
				THEN dbo.ARestCalcDtSaldo(1, SA.s_passive, G2.SUMMA, default)
				ELSE dbo.ARestCalcDtSaldo(1, SA.s_passive, default, G2.SUMMA)
				END,
		[K_SUMMA] = CASE
				WHEN SA.s_passive = 0 THEN 0
				WHEN AP.DB_KR = 0
				THEN dbo.ARestCalcKtSaldo(SA.s_active, 1, G2.SUMMA, default)
				ELSE dbo.ARestCalcKtSaldo(SA.s_active, 1, default, G2.SUMMA)
				END,
		[R_SUMMA] = 0,
		[D_QUANTITY] = CASE
				WHEN SA.KSU = 0 OR SA.s_active = 0 THEN 0
				WHEN AP.DB_KR = 0 THEN G2.QUANTITY ELSE -G2.QUANTITY END,
		[K_QUANTITY] = CASE
				WHEN SA.KSU = 0 OR SA.s_passive = 0 THEN 0
				WHEN AP.DB_KR = 1 THEN G2.QUANTITY ELSE -G2.QUANTITY END,
		
		KBK	= CASE WHEN SA.ap_KBK = 1 AND SA.OB_KBK = 0 THEN AP.KBK ELSE NULL END,
		EKR	= CASE WHEN SA.ap_EKR = 1 AND SA.OB_EKR = 0 THEN AP.EKR ELSE NULL END,
		DEP	= CASE WHEN SA.ap_DEP = 1 AND SA.OB_DEP = 0 THEN AP.DEP ELSE NULL END,
		SUB	= CASE WHEN SA.ap_SUB = 1 AND SA.OB_SUB = 0 THEN SUB.LINK_UP ELSE NULL END,
		EMP	= CASE WHEN SA.ap_EMP = 1 AND SA.OB_EMP = 0 THEN AP.EMP ELSE NULL END,
		NOMEN	= CASE WHEN SA.ap_NOMEN  = 1 AND SA.OB_NOMEN = 0 THEN AP.NOMEN  ELSE NULL END,
		INV	= CASE WHEN SA.ap_INV = 1 AND SA.OB_INV = 0 THEN AP.INV ELSE NULL END,
		KAU	= CASE WHEN SA.ap_KAU = 1 AND SA.OB_KAU = 0 THEN AP.KAU ELSE NULL END,
		DEP_ACC	= CASE WHEN SA.ap_DEP_ACC = 1 AND SA.OB_DEP_ACC = 0 THEN AP.DEP_ACC ELSE NULL END,
		TMC	= CASE WHEN SA.ap_TMC = 1 AND SA.OB_TMC = 0 THEN AP.TMC ELSE NULL END,
		INDATE	= CASE WHEN SA.ap_INDATE = 1 AND SA.P_DATE = 0 THEN AP.INDATE ELSE NULL END,
		AP1	= CASE WHEN SA.ap_AP1 = 1  AND SA.OB_AP1 = 0 THEN AP.AP1 ELSE NULL END,
		AP2	= CASE WHEN SA.ap_AP2 = 1  AND SA.OB_AP2 = 0 THEN AP.AP2 ELSE NULL END,
		AP3	= CASE WHEN SA.ap_AP3 = 1  AND SA.OB_AP3 = 0 THEN AP.AP3 ELSE NULL END,
		SGU	= CASE WHEN SA.p_Kassa = 1 THEN AP.SGU ELSE NULL END,
		[DEP_LINK] = G.DEP,
		[PRICE]	= CASE
				WHEN @intPRICE_TYPE = 1 AND SA.ap_NOMEN  = 1 AND SA.KSU = 1
					AND ISNULL (N.PRICE_TYPE, 0) = 1 AND G2.QUANTITY <> 0
				THEN  CONVERT (NUMERIC (28,6), G2.SUMMA / G2.QUANTITY)
				ELSE 0
			END,
		[PRICE_TYPE] = CASE WHEN @intPRICE_TYPE = 1 THEN ISNULL (N.PRICE_TYPE, 0) 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
		INNER JOIN dbo.G_PROV_AP AP ON AP.LINK_UP = G2.LINK
		INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = AP.ACCOUNT
		INNER JOIN @tSaldoChanges SC on SC.[DATE] = G.DATE_PROV AND SC.ACCOUNT = AP.ACCOUNT
		LEFT JOIN dbo.NOMENCLATURE N ON (N.LINK = AP.NOMEN
				AND N.PRICE_TYPE = 1
				AND SA.ap_NOMEN  = 1)
		LEFT JOIN dbo.SUBDIV SUB ON SUB.LINK = AP.SUB
		) AP
	GROUP BY AP.DATE_PROV, AP.ACCOUNT,
		AP.KBK, AP.EKR, AP.DEP, AP.SUB, AP.EMP, AP.NOMEN, AP.INV, AP.KAU, AP.DEP_ACC, AP.TMC, AP.INDATE, AP.AP1, AP.AP2, AP.AP3, AP.SGU, AP.DEP_LINK, PRICE, PRICE_TYPE
	
	-- !!!Обновление фактической цены списания, если послупление и списание было в 1 день!!! --
	UPDATE T1
	SET PRICE = T2.PRICE
	FROM @RET_TABLE	T1
	INNER JOIN @RET_TABLE T2 ON 
				(T2.D_QUANTITY > 0 AND T2.D_SUMMA > 0)
				AND ISNULL (T2.ACCOUNT, 0) = ISNULL (T1.ACCOUNT, 0)
				AND ISNULL (T2.KBK, 0) = ISNULL (T1.KBK, 0)
				AND ISNULL (T2.EKR, 0) = ISNULL (T1.EKR, 0)
				AND ISNULL (T2.DEP, 0) = ISNULL (T1.DEP, 0)
				AND ISNULL (T2.SUB, 0) = ISNULL (T1.SUB, 0)
				AND ISNULL (T2.EMP, 0) = ISNULL (T1.EMP, 0)
				AND ISNULL (T2.DEP_LINK, 0) = ISNULL (T1.DEP_LINK, 0)
				AND ISNULL (T2.NOMEN, 0) = ISNULL (T1.NOMEN, 0)
				AND ISNULL (T2.INV, 0) = ISNULL (T1.INV, 0)
				AND ISNULL (T2.KAU, 0) = ISNULL (T1.KAU, 0)
				AND ISNULL (T2.DEP_ACC, 0) = ISNULL (T1.DEP_ACC, 0)
				AND ISNULL (T2.TMC, 0) = ISNULL (T1.TMC, 0)
				AND ISNULL (T2.INDATE, '17530101') = ISNULL (T1.INDATE, '17530101')
				AND ISNULL (T2.AP1, 0) = ISNULL (T1.AP1, 0)
				AND ISNULL (T2.AP2, 0) = ISNULL (T1.AP2, 0)
				AND ISNULL (T2.AP3, 0) = ISNULL (T1.AP3, 0)
				AND CONVERT (NUMERIC (28,2), T2.PRICE) = CONVERT (NUMERIC (28,2), T1.PRICE)
	WHERE T1.PRICE_TYPE = 1
		AND (T1.D_QUANTITY < 0 OR T1.D_SUMMA < 0)

	RETURN 
END

GO


GRANT SELECT ON dbo.[ARestCalcSaldoChanges] TO PUBLIC

GO


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


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

GO
CREATE VIEW  dbo.DOCUMENTS_INVOICE_ISSUED_OLD
AS
 	SELECT 	
		G.LINK,
		G.NUMBER,
		[SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		[FLAG_JC] = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
	
	[BOOK_SALES] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BOOK_SALES_ISSUED'))),
	
	[DEP_LINK]	=	G.DEP,-- для X_SELECT_DOCUMENT_LIST_ZB
	[SEL_LINK]	=	G.DEP,
	[SEL_CODE]	=	CONVERT(VARCHAR(10),(SELECT CODE FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),
	[SEL_NAME]	=	CONVERT(varchar(100),(SELECT NAME FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),

	[BUY_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BUYER_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[BUY_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BUYER_LINK')),
	[BUY_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BUYER_LINK') AND D.LINK = GPD.DEPARTMENT)),

	[CONS2_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[CONS2_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK')),
	[CONS2_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[CONS1_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK')),

	[DATE_BASE] = CONVERT(DATETIME, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DATE_BASE_DOCUMENT')),104),
	[PROD_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_ISSUED_PRODUCER_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[PROD_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_ISSUED_PRODUCER_LINK')),
	[PROD_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_ISSUED_PRODUCER_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[OSNOV] = GPO.OSNOV, 
	[DOG_LINK]= OSN.DOC_LINK,
	[DOG_CODE]= OSN.NUMBER,
	[NALOG_DOC] = CONVERT(NUMERIC(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'INVOICE_ISSUED_NALOG_DOC'))),
	[NUM_BASE] = CONVERT(VARCHAR(6), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'NUMBER_BASE_DOCUMENT'))),
	[CONS2_SELF] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELF_CONSIGNEE'))),
	[CONS1_SELF] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELF_CONSIGNOR'))),
	[CONS1_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[CONS1_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[PAYS_LINK]  =		(SELECT GPR.DOC_REF_FOREIGN FROM dbo.G_PROV_REF GPR WHERE GPR.DOC_REF_PRIMARY = G.LINK AND GPR.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'PAYS_LINK_ISSUED')),
	[TAX_RATE] = CONVERT(NUMERIC(4,2), (SELECT GPV_TAX.VALUE FROM dbo.G_PROV_VALUE as GPV_TAX WITH (NOLOCK)  WHERE GPV_TAX.DOC_LINK = G.LINK AND GPV_TAX.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_INVOICE_ISSUED_TAX')))
	FROM dbo.G_PROV as G WITH (NOLOCK)
	LEFT JOIN dbo.G_PROV_OSNOV GPO ON (GPO.DOC_LINK = G.LINK
		AND GPO.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'INVOICE_ISSUED_DOG_LINK'))
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = GPO.OSNOV)
	WHERE G.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_ISSUED')


GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_ISSUED_OLD] 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.CalcDocSumma(G.LINK), G.SUMMA),
		SUMMA_NDS	= P.SUMMA_NDS,
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		DEP_LINK	=	G.DEP, -- для x_list_documents_zb
		FLAG_JC = CASE WHEN G.DATE_PROV IS NULL THEN 0 ELSE 1 END,

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

		BO_NUM = P.BO_NUM,

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

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




GO


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

-- Если печать справки не из документа Бух. справка, то должно быть @intNASTR_SPRAV = 1

CREATE FUNCTION dbo.BK_PrintDoc_F0504033_DATA
		(@cBuffer_Name VARCHAR (100),
		@intNASTR_SPRAV	TINYINT = 0)

	RETURNS @RET_TABLE TABLE 
		(LINK_DOC INT,
		dDOC_DATE DATETIME,
		DOC_DATE VARCHAR (10),
		PROV_DATE VARCHAR (10),
		DOC_NUM VARCHAR(30),
		COMMENT VARCHAR (254),
		DOC_NAME VARCHAR(254),
		DOC_TITLE VARCHAR(254),
		DEP_LINK INT,
		DEP_NAME VARCHAR(254),
		OKPO VARCHAR(254),
		REASON VARCHAR(254),
		DT VARCHAR(254),
		KT VARCHAR(254),
		QTY NUMERIC(20,4),
		SUMMA NUMERIC(20,2),
		GLBUH VARCHAR(254),
		ORD1 INT, ORD2 INT,
		LINK_G1 INT,
		LINK_G2 INT,
		PRN_ANALIT INT,
		APD_NAME VARCHAR (3000),
		APK_NAME VARCHAR (3000),
		PRN_RUK	INT,
		PRN_GLBUH INT,
		ECON_OPER INT,
		LIST_JO VARCHAR (100))

AS
BEGIN
	DECLARE @intPRN_GLBUH INT,
		@intPRN_RUK INT,
		@intANALIT	INT,
		@strLIST_JO	VARCHAR (100),
		@intLINK_JO	INT,
		@iPrintDate tinyint
		
	SELECT @intPRN_GLBUH = ISNULL (dbo.XK_GET_NASTR_INT ('DOCUMENTS_F0504833_OPT_GL_BUH'), 0),
		@intPRN_RUK = ISNULL (dbo.XK_GET_NASTR_INT ('DOCUMENTS_F0504833_OPT_RUKOV'), 0),
		@intANALIT = ISNULL (dbo.XK_GET_NASTR_INT ('DOCUMENTS_F0504833_OPT_ANALIT'), 0),
		@iPrintDate = isnull(dbo.XK_GET_NASTR_INT('DOCUMENTS_F0504833_OPT_DATE'),0)

	IF @intANALIT = 0
		INSERT INTO @RET_TABLE
		SELECT 
			BUF.LINK,
			G.[DATE], CONVERT (VARCHAR (10), G.[DATE], 104),
			CONVERT (VARCHAR (10), case @iPrintDate when 0 then G.[DATE] else G.[DATE_PROV] end, 104),
			G.NUMBER, G.COMMENT,
			'', --dbo.JurnalProvGetDocKind(G.LINK, G.OBJECT),
			CASE
				WHEN SO.CODE IN ('DOCUMENTS_F0504833', 'DOCUMENTS_F0504833ZB')	THEN ''
				ELSE 'к документу ' + dbo.JurnalProvGetDocKind(G.LINK, G.OBJECT) + ' № ' + G.NUMBER
			END,	
			G.DEP,
--			DD.FULL_NAME,
			dbo.BK_GET_PRINT_DEP_NAME (DD.LINK),
			DD.OKPO,
			T1.NAME_OPER,
			T1.ACCT_CD_D,
			T1.ACCT_CD_K,
			T1.QTY,
			T1.SUMMA,
			'',
			T1.ORDERS_G1, T1.ORDERS_G2,
			T1.LINK_G1,
			T1.LINK_G2,
			@intANALIT,
			'',
			'',
			@intPRN_RUK, 
			@intPRN_GLBUH,
			T1.XOZ_OPER,
			''

		FROM dbo.BufferGetTableByID(@cBuffer_Name) BUF
		INNER JOIN dbo.G_PROV G ON (G.LINK = BUF.LINK)
		INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = G.OBJECT)
		INNER JOIN dbo.BK_PrintDocProv (DEFAULT, @intNASTR_SPRAV) T1 ON (T1.LINK_G = BUF.LINK)
		LEFT JOIN dbo.DEPARTMENTS DD ON DD.LINK = G.DEP
	ELSE
		INSERT INTO @RET_TABLE
		SELECT 
			BUF.LINK,
			G.[DATE], 
			CONVERT (VARCHAR (10), G.[DATE], 104), 
			CONVERT (VARCHAR (10), case @iPrintDate when 0 then G.[DATE] else G.[DATE_PROV] end, 104),
			G.NUMBER, G.COMMENT,
			'', -- dbo.JurnalProvGetDocKind(G.LINK, G.OBJECT),
			CASE
				WHEN SO.CODE IN ('DOCUMENTS_F0504833', 'DOCUMENTS_F0504833ZB')	THEN ''
				ELSE 'к документу ' + dbo.JurnalProvGetDocKind(G.LINK, G.OBJECT) + ' № ' + G.NUMBER
			END,	
			G.DEP,
--			DD.FULL_NAME,
			dbo.BK_GET_PRINT_DEP_NAME (DD.LINK),
			DD.OKPO,
			T1.NAME_OPER,
			T1.ACCT_CD_D,
			T1.ACCT_CD_K,
			T1.QTY,
			T1.SUMMA,
			'',
			T1.ORDERS_G1, T1.ORDERS_G2,
			T1.LINK_G1,
			T1.LINK_G2,
			@intANALIT,
			ISNULL ('ЭКР - ' + RTRIM (D_EKR.[CODE]) + ' ' + RTRIM (D_EKR.[NAME]) + '; ', '') 
				+ ISNULL ('Орг. - ' + RTRIM (D_DEP.[NAME]) + '; ', '')
				+ ISNULL ('Отд. - ' + RTRIM (D_SUB.[NAME]) + '; ', '')
				+ CASE WHEN GAP_D.EMP IS NULL THEN '' ELSE 'Сотр. - ' + RTRIM (dbo.sd_GetEmplName (GAP_D.EMP))  + '; ' END
				+ ISNULL ('Номенкл. - ' + RTRIM (D_NOMEN.[CODE]) + ' ' + RTRIM (D_NOMEN.[NAME]) + '; ', '') 
				+ ISNULL ('Инв. - ' + RTRIM (D_INV.[CODE]) + ' ' + RTRIM (D_INV.[NAME]) + '; ', '')
				+ ISNULL ('КАУ - ' + RTRIM (D_KAU.[CODE]) + ' ' + RTRIM (D_KAU.[NAME]) + '; ', '')
				+ ISNULL ('Сч. - ' + RTRIM (D_DEP_ACC.[CODE]) + ': ' + RTRIM (D_DEP_ACC.ANAME) + '; ', '')
				+ ISNULL ('ТМЦ - ' + RTRIM (D_TMC.[NAME]) + '; ', '')
				+ ISNULL ('Осн. - ' + RTRIM (D_OSN.[INFO]) + '; ', '')
				+ ISNULL ('Доп. кл. - ' + RTRIM (D_DOP.[NAME]) + '; ', '') 
				+ ISNULL ('Дата - ' + CONVERT (VARCHAR (10), GAP_D.INDATE, 104) + '; ', '') AS APD_NAME,

			ISNULL ('ЭКР - ' + RTRIM (K_EKR.[CODE]) + ' ' + RTRIM (K_EKR.[NAME]) + '; ', '')
				+ ISNULL ('Орг. - ' + RTRIM (K_DEP.[NAME]) + '; ', '')
				+ ISNULL ('Отд. - ' + RTRIM (K_SUB.[NAME]) + '; ', '')
				+ CASE WHEN GAP_K.EMP IS NULL THEN '' ELSE 'Сотр. - ' + RTRIM (dbo.sd_GetEmplName (GAP_K.EMP)) + '; ' END
				+ ISNULL ('Номенкл. - ' + RTRIM (K_NOMEN.[CODE]) +  ' ' + RTRIM (K_NOMEN.[NAME]) + '; ', '') 
				+ ISNULL ('Инв. - ' + RTRIM (K_INV.[CODE]) + ' ' + RTRIM (K_INV.[NAME]) + '; ', '')
				+ ISNULL ('КАУ - ' + RTRIM (K_KAU.[CODE]) + ' ' + RTRIM (K_KAU.[NAME]) + '; ', '')
				+ ISNULL ('Сч. - ' + RTRIM (K_DEP_ACC.[CODE]) + ': ' + RTRIM (K_DEP_ACC.ANAME) + '; ', '')
				+ ISNULL ('ТМЦ - ' + RTRIM (K_TMC.[NAME]) + '; ', '')
				+ ISNULL ('Осн. - ' + RTRIM (K_OSN.[INFO]) + '; ', '')
				+ ISNULL ('Доп. кл. - ' + RTRIM (K_DOP.[NAME]) + '; ', '') 
				+ ISNULL ('Дата ' + CONVERT (VARCHAR (10), GAP_K.INDATE, 104) + '; ', '') AS APK_NAME,
			@intPRN_RUK, 
			@intPRN_GLBUH,
			T1.XOZ_OPER,
			''

		FROM dbo.BufferGetTableByID(@cBuffer_Name) BUF
		INNER JOIN dbo.G_PROV G ON (G.LINK = BUF.LINK)
		INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = G.OBJECT)
		INNER JOIN dbo.BK_PrintDocProv (DEFAULT, @intNASTR_SPRAV) T1 ON (T1.LINK_G = BUF.LINK)
		LEFT JOIN dbo.DEPARTMENTS DD ON DD.LINK = G.DEP

		LEFT JOIN dbo.G_PROV_AP GAP_D ON (GAP_D.LINK_UP = T1.LINK_G2
				AND GAP_D.DB_KR = 0)
		LEFT JOIN dbo.KOSGU D_EKR ON (D_EKR.LINK = GAP_D.EKR)
		LEFT JOIN dbo.DEPARTMENTS D_DEP ON (D_DEP.LINK = GAP_D.DEP)
		LEFT JOIN dbo.SUBDIV D_SUB ON (D_SUB.LINK = GAP_D.SUB)
		LEFT JOIN dbo.NOMENCLATURE D_NOMEN ON (D_NOMEN.LINK = GAP_D.NOMEN)
		LEFT JOIN dbo.INVENTORY D_INV ON (D_INV.LINK = GAP_D.INV)
		LEFT JOIN dbo.KAU D_KAU ON (D_KAU.LINK = GAP_D.KAU)
		LEFT JOIN dbo.DICTIONARY_ACCOUNTS D_DEP_ACC ON (D_DEP_ACC.LINK = GAP_D.DEP_ACC)
		LEFT JOIN dbo.DICTION D_TMC ON (D_TMC.LINK = GAP_D.TMC)
		LEFT JOIN dbo.BD_OSNOV D_OSN ON (D_OSN.LINK = GAP_D.AP1)
		LEFT JOIN dbo.DOP_CLASSIF D_DOP ON (D_DOP.LINK = GAP_D.AP2)

		LEFT JOIN dbo.G_PROV_AP GAP_K ON (GAP_K.LINK_UP = T1.LINK_G2
				AND GAP_K.DB_KR = 1)
		LEFT JOIN dbo.KOSGU K_EKR ON (K_EKR.LINK = GAP_K.EKR)
		LEFT JOIN dbo.DEPARTMENTS K_DEP ON (K_DEP.LINK = GAP_K.DEP)
		LEFT JOIN dbo.SUBDIV K_SUB ON (K_SUB.LINK = GAP_K.SUB)
		LEFT JOIN dbo.NOMENCLATURE K_NOMEN ON (K_NOMEN.LINK = GAP_K.NOMEN)
		LEFT JOIN dbo.INVENTORY K_INV ON (K_INV.LINK = GAP_K.INV)
		LEFT JOIN dbo.KAU K_KAU ON (K_KAU.LINK = GAP_K.KAU)
		LEFT JOIN dbo.DICTIONARY_ACCOUNTS K_DEP_ACC ON (K_DEP_ACC.LINK = GAP_K.DEP_ACC)
		LEFT JOIN dbo.DICTION K_TMC ON (K_TMC.LINK = GAP_K.TMC)
		LEFT JOIN dbo.BD_OSNOV K_OSN ON (K_OSN.LINK = GAP_K.AP1)
		LEFT JOIN dbo.DOP_CLASSIF K_DOP ON (K_DOP.LINK = GAP_K.AP2)

	-- Список ЖО, по которым были операции --
	DECLARE @TAB_JO_LINKS TABLE (JO INT, TEST_FLAG TINYINT)

	INSERT INTO @TAB_JO_LINKS
	SELECT XOJ.JURN_LINK, 0
	FROM dbo.XOZ_OPER_JURN XOJ
	INNER JOIN @RET_TABLE RT ON (RT.ECON_OPER = XOJ.XOZ_LINK)
	GROUP BY XOJ.JURN_LINK

	SET @strLIST_JO	= ''
	WHILE EXISTS (SELECT * FROM @TAB_JO_LINKS WHERE TEST_FLAG = 0)
	BEGIN
		SET @intLINK_JO = (SELECT TOP 1 JO FROM @TAB_JO_LINKS WHERE TEST_FLAG = 0)
		SET @strLIST_JO = LTRIM (@strLIST_JO)
			+ CASE 
				WHEN @strLIST_JO = '' THEN ''
				ELSE ', '
			END
			+ ISNULL ((SELECT RTRIM (CODE) FROM dbo.JOURNAL_OPERATION WHERE LINK = @intLINK_JO), '')

		UPDATE @TAB_JO_LINKS SET TEST_FLAG = 1
		WHERE JO = @intLINK_JO
	END

	UPDATE @RET_TABLE SET LIST_JO = @strLIST_JO

	RETURN 
END
GO

GRANT SELECT ON dbo.[BK_PrintDoc_F0504033_DATA] 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].[KJ_PERS_PENSION]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[KJ_PERS_PENSION]
GO




/*
© Кейсистемс (Keysystems), 2008
*/
CREATE VIEW [dbo].KJ_PERS_PENSION
AS
select	*
from	(
	SELECT	[LINK]		= PERS_PENS.LINK,
		[PERS_LINK]	= PERS.LINK,
		[FIO] 		= CONVERT(VARCHAR(200),PERS.FIO),
		[DATE_PENS]	= PERS_PENS.PENS_DATE,
		[DOC_NUM]	= PERS_PENS.DOC_NUMBER,
		[DOC_DATE]	= PERS_PENS.DOC_DATE,
		[COMMENT]	= PERS_PENS.COMMENT,
		[CHECK_SZV] = PERS_PENS.CHECK_SZV,
		[CHECK_SZVC] = case when PERS_PENS.CHECK_SZV = 1 then 'Вкл.' else '' end,
		[WORK_PENS] = PERS_PENS.WORK_PENS,
		[WORK_PENSC] = case when PERS_PENS.WORK_PENS = 1 then 'Вкл.' else '' end 
	FROM	PERS_PENSION PERS_PENS right JOIN KU_PERSON PERS
		ON PERS_PENS.PERS_LINK = PERS.LINK
	) t
where t.link is not null

GO

GRANT SELECT ON dbo.[KJ_PERS_PENSION] 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].BB_ZAYAVKA_KR') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].BB_ZAYAVKA_KR
GO

CREATE VIEW dbo.BB_ZAYAVKA_KR
AS

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

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

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

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




GO

grant all on BB_ZAYAVKA_KR to public
GO

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

GO



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

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

	      ВОЗВРАЩАЕТ РАЗНИЦУ МЕЖДУ ДАТАМИ В ФОРМАТЕ СТАЖА В ВИДЕ ТАБЛИЦЫ
				  (ЛЕТ , МЕСЯЦЕВ, ДНЕЙ)

		за основу взята функция вычисления стажа ku_EmplExpirTable
*******************************************************************************/

CREATE       FUNCTION dbo.kj_GetExpirDateDiffTable (
	@date1	datetime,
	@date2	datetime,
	@koef	numeric(9,2)
)  
RETURNS @R TABLE (years INT, months INT, days INT, yymmdd varchar(20))
AS  
BEGIN 
	DECLARE @YEARS numeric(9,2), @MONTHS numeric(9,2), @DAYS numeric(9,2), @LASTDAY INT

	SET @YEARS = (YEAR(@date2+1) - YEAR(@date1)) * @koef
	SET @MONTHS = (MONTH(@date2+1) - MONTH(@date1)) * @koef
	SET @DAYS = (DAY(@date2+1) - DAY(@date1) +	CASE WHEN DAY(dbo.DateEndOfMonth(@date1)) = 31 AND DAY(@date1) = 31
													   AND DAY(dbo.DateEndOfMonth(@date2)) = 30 AND DAY(@date2) = 30 THEN 1
													 ELSE 0
												END
				) * @koef

	SET @LASTDAY =  CASE WHEN MONTH(@date1) = 2 THEN 30
						 ELSE datepart(day, dbo.DateBeginOfMonth(@date2+1) - 1)
					END

	SET @years = convert(int, @years)
	SET @months = @months + (@years-convert(int, @years)) * 12
	SET @months = convert(int, @months)
	SET @days = @days + (@months-convert(int, @months)) * @lastday
	IF @days < 0 BEGIN
		SET @months = @months - 1
		SET @days = @days + @lastday
	END
	IF @months < 0 BEGIN
		SET @years = @years - 1
		SET @months = @months + 12
	END


	DECLARE @R_TEMP TABLE (years numeric(5,2), months numeric(5,2), days numeric(5,2))
	INSERT @R_TEMP
	SELECT isnull(sum(@years*@koef), 0), isnull(sum(@months*@koef), 0), isnull(sum(@days*@koef), 0)

	UPDATE @R_TEMP SET months = months + case when convert(int, years) != 0 then 12*(years - convert(int, years)) else 12*years end, years = convert(int, years)
	UPDATE @R_TEMP SET days = days + case when convert(int, months) != 0 then 30*(months - convert(int, months)) else 30*months end, months = convert(int, months)

	WHILE exists(SELECT * FROM @R_TEMP WHERE days>=30)
		UPDATE @R_TEMP SET days = days - 30, months = months + 1 WHERE days>=30

	WHILE exists(SELECT * FROM @R_TEMP WHERE months>=12)
		UPDATE @R_TEMP SET months = months - 12, years = years + 1 WHERE months>=12


	INSERT @R
	SELECT years, months, days, 
	--'' 
		   case when years < 9 then '0' + convert(varchar(1),ltrim(str(years))) else convert(varchar(2),ltrim(str(years))) end + ' г. ' +  
		   case when months < 9 then '0' + convert(varchar(1),ltrim(str(months))) else convert(varchar(2),ltrim(str(months))) end + ' м. ' + 
		   case when days < 9 then '0' + convert(varchar(1),ltrim(str(days))) else convert(varchar(2),ltrim(str(days))) end + ' д. ' 

	from @R_TEMP

	RETURN
				
END



GO


GRANT SELECT ON dbo.[kj_GetExpirDateDiffTable] TO PUBLIC

GO

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

GO

CREATE FUNCTION [dbo].KJ_GET_EDUC_EMPL(@link_empl int)
/*
	Функция возвращает информацию о учебных заведениях и датах их окончания, которые закончил человек @link_empl
*/
RETURNS varchar(3000)
AS
BEGIN

declare @str varchar(3000)

declare @tbl table (cod int,SCHOOL_NAME varchar(400),DATE_END datetime, SPEC_NAME varchar(500),QUALIFY varchar(200), EDUC_NAME VARCHAR(80))
declare @i int
	
	insert into @tbl (cod,SCHOOL_NAME,DATE_END,SPEC_NAME,QUALIFY, EDUC_NAME)
	select LINK, SCHOOL_NAME, DATE_END, SPEC_NAME, QUALIFY, EDUC_NAME
	from KU_PERS_EDUCATION
	where PERS_LINK = (select pers_link from empl where link = @link_empl)

	update @tbl set SCHOOL_NAME = REPLACE(SCHOOL_NAME, 'институт', 'ин-т')
	update @tbl set SCHOOL_NAME = REPLACE(SCHOOL_NAME, 'университет', 'ун-т')
	update @tbl set SCHOOL_NAME = REPLACE(SCHOOL_NAME, 'техникум', 'тех.')
	update @tbl set SCHOOL_NAME = REPLACE(SCHOOL_NAME, 'училище', 'уч.')
	update @tbl set SCHOOL_NAME = REPLACE(SCHOOL_NAME, 'академия', 'ак.')

	set @str = ''
	while exists (select * from @tbl)
	begin
		select @i = min(cod) from @tbl
		select @str = (
					case	when len(rtrim(ltrim(isnull(EDUC_NAME,'')))) = 0 then ''
								else rtrim(ltrim(isnull(EDUC_NAME,''))) + ', '
						  end + 
					case when len(@str + rtrim(SCHOOL_NAME) + ' ' + convert(varchar(10),year(DATE_END))  
						+ case	when len(rtrim(ltrim(isnull(SPEC_NAME,'')))) = 0 and len(rtrim(ltrim(QUALIFY))) = 0 then ''
							else ' (' + rtrim(
								    case when len(rtrim(ltrim(isnull(SPEC_NAME,'')))) = 0 then ''
									 else 'спец. '  + rtrim(ltrim(isnull(SPEC_NAME,''))) + '; '
								    end +
								    case when len(rtrim(ltrim(QUALIFY))) = 0 then ''
									 else 'квал. '  + rtrim(ltrim(QUALIFY))
								    end) + 
							     ')'
						  end +', ') < 3000
					then (@str + rtrim(SCHOOL_NAME) + ', год окончания ' + convert(varchar(4),year(DATE_END))  
						  + case	when len(rtrim(ltrim(isnull(SPEC_NAME,'')))) = 0 and len(rtrim(ltrim(QUALIFY))) = 0 then ''
							else ' (' + rtrim(
								    case when len(rtrim(ltrim(isnull(SPEC_NAME,'')))) = 0 then ''
									 else 'спец. '  + rtrim(ltrim(isnull(SPEC_NAME,''))) + case when len(rtrim(ltrim(QUALIFY))) != 0 then '; ' else '' end
								    end +
								    case when len(rtrim(ltrim(QUALIFY))) = 0 then ''
									 else 'квал. '  + rtrim(ltrim(QUALIFY))
								    end) + 
							     ')'
						  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
	RETURN left(@str,@length)
END



GO


GRANT EXECUTE ON dbo.[KJ_GET_EDUC_EMPL] TO PUBLIC

GO


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


GO

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








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

******************************************************************************


*/
CREATE       VIEW dbo.REPORT_FORM14_RAZD_NAME
AS
SELECT link, code as shifr, 0 AS Razd_link, left(code_str,4) AS Razd_Code, '' as Razd_Name, 
		0 AS Cel_st_link, substring(code_str, 5,7) as Cel_st_Code, '' as Cel_st_Name,
       0 AS VR_Link, substring(code_str,12,3) AS VR_Code,'' AS VR_Name,
        ISNULL(link_self, 0) as link_self,
       CASE WHEN EXISTS
                   (SELECT *
                    FROM   dbo.r_spr_kbk_0503074
                    WHERE link_self = r.link) THEN CONVERT(bit, 0) ELSE CONVERT(bit, 1) END AS childrens, 0 AS imageindex, 0 AS checked,
		left(code_str,4) + ' ' + substring(code_str,5,7) + ' ' + substring(code_str,12,3) + ' ' + code + ' ' + name as name, name as name_str,
      begin_date, end_date
FROM [dbo].[RO_KBK_HIST_VIEW] R
where code_form = 'r_spr_kbk_0503074'





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

CREATE   Function dbo.BB_DEP_NAME_FOR_SHABLON(@cShablon varchar(254), @iLinkDep int = null, @iLinkDepAcc int = null)
RETURNS varchar(254)
AS
BEGIN
--set @cShablon = UPPER(@cShablon)
if @iLinkDepAcc is not null
	select @iLinkDep = case when @iLinkDep is null then DA.REF_LINK_D else @iLinkDep end,   
			@cShablon = rtrim(replace(replace(replace(replace(replace(replace(replace(replace(replace(@cShablon, 
			'<Филиал_банка>', isnull(rtrim(DA.BANK_FILIAL),'')), 
			'<БИК_банка>', isnull(rtrim(DA.BANK_CODE),'')), 
			'<Наим_банка>', isnull(rtrim(DA.BANK_NAME),'')), 
			'<Счет_ОФК>', isnull(rtrim(DA.K_ACC_CODE),'')), 
			'<ОФК>', isnull(rtrim(DA.KAZN_NAME),'')), 
			'<ОФК_полн>', isnull(rtrim(DA.KAZN_F_NAME),'')), 
			'<ИНН_ОФК>', isnull(rtrim(DA.KAZN_INN),'')), 
			'<Счет>', isnull(rtrim(DA.CODE),'')), 
			'<Счет_лиц>', isnull(rtrim(case DA.TYPE when 1 then '' else 'Л/С ' + DA.CODE end),''))) 
	from DICTIONARY_ACCOUNTS DA
	where DA.LINK = @iLinkDepAcc
else
	set @cShablon = replace(replace(replace(replace(replace(replace(@cShablon, '<ФИЛИАЛ_БАНКА>', ''), '<БИК_БАНКА>', ''), '<НАИМ_БАНКА>', ''), '<СЧЕТ_ОФК>', ''), '<ОФК>', ''), '<СЧЕТ>', '') 

if @iLinkDep is not null
	select @cShablon = rtrim(replace(replace(replace(replace(replace(replace(replace(@cShablon, 
			'<ИНН_орг>', isnull(rtrim(D.INN),'')), 
			'<КПП_орг>', isnull(rtrim(D.KPP),'')), 
			'<Наим_орг_полн>', rtrim(D.FULL_NAME)), 
			'<Наим_орг>', rtrim(D.NAME)),
			'<Префикс_орг>', rtrim(D.PREFIX)),
			'<ОФК_орг>', isnull(rtrim(T.NAME),'')), 
			'<ОФК_полн_орг>', isnull(rtrim(T.FULL_NAME),'')))
	from DEPARTMENTS D
	left join TREASURY T on D.TOFK_LINK = T.LINK
	where D.LINK = @iLinkDep
else
	set @cShablon = replace(replace(replace(@cShablon, '<ИНН_ОРГ>', ''), '<НАИМ_ОРГ_ПОЛН>', ''), '<НАИМ_ОРГ>', '')
	
set @cShablon = ltrim(rtrim(@cShablon))	
if LEN(replace(@cShablon,'(','')) < LEN(replace(@cShablon,')',''))
	 set @cShablon = @cShablon + ')'

if left(@cShablon,1) = '(' and right(@cShablon,1) = ')'
	 set @cShablon = substring(@cShablon,2, len(@cShablon) - 2) 

RETURN @cShablon
END
GO


GRANT ALL ON dbo.BB_DEP_NAME_FOR_SHABLON TO PUBLIC
GO


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

GO

CREATE FUNCTION [dbo].SklonStr(@str VARCHAR(2000), @cPad VARCHAR(2000))
RETURNS VARCHAR(2000)
BEGIN
	DECLARE @result varchar(2000), @Stroka varchar(2000), @tmpstr varchar(2000), @LENSPACEs int, @WordBorder int
	DECLARE @pad INT
	
	IF ISNUMERIC(@cPad) = 1
		SET @pad = CASE WHEN CONVERT(BIGINT,@cPad) > 6 THEN 1 ELSE CONVERT(INT,@cPad) END
	ELSE
		SET @pad = 1
	
	IF (@str is NULL)	 
		SET @result = ''
	ELSE
	BEGIN

		SET @tmpstr = '' + SPACE(LEN(@Str) - LEN(LTRIM(@Str)))
        SET @LENSPACEs = LEN(@Str) - LEN(RTRIM(@Str))
        SET @Stroka = RTRIM(@Str)


	WHILE 1 > 0
	BEGIN
            SET @tmpstr = @tmpstr + ' '
            SET @WordBorder = CHARINDEX(' ',@Stroka,1)  --первое слово
            IF @WordBorder = 0  SET @WordBorder = LEN(@Stroka)
            IF LEN(@Stroka) > 0  SET @tmpstr = @tmpstr + LTRIM (RTRIM(dbo.SklonWord(left(@Stroka, @WordBorder), @Pad)))
            IF LEN(@Stroka) = @WordBorder   BREAK
            ELSE	
					
                SET @Stroka = SUBSTRING(@Stroka, (@WordBorder + 1),(LEN(LTRIM(@Stroka)) - @WordBorder)) --убрали первое слово            
    END	
        SET @result = @tmpstr
	END	
	RETURN @result
END


GO


GRANT EXECUTE ON dbo.[SklonStr] TO PUBLIC

GO


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


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

GO

CREATE VIEW dbo.DICTIONARY_DEPARTMENT

AS
SELECT 
    [LINK]    = D.LINK,
    [CODE]    = CONVERT(VARCHAR(10),D.CODE),
    [NAME]    = D.NAME,
    [FULL_NAME] = D.FULL_NAME,
    [F_NAME_CHAR] = CONVERT(VARCHAR(254),D.FULL_NAME),
    [INN]   = COALESCE (PERS.INN, D.INN),
    [INN_DOP] = D.INN_DOP,
    [INN_LONG]  = RTRIM(COALESCE (PERS.INN, D.INN)) + CASE WHEN D.INN_DOP = '' THEN '' ELSE '/' + D.INN_DOP END,
    [KPP]   = D.KPP,
    [OKPO]    = D.OKPO,
    [TYPE]    = D.TYPE,
    [TYPE_NAME] = (SELECT NAME FROM dbo.DICTIONARY_DEPARTMENT_TYPE WHERE NUMBER = D.TYPE),
    [ZB]    =   D.ZB,
    [REF_LINK_A]  = CASE
            WHEN D.TYPE = 3 THEN PERS.ADR_OFIC_LINK
            ELSE D.KLADR_LINK
          END,
    [VED_LINK]  = D.VED_LINK,
    [VED]   = CONVERT(VARCHAR(3), DIC1.CODE),
    [VED_NAME]  = CONVERT(VARCHAR(254), DIC1.NAME),
    [VED_BUDG]  = DIC1.LINK_BUDG,
    [HOUSE]   = CASE
            WHEN D.TYPE = 3 THEN PERS.HOUSE_OFIC
            ELSE D.HOUSE
          END,
    [CORP]   = CASE
            WHEN D.[TYPE] = 3 THEN PERS.CORP_OFIC
            ELSE D.CORP
          END,          
    [FLAT]    = CASE
            WHEN D.TYPE = 3 THEN PERS.FLAT_OFIC
            ELSE D.FLAT
          END,
    [MAIN_LINK] = D.MAIN_LINK,
    [REGCODE] = D.REGCODE,
    [OKATO]   = D.OKATO,
    [FIN_CODE]  = D.FIN_CODE,
    [TOFK_LINK] = D.TOFK_LINK,
    [TOFK]    = T.CODE,
    [TOFK_NAME] = T.NAME,
    [FO_LINK] = D.FO_LINK,
    [FO_CODE] = CONVERT(VARCHAR(10),FO.CODE),
    [FO_NAME] = FO.NAME,
    [UCHR_LINK] = D.UCHR_LINK,
    [UCHR_CODE] = CONVERT(VARCHAR(10),UCHR.CODE),
    [UCHR_NAME] = UCHR.NAME,
    [N_ACC_LINK] = D.N_ACC_LINK,
    [N_ACC_CODE] = NA.CODE,
    [N_ACC_NAME] = NA.ANAME,
--    [PFNUMBER]  = D.PFNUMBER,
    [PFNUMBER]  = COALESCE (PERS.INSUR_NUM, D.PFNUMBER),
    [BUDG]    = D.BUDG,
    [BRON]    = D.BRON,
    [PREFIX]  = D.PREFIX,
    [SONO_LINK] = D.LINK,
    [NALTYPE] = (SELECT MAX(FIN_IS_RBS) FROM WORKMODE),
    [NALOG]   = CONVERT(VARCHAR(10), D.CODE) ,
    [NALOG_NAME]  = CONVERT(VARCHAR(254), D.NAME),
    [OGRN]    = D.OGRN,
    [IMNS_LINK] = D.IMNS_LINK,
    [IMNS]    = CONVERT(VARCHAR(10),DD2.CODE),
    [IMNS_NAME] = DD2.NAME,
    [HIGH_LINK] = D.HIGH_LINK,
    [HIGH_CODE] = CONVERT(VARCHAR(10),(SELECT CODE FROM dbo.DEPARTMENTS WHERE LINK = D.HIGH_LINK)),
    [HIGH_NAME] = (SELECT NAME FROM dbo.DEPARTMENTS WHERE LINK = D.HIGH_LINK),
    [LIMIT]   = 0,
    [ORD_HEAD]  =   D.ORD_HEAD,
    [SBK_REGNUM]  = D.SBK_REGNUM,
    [SBK_DOCNUM]  =   D.SBK_DOCNUM,
    [SBK_DOCDATE]   =   D.SBK_DOCDATE,
    [SBK_LINK]  = D.SBK_LINK,
    [SBK_CODE]  =   CONVERT(VARCHAR(10), DD.CODE),
    [SBK_NAME]  = DD.NAME,
    [DEP_GROUPS]  =   dbo.xd_DepGroups(D.LINK),
    [PERS_LINK] = D.PERS_LINK,
    [PERS_FIO]  = CONVERT (VARCHAR (100), dbo.ku_GetPersFIO (PERS.LINK)),
    [IS_RBS]  =   D.IS_RBS,
    [DEP_TYPE2] =   D.DEP_TYPE2,
    [DEP_TYPE2_NAME]=   case D.DEP_TYPE2 when 1 then 'Малое предприятие'
               when 2 then 'Учреждение УИС'
               when 3 then 'Организация инвалидов'
               else 'Прочие' end,
	[OKVED]	= ISNULL (D.OKVED, ''),
	[EGRUL]	= ISNULL (D.EGRUL, ''),
	[IORUK_TASK] = ISNULL(D.IORUK_TASK,'00000'),
	D.FSS_REG_NUM, --Регистрационный номер (код) страхователя - регистрационный номер, указанный в Извещении (Уведомлении) страхователя, которое выдается при регистрации (учете) в территориальном органе Фонда.
	D.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	D.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	D.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	D.OKFS ,--- код Общероссийского классификатора форм собственности;
	D.CODE_UBP,
	D.TFOMS_REG_NUM, --Регистрационный номер в ТФОМС,
	D.TFOMS_KT, --Код тарифа для РСВ-1 ПФ
	D.EMail,
	DBT.BUH_TYPE AS BUH_TYPE,
	DBT.BT_NAME AS NM_BUHTYPE,
	D.FSS_KP_P1, FSS_KP_PC1 = P1.CODE,
	D.FSS_KP_P2, FSS_KP_PC2 = P2.CODE,
	D.FSS_KP_P3, FSS_KP_PC3 = P3.CODE,
	D.ISUSED,
	ISUSED_COM = CASE D.ISUSED WHEN 1 THEN CONVERT (VARCHAR (3), 'Да') ELSE CONVERT (VARCHAR (3), 'Нет') END

FROM dbo.DEPARTMENTS D
LEFT OUTER JOIN dbo.TREASURY T ON D.TOFK_LINK = T.LINK
LEFT OUTER JOIN DEPARTMENTS DD ON D.SBK_LINK = DD.LINK
LEFT OUTER JOIN DEPARTMENTS DD2 ON DD2.LINK = D.IMNS_LINK
LEFT OUTER JOIN KL_ADMIN_BS  DIC1 ON DIC1.LINK = D.VED_LINK 
LEFT OUTER JOIN PERSON PERS ON (PERS.LINK = D.PERS_LINK)
LEFT OUTER JOIN DEPARTMENTS FO ON D.FO_LINK = FO.LINK
LEFT OUTER JOIN DEPARTMENTS UCHR ON D.UCHR_LINK = UCHR.LINK
LEFT OUTER JOIN dbo.DICTIONARY_ACCOUNTS NA ON D.N_ACC_LINK = NA.LINK
LEFT JOIN dbo.DICTIONARY_BUH_TYPE DBT ON (DBT.BUH_TYPE = D.BUH_TYPE)
LEFT JOIN dbo.[SA_4FSS_KATEG_PLAT_P1] P1 ON P1.LINK = D.FSS_KP_P1
LEFT JOIN dbo.[SA_4FSS_KATEG_PLAT_P2] P2 ON P2.LINK = D.FSS_KP_P2
LEFT JOIN dbo.[SA_4FSS_KATEG_PLAT_P3] P3 ON P3.LINK = D.FSS_KP_P3

GO

GRANT SELECT ON dbo.[DICTIONARY_DEPARTMENT] 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_CREDIT_DATE_BEG]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[BB_CREDIT_DATE_BEG]
GO




CREATE	function dbo.BB_CREDIT_DATE_BEG (@iLink int)
returns datetime
as
begin
declare @dDateBeg datetime

-- Колличество платежей с датой завершения
set @dDateBeg = (select TOP 1 CP.[DATE]
from dbo.CREDIT_SUM CP
inner join CREDIT_PARAM_DICTION CPD on CPD.LINK = CP.PARAM_LINK
where CPD.CODE = 'PER_CREDIT' and LINK_UP = @iLink
order by CP.[DATE] desc)

if @dDateBeg is null 
	set @dDateBeg = (select TOP 1 G.[DATE]
	from dbo.G_PROV G
	inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK 
	inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK 
	inner join dbo.G_PROV_AP GAP on GAP.LINK_UP = G2.LINK and GAP.DB_KR = 0
	inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and (sa.cSinth = '210' and SA.cAnalit = '02' or sa.cSinth = '401' and SA.cAnalit = '30')
	inner join dbo.G_PROV_AP GAP1 on GAP1.LINK_UP = G2.LINK and GAP1.DB_KR = 1
	inner join dbo.BD_OSNOV O on O.LINK = /*isnull(GAP.AP1,*/GAP1.AP1 and O.DOC_LINK = @iLink
	order by G.[DATE] desc)


RETURN @dDateBeg
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.[BK_DOC_TAB_INVOICE_COR_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[BK_DOC_TAB_INVOICE_COR_FN]

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

RETURNS @RETURN_TAB TABLE 
	(LINK		INT,
	LINK_UP		INT,

	NEW_REC		TINYINT,
	ROW_LINK	INT,
	ORDERS		INT,
	
	INV_TYPE	VARCHAR (30),
	INV_LINK	INT,
	INV_CODE	VARCHAR (20),
	INV_NAME	VARCHAR (254),
	UM_LINK		INT,
	UM_CODE		VARCHAR (6),
	UM_NAME		VARCHAR (254),
	PRICE		NUMERIC (18, 2),
	QTY		NUMERIC (18, 4),
	SUMMA		NUMERIC (18, 2),
	STAVKA_NDS	NUMERIC (5, 2),
	SUMMA_NDS	NUMERIC (18, 2), 
	SUMMA_ALL	NUMERIC (18, 2), 
	AKCIZ		NUMERIC (18, 2),
	COUNTRY		VARCHAR (100),
	NUM_TD		VARCHAR (30),
	EKR_LINK	INT,
	EKR_CODE	VARCHAR (3),
	SFIN_CODE	VARCHAR (1),
	SFIN_NAME	VARCHAR (30),
	NO_NDS		TINYINT,

	TNDS_LINK1	INT,
	TNDS_CODE1	VARCHAR (2),

	PRICE_NEW	NUMERIC (18, 2),
	QTY_NEW		NUMERIC (18, 4),
	SUM_NEW		NUMERIC (18, 2),
	ST_NDS_NEW	NUMERIC (5, 2),
	NO_NDS_NEW	TINYINT,
	S_NDS_NEW	NUMERIC (18, 2), 
	S_ALL_NEW	NUMERIC (18, 2), 
	AKC_NEW		NUMERIC (18, 2),

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

	TNDS_LINK2	INT,
	TNDS_CODE2	VARCHAR (2)
	)
AS
BEGIN
	INSERT INTO @RETURN_TAB
	SELECT OTCI.LINK,
		OTCI.DOC_LINK,

		0,		
		OTCI.LINK_UP,
		OTR.ORDERS,
		
		OTMS.INV_TYPE,
		SMWT.LINK AS INV_LINK,
		SMWT.INV_CODE,
		SMWT.INV_NAME,
		SMWT.UM_LINK,
		UM.CODE AS UM_CODE,
		UM.[NAME] AS UM_NAME,
		CONVERT (NUMERIC (18, 2), PRICE) AS PRICE,
		CONVERT (NUMERIC (18, 4), QTY) AS QTY,
		CONVERT (NUMERIC (18, 2), SUMMA) AS SUMMA,
		CONVERT (NUMERIC (5, 2), STAVKA_NDS) AS STAVKA_NDS,
		CONVERT (NUMERIC (18, 2), SUMMA_NDS) AS SUMMA_NDS,
		CONVERT (NUMERIC (18, 2), SUMMA_ALL) AS SUMMA_ALL,
		OTMS.AKCIZ, OTMS.COUNTRY, OTMS.NUM_TD,
		EKR.LINK AS EKR_LINK,
		EKR.CODE AS EKR_CODE,
		FS.CODE AS SFIN_CODE,
		CONVERT (VARCHAR (30), FS.[SHORT_NAME]) AS SFIN_NAME,
		OTMS.NO_NDS,

		TO_NDS1.LINK,
		TO_NDS1.CODE,
		
		CONVERT (NUMERIC (18, 2), OTCI.PRICE_AFTER),
		CONVERT (NUMERIC (18, 4), OTCI.QTY_AFTER),
		CONVERT (NUMERIC (18, 2), OTCI.SUM_AFTER),
		OTCI.STAVKA_NDS_AFTER,
		OTCI.NO_NDS_AFTER,
		CONVERT (NUMERIC (18, 2), OTCI.SUM_NDS_AFTER),
		CONVERT (NUMERIC (18, 2), OTCI.SUM_ALL_AFTER),
		OTCI.AKCIZ_AFTER,
		
		FS.LINK,
		FS.CODE,
		CONVERT (VARCHAR (20), FS.SHORT_NAME),

		TO_NDS2.LINK,
		TO_NDS2.CODE

	FROM dbo.OUT_TABLE_INVOICE_COR OTCI
	INNER JOIN dbo.OUT_TABLE_ROW OTR ON (OTR.LINK = OTCI.LINK_UP)
	INNER JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = OTR.LINK)
	LEFT JOIN dbo.TYPE_OPER_NDS TO_NDS1 ON (TO_NDS1.LINK = OTMS.TYPE_NDS)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE SMWT ON (SMWT.INV_TYPE = OTMS.INV_TYPE
		AND (OTMS.INV_TYPE IN ('BV_NOMENCLATURE', 'DICTIONARY_SERV')
				 AND SMWT.LINK = OTMS.NOMEN
			OR OTMS.INV_TYPE = 'INVENTORY_CARD'
			 	AND SMWT.LINK = OTMS.INV)
			OR OTMS.INV_TYPE = 'DICTIONARY_TMC'
			 	AND SMWT.LINK = OTMS.TMC)
	LEFT JOIN dbo.DICTIONARY_DIGIT UM ON (UM.LINK = SMWT.UM_LINK)
	LEFT JOIN dbo.KOSGU EKR ON (EKR.LINK = OTMS.EKR)	
	LEFT JOIN dbo.FIN_SOURCE FS ON (FS.CODE = OTMS.FIN_SOURCE)
	LEFT JOIN dbo.TYPE_OPER_NDS TO_NDS2 ON (TO_NDS2.LINK = OTCI.TYPE_NDS_AFTER)
	WHERE @intLINK_DOC IS NULL
		OR OTCI.DOC_LINK = @intLINK_DOC


	RETURN 
END






GO


GRANT SELECT ON dbo.[BK_DOC_TAB_INVOICE_COR_FN] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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






/*
	© Кейсистемс (Keysystems), 2006
	Доступ к отчету с учетом иерахии дерева
	Новое условие: в листе содержатся только ОТЧЕТЫ, в остальном только СВОДЫ
*/
CREATE   FUNCTION dbo.RO_SVOD_STATUS_ACCESS_WITH_ATR (@LinkTypeSvod int, @LinkOrg int, @IsSvod tinyint, @link_form int, @pType tinyint, @pNom tinyint, @BeginDate datetime,@cAtr varchar(250))
RETURNS TINYINT
AS
BEGIN

declare @t_tree_with_access table (link int, parent int, link_budg int, link_org int, childrens tinyint)

insert @t_tree_with_access(link, parent, link_budg, link_org, childrens)
	select	link,
		[parent] = link_self,
		[link_budg] = link_report_budg,
		[link_org] = link_report_org,
		childrens -- 0 - есть дети, 1 - нет
	from dbo.RO_SVOD_TREE T 
		inner join dbo.user_form_access ufa 
    	on isnull(T.link_report_org,0) = isnull(ufa.dep_link,0)
    	and isnull(ufa.budg_link,0) = isnull(T.link_report_budg,0)
		 and ufa.SID = suser_sid()
   WHERE LINK_HISTORY = dbo.[RO_SVOD_TREE_Link_History](@BeginDate)


delete @t_tree_with_access
from @t_tree_with_access T1
where parent is NULL or exists(select * from @t_tree_with_access T2 where T1.parent = T2.link) -- у которого есть отец


declare @t_Links table (linkTree int)
insert @t_Links
select Link
from dbo.RO_SVOD_TREE L 
where /*L.childrens = 1 - @IsSvod and*/ ((L.Link_org = @LinkOrg and L.link_report_budg = @LinkTypeSvod) or (L.link_budg = @LinkTypeSvod and L.link_report_org = @LinkOrg))

IF ISNULL((SELECT Val_Int FROM dbo.[REPORT_OPTIONS] ro WHERE ro.[Razdel] = 'COMMON' AND CODE = 'ACCESS_STATUS'),0) = 0
BEGIN 
   if exists(select * from report_saved_forms RSF inner join @t_tree_with_access TA on RSF.[Link_Type_Svod] = dbo.[RO_SVOD_BUDG](TA.Link) and RSF.[Link_Organization] = dbo.[RO_SVOD_ORG](TA.Link) /*and childrens + IsSvod = 1*/
		   inner join @t_Links L on dbo.RO_SVOD_TREE_POTOMOK(L.LinkTree, TA.Link) = 1 
		   where del = 0 and IsRO in (select Status from dbo.Report_Status where access <> 255) and RSF.link_form = @link_form and RSF.Period_Type = @pType and RSF.Period_Number = @pNom and YEAR(RSF.Begin_Date) = YEAR(@BeginDate)
	   --	and dbo.rn_get_atr_val(link_saved_form,0,1)=@catr)
		   and isnull(atr_code,'')=@catr)
   begin 
	   return 1
   end
   else BEGIN
	   return 255
   END
END 
ELSE BEGIN
   if exists(select * from report_saved_forms RSF inner join @t_tree_with_access TA on RSF.[Link_Type_Svod] = dbo.[RO_SVOD_BUDG](TA.Link) and RSF.[Link_Organization] = dbo.[RO_SVOD_ORG](TA.Link) /*and childrens + IsSvod = 1*/
		   inner join @t_Links L on L.LinkTree = TA.Link  
		   where del = 0 and IsRO in (select Status from dbo.Report_Status where access <> 255) and RSF.link_form = @link_form and RSF.Period_Type = @pType and RSF.Period_Number = @pNom and YEAR(RSF.Begin_Date) = YEAR(@BeginDate)
	   --	and dbo.rn_get_atr_val(link_saved_form,0,1)=@catr)
		   and isnull(atr_code,'')=@catr)
   begin 
	   return 1
   end
   else BEGIN
	   return 255
   END
END       


RETURN 0
END

GO
GRANT ALL ON dbo.RO_SVOD_STATUS_ACCESS_WITH_ATR TO PUBLIC
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

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

FROM KL_KBK K 
left join KL_ADMIN_BS A ON K.Link_Adm = A.link 
left join dbo.DEPARTMENT_KBK DKBK on DKBK.KBK_LINK = K.LINK and DEP_LINK = isnull(dbo.BK_getDepZB(),dbo.GetOwnDepLink())



GO


GRANT SELECT ON dbo.[BI_DICTION_KBK] TO PUBLIC

GO


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


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

GO
CREATE VIEW dbo.DOCUMENTS_INVOICE_RECEIVED_OLD
AS
 	SELECT 	
		G.LINK,
		G.NUMBER,
		[SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		[FLAG_JC] = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
	[BOOK_PUR] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BOOK_PURCHASE_RECEIVED'))),

	[DEP_LINK]	=	G.DEP, -- для X_SELECT_DOCUMENT_LIST_ZB
	[BUY_LINK]	=	G.DEP,
	[BUY_CODE]	=	CONVERT(VARCHAR(10),(SELECT CODE FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),
	[BUY_NAME]	=	CONVERT(varchar(100),(SELECT NAME FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),

	[CONS2_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[CONS2_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK_RECEIVED')),
	[CONS2_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNEE_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[CONS1_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK_RECEIVED')),
	[PROD_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_RECEIVED_PRODUCER_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[PROD_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_RECEIVED_PRODUCER_LINK')),
	[PROD_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_RECEIVED_PRODUCER_LINK') AND D.LINK = GPD.DEPARTMENT)),
	[OSNOV] = GPO.OSNOV, 
	[DOG_LINK]= OSN.DOC_LINK,
	[DOG_CODE]= OSN.NUMBER,
	[NALOG_DOC] = CONVERT(NUMERIC(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'INVOICE_RECEIVED_NALOG_DOC_1'))),
	[NUM_BASE] = CONVERT(VARCHAR(6), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'NUMBER_BASE_DOCUMENT_RECEIVED'))),
	[DATE_BASE] = CONVERT(DATETIME, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DATE_BASE_DOCUMENT_RECEIVED')),104),
	[CONS1_SELF] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELF_CONS1_RECEIVED'))),
	[CONS2_SELF] = CONVERT(BIT, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELF_CONSIGNEE_RECEIVED'))),
	[SEL_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELLER_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[CONS1_CODE]=	CONVERT(varchar(10),	(SELECT CODE FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[SEL_LINK]=		(SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELLER_LINK_RECEIVED')),
	[SEL_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'SELLER_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[CONS1_NAME]=	CONVERT(varchar(50),	(SELECT NAME FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'CONSIGNOR_LINK_RECEIVED') AND D.LINK = GPD.DEPARTMENT)),
	[PAYS_LINK]  =		(SELECT GPR.DOC_REF_FOREIGN FROM dbo.G_PROV_REF GPR WHERE GPR.DOC_REF_PRIMARY = G.LINK AND GPR.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'PAYS_LINK_RECEIVED')),
	[KBK_LINK]= (SELECT GPK.KBK FROM dbo.G_PROV_KBK GPK WHERE GPK.DOC_LINK = G.LINK AND GPK.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_INVOICE_RECEIVED_LN_KBK')),
	[KBK_CODE]= (SELECT D.CODE FROM dbo.KL_KBK D WITH (NOLOCK)
			INNER JOIN dbo.G_PROV_KBK GPK ON (GPK.KBK = D.LINK) WHERE GPK.DOC_LINK = G.LINK AND GPK.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_INVOICE_RECEIVED_LN_KBK')),
	[KBK_NAME]= (SELECT D.[NAME] FROM dbo.KL_KBK D WITH (NOLOCK)
			INNER JOIN dbo.G_PROV_KBK GPK ON (GPK.KBK = D.LINK) WHERE GPK.DOC_LINK = G.LINK AND GPK.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_INVOICE_RECEIVED_LN_KBK')),
	[TAX_RATE] = CONVERT(NUMERIC(4,2), (SELECT GPV_TAX.VALUE FROM dbo.G_PROV_VALUE as GPV_TAX WITH (NOLOCK)  WHERE GPV_TAX.DOC_LINK = G.LINK AND GPV_TAX.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_INVOICE_RECEIVED_TAX')))
	FROM dbo.G_PROV as G WITH (NOLOCK)
	LEFT JOIN dbo.G_PROV_OSNOV GPO ON (GPO.DOC_LINK = G.LINK
		AND GPO.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'INVOICE_RECEIVED_DOG_LINK'))
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = GPO.OSNOV)
	WHERE G.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_RECEIVED')


GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_RECEIVED_OLD] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.[sysobjects]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_SELECT_SVOD_FORMS]') AND 
                 [XTYPE] IN (N'FN', N'IF', N'TF'))
BEGIN
   DROP FUNCTION dbo.[RA_SELECT_SVOD_FORMS]
END
GO

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

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

*******************************************************************************/
CREATE FUNCTION dbo.[RA_SELECT_SVOD_FORMS] (
   @iLINK_SAVED_FORM INT
)
RETURNS @tabReturn TABLE (LINK_SAVED_FORM INT, Link_Organization int, Link_Type_Svod int, Link_Tree int, Link_Tree_Self int, childrens tinyint, FilterField tinyint)
AS
BEGIN

   DECLARE	@liYear		         INT,
         	@liLINK_FORM		   INT,
         	@ltPERIOD_TYPE		   TINYINT,
         	@ltPERIOD_NUMBER		TINYINT,
         	@lvcFormCode		   VARCHAR(20),
         	@liLINK_ORGANIZATION	INT,
         	@liLINK_TYPE_SVOD		INT,
         	@liLinkTreeSvod	   INT,
	        @atribut varchar(250),
			@date datetime,
			@link_history int

   SELECT   @liLINK_FORM         = [RSF].[LINK_FORM],
    	    @lvcFormCode         = [RF].[CODE],
         	@liYear              = YEAR([RSF].[BEGIN_DATE]), 
         	@ltPERIOD_TYPE       = [RSF].[PERIOD_TYPE], 
         	@ltPERIOD_NUMBER     = [RSF].[PERIOD_NUMBER],
         	@liLINK_TYPE_SVOD    = [RSF].[LINK_TYPE_SVOD],
         	@liLINK_ORGANIZATION = [RSF].[LINK_ORGANIZATION],
			@atribut =atr_code,
			@date = begin_date
   FROM dbo.[REPORT_SAVED_FORMS] [RSF] 
   JOIN dbo.[REPORT_FORMS]       [RF] ON [RF].[LINK_FORM] = [RSF].[LINK_FORM]
   WHERE [RSF].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM

	set @link_history = dbo.RO_SVOD_TREE_Link_History(@date)
   
   SELECT @liLinkTreeSvod = MIN([LINK]) 
   FROM dbo.[RO_SVOD_TREE] 
   WHERE isnull([LINK_REPORT_BUDG],0) = isnull(@liLINK_TYPE_SVOD,0)   AND 
         [LINK_REPORT_ORG] = @liLINK_ORGANIZATION and link_history = @link_history

   IF @lvcFormCode='425G'
	   select @atribut=dbo.rn_get_atr_svod_val(@iLINK_SAVED_FORM,0,1)
   --атрибуты для сводных форм
   IF @lvcFormCode not in ('(72н)0503125','(72н)0503125М','(72н)425M','(72н)425','(72н)0503117M','OPKB','OPKB_2008','0503117G','0503125G','425G','OPKB_MINREGION','425M','0503125M','0503117M','INVZ_2009','63', 'RRO','OPKB_2009_MR','Monit_napr_dohod(3)','Inf_opl_truda(1)','Inf_isp_dotaciy(2)', 'T0503324MF', 'T0503324MO', 'T0503324MI')
   begin 
      if @atribut not like  '%REPORTS_ATR_VID=%' and  @atribut not like  '%REPORTS_ATR_RRO_TYPE=%' and @atribut not like '%REPORTS_ATR_TYPE_ORG=%'
	      set @atribut='' 

   end


    declare @tree table(Link int, Link_Self int, Link_Report_Org int, Link_Report_Budg int, Childrens tinyint, FilterField tinyint, [Level] varchar(30), orders int)

   INSERT @tree(Link, Link_Self, childrens, Link_Report_Org, Link_Report_Budg, FilterField, [Level], orders)
	select  T.Link, T.Link_Self, T.childrens, Link_Report_Org, Link_Report_Budg, case when @liLinkTreeSvod = T.Link_Self then 1 else 0 end as FilterField,  dbo.RO_SVOD_TREE_POTOMOK_Level (T.Link, @liLinkTreeSvod), orders
	from RO_SVOD_TREE T 

	delete @tree where [Level] = ''

   DECLARE @c700 VARCHAR (100)
   SET @c700 = ''
   IF @atribut LIKE '%Сводный%' 
    BEGIN
        IF NOT EXISTS(
	        select *
	        from @tree T join report_saved_forms RSF on T.Link_report_org = RSF.link_Organization and isnull(T.Link_report_budg,0) = isnull(RSF.Link_Type_Svod,0)
		    join report_forms RF on RSF.Link_Form = RF.Link_Form
	        where [RF].[CODE] = @lvcFormCode                AND 
            [RSF].DEL = 0                             AND
            YEAR([RSF].[BEGIN_DATE]) = @liYear       AND 
            [RSF].[PERIOD_TYPE] = @ltPERIOD_TYPE     AND 
            [RSF].[PERIOD_NUMBER] = @ltPERIOD_NUMBER AND 
            [RSF].[IsChangeAnalit] = 0		           AND 
            [RSF].[VERSION] =    (SELECT MAX([X].[VERSION]) 
                                FROM dbo.[REPORT_SAVED_FORMS]  [X]
                           	 WHERE [X].[DEL]              = 0   AND 
                                     [X].[LINK_FORM]         = [RSF].[LINK_FORM] AND 
                                     [X].[LINK_ORGANIZATION] = [RSF].[LINK_ORGANIZATION] AND 
                                     isnull([X].[LINK_TYPE_SVOD],0)    = isnull([RSF].[LINK_TYPE_SVOD],0) AND 
                                     YEAR([X].[BEGIN_DATE])  = @liYear    				  AND 
                                     [X].[PERIOD_TYPE]       = @ltPERIOD_TYPE  			  AND 
                                     [X].[PERIOD_NUMBER]     = @ltPERIOD_NUMBER			
									 and isnull(X.atr_code,'')=isnull(RSF.atr_code,''))
		    AND (case when @lvcFormCode='425G' then dbo.rn_get_atr_svod_val(RSF.link_saved_form,0,1) else  
				isnull(RSF.atr_code,'') end) =  (case when isnull(@atribut,'')<>'' then @ATRIBUT else isnull(RSF.atr_code,'') END))
        BEGIN
            SET @c700 = '700-ые формы'       	
        END
    	
    END
	

   INSERT @tabReturn([LINK_SAVED_FORM], Link_Organization, Link_Type_Svod, Link_Tree, Link_Tree_Self, Childrens, FilterField)
	select [RSF].[LINK_SAVED_FORM], RSF.Link_Organization, RSF.Link_Type_Svod, T.Link, T.Link_Self, T.childrens, case when @liLinkTreeSvod = T.Link_Self then 1 else 0 end as FilterField
	from @tree T join report_saved_forms RSF on T.Link_report_org = RSF.link_Organization and isnull(T.Link_report_budg,0) = isnull(RSF.Link_Type_Svod,0)
		join report_forms RF on RSF.Link_Form = RF.Link_Form
	where [RF].[CODE] = @lvcFormCode                AND 
         [RSF].DEL = 0                             AND
         YEAR([RSF].[BEGIN_DATE]) = @liYear       AND 
         [RSF].[PERIOD_TYPE] = @ltPERIOD_TYPE     AND 
         [RSF].[PERIOD_NUMBER] = @ltPERIOD_NUMBER AND 
         [RSF].[IsChangeAnalit] = 0		           AND 
         [RSF].[VERSION] =    (SELECT MAX([X].[VERSION]) 
                               FROM dbo.[REPORT_SAVED_FORMS]  [X]
                           	 WHERE [X].[DEL]              = 0   AND 
                                     [X].[LINK_FORM]         = [RSF].[LINK_FORM] AND 
                                     [X].[LINK_ORGANIZATION] = [RSF].[LINK_ORGANIZATION] AND 
                                     isnull([X].[LINK_TYPE_SVOD],0)    = isnull([RSF].[LINK_TYPE_SVOD],0) AND 
                                     YEAR([X].[BEGIN_DATE])  = @liYear    				  AND 
                                     [X].[PERIOD_TYPE]       = @ltPERIOD_TYPE  			  AND 
                                     [X].[PERIOD_NUMBER]     = @ltPERIOD_NUMBER			
									 and isnull(X.atr_code,'')=isnull(RSF.atr_code,''))
		AND (case when @lvcFormCode='425G' then dbo.rn_get_atr_svod_val(RSF.link_saved_form,0,1) 
		          when @c700='700-ые формы' then REPLACE(REPLACE(REPLACE(RSF.atr_code,'Бюджетный','Сводный'),'Казенный','Сводный'),'Автономный','Сводный')
		        else  
				isnull(RSF.atr_code,'') end) =  (case when isnull(@atribut,'')<>'' then @ATRIBUT else isnull(RSF.atr_code,'') end)
	order by [level] 

   RETURN 
END

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

/*

select * from dbo.[RA_SELECT_SVOD_FORMS](5114)


select * from report_saved_forms

select * from PLAN_ACCOUNTS

select 

create table #b (i int, k int)
select * from #a a join #b b on a.i=b.i



*/





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

GO



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

CREATE   FUNCTION dbo.ARestPackedOborotByPeriod
	(@varKSDateBegin datetime,
	@varKSDateEnd datetime,
	@varKSAccount int = null)

RETURNS @RET_TABLE  TABLE  ([DATE_PROV] [DATETIME],
		[ACCOUNT] [INT],
		[D_SUMMA] [NUMERIC] (28,2),
		[K_SUMMA] [NUMERIC] (28,2),
		[R_SUMMA] [NUMERIC] (28,2),
		[D_QUANTITY] [NUMERIC] (28,4),
		[K_QUANTITY] [NUMERIC] (28,4),
		[KBK]	[INT],
		[EKR]	[INT],
		[DEP] [INT],
		[SUB]	[INT],
		[EMP]	[INT],
		[NOMEN]	[INT],
		[INV]	[INT],
		[KAU]	[INT],
		[DEP_ACC] [INT],
		[TMC]	[INT],
		[INDATE]	[DATETIME],
		[AP1]	[INT],
		[AP2]	[INT],
		[AP3]	[INT],
		[SGU]	[INT],
		[DEP_LINK] [INT],
		[PRICE]	[NUMERIC] (28,6),
		[PRICE_TYPE] [TINYINT],
		[B_YEAR0] [TINYINT])
AS
BEGIN
	INSERT INTO @RET_TABLE
	SELECT G.DATE_PROV, AP.ACCOUNT,
		[D_SUMMA] = CASE 
				WHEN SA.s_active = 0 THEN 0
				WHEN AP.DB_KR = 0
				THEN dbo.ARestCalcDtSaldo(1, SA.s_passive, G2.SUMMA, default)
				ELSE dbo.ARestCalcDtSaldo(1, SA.s_passive, default, G2.SUMMA)
				END,
		[K_SUMMA] = CASE
				WHEN SA.s_passive = 0 THEN 0
				WHEN AP.DB_KR = 0
				THEN dbo.ARestCalcKtSaldo(SA.s_active, 1, G2.SUMMA, default)
				ELSE dbo.ARestCalcKtSaldo(SA.s_active, 1, default, G2.SUMMA)
				END,
		[R_SUMMA] = 0,
		[D_QUANTITY] = CASE
				WHEN SA.KSU = 0 OR SA.s_active = 0 THEN 0
				WHEN AP.DB_KR = 0 THEN G2.QUANTITY ELSE -G2.QUANTITY END,
		[K_QUANTITY] = CASE
				WHEN SA.KSU = 0 OR SA.s_passive = 0 THEN 0
				WHEN AP.DB_KR = 1 THEN G2.QUANTITY ELSE -G2.QUANTITY END,
		
		KBK	= CASE WHEN SA.ap_KBK = 1 AND SA.OB_KBK = 0 THEN AP.KBK ELSE NULL END,
		EKR	= CASE WHEN SA.ap_EKR = 1 AND SA.OB_EKR = 0 THEN AP.EKR ELSE NULL END,
		DEP	= CASE WHEN SA.ap_DEP = 1 AND SA.OB_DEP = 0 THEN AP.DEP ELSE NULL END,
		SUB	= CASE WHEN SA.ap_SUB = 1 AND SA.OB_SUB = 0 THEN SUB.LINK_UP ELSE NULL END,
		EMP	= CASE WHEN SA.ap_EMP = 1 AND SA.OB_EMP = 0 THEN AP.EMP ELSE NULL END,
		NOMEN	= CASE WHEN SA.ap_NOMEN = 1 AND SA.OB_NOMEN = 0 THEN AP.NOMEN  ELSE NULL END,
		INV	= CASE WHEN SA.ap_INV = 1 AND SA.OB_INV = 0 THEN AP.INV ELSE NULL END,
		KAU	= CASE WHEN SA.ap_KAU = 1 AND SA.OB_KAU = 0 THEN AP.KAU ELSE NULL END,
		DEP_ACC = CASE WHEN SA.ap_DEP_ACC = 1 AND SA.OB_DEP_ACC = 0 THEN AP.DEP_ACC ELSE NULL END,
		TMC	= CASE WHEN SA.ap_TMC = 1 AND SA.OB_TMC = 0 THEN AP.TMC ELSE NULL END,
		INDATE	= CASE WHEN SA.ap_INDATE = 1 AND SA.P_DATE = 0 THEN AP.INDATE ELSE NULL END,
		AP1	= CASE WHEN SA.ap_AP1 = 1 AND SA.OB_AP1 = 0 THEN AP.AP1 ELSE NULL END,
		AP2	= CASE WHEN SA.ap_AP2 = 1 AND SA.OB_AP2 = 0 THEN AP.AP2 ELSE NULL END,
		AP3	= CASE WHEN SA.ap_AP3 = 1 AND SA.OB_AP3 = 0 THEN AP.AP3 ELSE NULL END,
		SGU	= AP.SGU,
		[DEP_LINK] = G.DEP,
		[PRICE]	= CASE
				WHEN N.PRICE_TYPE = 1 AND G2.QUANTITY <> 0 THEN
					CONVERT (NUMERIC (28,6), G2.SUMMA / G2.QUANTITY)
				ELSE CONVERT (NUMERIC (28,6), 0)
			END,
		[PRICE_TYPE] = ISNULL (N.PRICE_TYPE, 0),
		SA.B_YEAR0
	FROM dbo.G_PROV G
	INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
		AND G.DATE_PROV BETWEEN @varKSDateBegin AND @varKSDateEnd
	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
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = AP.ACCOUNT
	LEFT JOIN dbo.BK_GetNomenPriceFACT () N  ON (N.LINK = AP.NOMEN
		AND SA.ap_NOMEN = 1 AND SA.ksu = 1)
	LEFT JOIN dbo.SUBDIV SUB ON SUB.LINK = AP.SUB
	WHERE SA.LINK IN (select LINK FROM dbo.AccountsSubtreeByRoot(@varKSAccount)) AND @varKSAccount IS NOT NULL
		OR SA.LINK IN (select LINK FROM dbo.AccountsTableWithNoChild()) AND @varKSAccount IS NULL


	UPDATE T1
	SET PRICE = SC.PRICE
	FROM @RET_TABLE T1 
	INNER JOIN @RET_TABLE SC ON
		(
			(SC.D_QUANTITY > 0 AND SC.D_SUMMA > 0)
				AND ISNULL (SC.ACCOUNT, 0) = ISNULL (T1.ACCOUNT, 0)
				AND ISNULL (SC.KBK, 0) = ISNULL (T1.KBK, 0)
				AND ISNULL (SC.EKR, 0) = ISNULL (T1.EKR, 0)
				AND ISNULL (SC.DEP, 0) = ISNULL (T1.DEP, 0)
				AND ISNULL (SC.SUB, 0) = ISNULL (T1.SUB, 0)
				AND ISNULL (SC.EMP, 0) = ISNULL (T1.EMP, 0)
				AND ISNULL (SC.DEP_LINK, 0) = ISNULL (T1.DEP_LINK, 0)
				AND ISNULL (SC.NOMEN, 0) = ISNULL (T1.NOMEN, 0)
				AND ISNULL (SC.INV, 0) = ISNULL (T1.INV, 0)
				AND ISNULL (SC.KAU, 0) = ISNULL (T1.KAU, 0)
				AND ISNULL (SC.DEP_ACC, 0) = ISNULL (T1.DEP_ACC, 0)
				AND ISNULL (SC.TMC, 0) = ISNULL (T1.TMC, 0)
				AND ISNULL (SC.INDATE, '17530101') = ISNULL (T1.INDATE, '17530101')
				AND ISNULL (SC.AP1, 0) = ISNULL (T1.AP1, 0)
				AND ISNULL (SC.AP2, 0) = ISNULL (T1.AP2, 0)
				AND ISNULL (SC.AP3, 0) = ISNULL (T1.AP3, 0)
--				AND FLOOR (SC.PRICE * 10000) = FLOOR (T1.PRICE * 10000)
				AND CONVERT (NUMERIC (28,2), SC.PRICE) = CONVERT (NUMERIC (28,2), T1.PRICE)
		)
	WHERE T1.PRICE_TYPE = 1
		AND (T1.D_QUANTITY < 0 OR T1.D_SUMMA < 0)
		AND SC.PRICE IS NOT NULL
		AND SC.DATE_PROV < = T1.DATE_PROV

	RETURN
END

GO


GRANT SELECT ON dbo.[ARestPackedOborotByPeriod] 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_SignWhat]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RO_SignWhat]
GO




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

-- подпись своей организацией или вышестоящей

CREATE  FUNCTION dbo.RO_SignWhat(@varKSiLSF int)
RETURNS tinyint
AS
BEGIN
  DECLARE  @LinkOrg int, @LinkBudg int

   -- есть подпись пользователя у которого нет прав на организации, значит он подписала в Своде-КС
  if not exists(select top 1 * from dbo.user_form_access U where U.sid = suser_sid()) 
      return 2

   -- есть подпись пользователя у которого есть права на самую верхнюю организацию
  if exists(select top 1 * from dbo.user_form_access U where U.sid = suser_sid() and dep_link = dbo.getowndeplink() and exists(select top 1 * from dbo.report_svod_tree T where T.link_report_org = U.dep_link and T.link_report_budg = U.budg_link))  
      return 2

  select @LinkOrg = Link_Organization, @LinkBudg = isnull(Link_Type_Svod, 0) from dbo.report_saved_forms where link_saved_form =  @varKSiLSF

  -- если есть подпись пользователя, у которого есть доступ на вышестоящую организацию
  if exists(select top 1 * from dbo.user_form_access U where U.sid = suser_sid() and
            dbo.RO_SVOD_TREE_POTOMOK_Org_Budg (@LinkOrg, @LinkBudg, dep_link, budg_link) = 1 and (dep_link <> @LinkOrg OR budg_link <> @LinkBudg))
      return 2
  

  -- подпись самой организации
  RETURN 1
END






GO
GRANT ALL ON dbo.[RO_SignWhat] 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].[I_REPORT_USER_SAVED_FORMS_WEB_NASTR_FAST]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[I_REPORT_USER_SAVED_FORMS_WEB_NASTR_FAST]
GO




/*
© Кейсистемс (Keysystems), 2005
Вывод сохраненных форм отчетности для тонкого клиента
аналогично I_REPORT_USER_SAVED_FORMS
добавлена проверка прав пользователя на доступ к отчету
Соколов С.В.
исправлено: 20061023 - отображать все версии отчетов по настройке
*/



CREATE              VIEW dbo.I_REPORT_USER_SAVED_FORMS_WEB_NASTR_FAST
AS
select  
  link_saved_form as link,
  (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) as period,
  RF.name,
  RF.code,
  RSF.link_saved_form,
  RSF.Link_form,
  RSF.Version,
  RSF.begin_date,
  RSF.period_type,
  RSF.period_number,
  RSF.link_organization,
  RSF.IsRO,
  RSF.IsRightKS,
  convert(VARCHAR(100),dbo.GetDepName(RSF.Link_Organization, RSF.begin_date)) as dep_name,
  convert(CHAR(10),DD.CODE) as dep_code,
  convert(VARCHAR(10), DD.BUDG) as dep_budg,
  RSF.isUpload,
  RSF.isSvod,
  RSF.Link_Type_Svod,
  [Type_Svod] = isnull((select Name from KL_BUDG_TYPE D where D.link = RSF.Link_Type_Svod), ''),
  RSF.isChangeAnalit,
  CASE WHEN RF.CODE = '(86н)001' THEN  
     (SELECT TOP 1 'Загружен на сайт' FROM  report_kbk F WHERE  F.code_form = 'spr_info_send_razdel_1' AND F.CODE = DD.CODE AND F.CODE_STR='Отчет успешно загружен')     
  ELSE '' END AS Note,  
  dbo.GET_WEB_OBJ_REPORT_ACCESS('REPORT_SAVED_FORMS', link_saved_form) as access,
  RF.IsUsedRazdel ,
  RF.IsUsedCelSt ,
  RF.IsUsedRashod ,
  0 as LinkRazdel,
  0 as LinkCelSt,
  0 as LinkRashod,
  RF.Print_Object_Method, 
  RF.Query_Add_Module, 
  RF.Query_Before, 
  RF.Query_RepMaker, 
  RF.Query_Report, 
  RF.Query_Report_Path,
  RF.IsRemoteAccess,
  isCalcItog = 1,
 [IsRO_MASK] = 0,--(select sum(case status when 0 then 0 when 1 then 256 when 2 then 512 when 5 then 8192 else 1024 end) FROM dbo.REPORT_STATUS WHERE access_change = 1 or IS_MEMBER('db_owner')=1 or IS_MEMBER('Главный бухгалтер')=1 or isnull(IS_MEMBER('Начальник отдела кадров'),0)=1 or (IS_MEMBER('Свод-КС')=1 and dbo.RO_SVOD_STATUS_ACCESS_MASK_ISRO(RSF.Link_Type_Svod, RSF.Link_Organization) = 255) or Status = (select IsRO from report_saved_forms where Link_Saved_Form = RSF.Link_Saved_Form)),
  RSF.CountSave,  
  DateLastEdit = SJ.date,
  WhoLastEdit = CONVERT (VARCHAR(254), (Isnull (ltrim(rtrim(SJ.FIO)), '') + ' ('+ltrim(rtrim(SJ.Login))+') - ' + ltrim(rtrim(SJ.HOSTNAME)))),
--  obj_code = case when CHARINDEX('#', ISNULL(RF.Object, '')) = 0 then 'REPORT_FORMS_TABLES' when CHARINDEX('REPORT_TEXT',ISNULL(RF.Object, '')) > 0 then 'FORM14_EDIT' else LEFT(RF.Object, CHARINDEX('#', RF.Object) - 1) end,
  obj_code = case when CHARINDEX('#', ISNULL(RF.Object, '')) = 0 then 'REPORT_FORMS_TABLES' else LEFT(RF.Object, case when CHARINDEX(',', RF.Object) = 0 then CHARINDEX('#', RF.Object) - 1 else CHARINDEX(',', RF.Object) - 1 end) end,
  left(RF.atributs,250) atributs,--left(dbo.rn_get_atr_val(RSF.link_saved_form,0,0),250) atr_val
  RSF.atr as atr_val,
	IsSign = isnull((select max(type_who) from dbo.report_sign S  where S.lsf = RSF.link_saved_form), 0) 
from report_saved_forms RSF (nolock) inner join i_Report_Forms RF on RSF.Link_Form = RF.Link_Form  left outer join 
   departments DD on DD.link = RSF.link_organization
  --inner join dbo.RO_SVOD_ORG_ACCESS() ufa on  ufa.link_org = RSF.link_organization
-- left join  sys_jurnal SJ on SJ.link = RSF.link_jurnal
   left outer join  dbo.RO_SF_OWNER SJ on SJ.Link = RSF.link_saved_form


where      'OUTPUTS' = (select code_task from user_task_info)
  AND begin_date >= (select begindate from user_info) 
  AND ((select top 1 ALL_VERS_IN_THIN_CLI from dbo.I_REPORT_OPTIONS_COMMON) = 1 or RSF.Version = (select max(version) from report_saved_forms RSF2 
      where RSF2.link_form = RSF.Link_Form
      AND rsf2.del = 0
      and RSF2.Begin_Date = RSF.Begin_Date
      and RSF2.Period_Type = RSF.Period_Type
      and RSF2.Period_Number = RSF.Period_Number
      and RSF2.Link_Organization = RSF.Link_Organization
      and RSF2.IsUpload = RSF.IsUpload
      and RSF2.IsSvod = RSF.IsSvod
      and RSF2.IsChangeAnalit = RSF.IsChangeAnalit
      and isnull(RSF2.Link_Type_Svod, -1) = isnull(RSF.Link_Type_Svod, -1)
      and isnull(RSF.atr,'')=isnull(RSF2.atr,'')))
   and (RSF.[Owner_SID] = SUSER_SID() OR ISNULL((SELECT VALUE
						FROM S_OPTIONS
						WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'REPORT_VIEW_ONLY_OWN')
								AND  SID = suser_sid()), 0) = 0)
     AND rsf.del = 0
   
--left(dbo.rn_get_atr_val(RSF.link_saved_form,0,0),250)=left(dbo.rn_get_atr_val(RSF2.link_saved_form,0,0),250)))







GO
GRANT SELECT ON dbo.[I_REPORT_USER_SAVED_FORMS_WEB_NASTR_FAST] 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_SZV4_SVEDENIA]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SA_SZV4_SVEDENIA]

GO
CREATE VIEW [dbo].SA_SZV4_SVEDENIA
as

SELECT 
	link = S.link_up,
	link1 = S.link,
	LINK_FACE = S.link_pers, 
	S.pachka,
	S.orders,
	forma, 	
	n_forma = ( CASE WHEN D.year_begin < 2010
				THEN case forma when 1 then 'СЗВ-4-1' when 2 then 'СЗВ-4-2' else '' end
				ELSE case forma when 1 then 'СЗВ-6-1' when 2 then 'СЗВ-6-2' else '' end
				END),
	S.LINK_KATEG,				
	K.CODE,
	FM, IM, OT, PF_NUM = INSUR_NUM, 

	FIO = LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.',
	FIO2 = LTRIM(RTRIM(FM)) + ' ' + LTRIM(RTRIM(IM)) + ' ' + LTRIM(RTRIM(OT)),

	ADDRESS = LEFT(ISNULL(dbo.GetAddressByKladr(P.ADR_REAL_LINK), ''), 254) + 
	CASE WHEN LEN(ISNULL(HOUSE_REAL, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(HOUSE_REAL)) END 
	+ CASE WHEN LEN(ISNULL(CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(CORP_REAL)) END 
	+ CASE WHEN LEN(ISNULL(FLAT_REAL, '')) = 0 THEN '' ELSE ', кв. ' + LTRIM(RTRIM(FLAT_REAL)) END ,

	ADDRESS2 = dbo.GET_ADDRESS9PARTS(S.link_pers, 0),

	sum_doh,
	INSUR = sum_str,
	GAIN = sum_nak,
	DOP = sum_dop,
	dper_vn_m,
	dper_vn_d,
	dper_oz_m,
	dper_oz_d,
	isum_str,
	isum_nak,
	S.sum_dolg_str,
	S.sum_uplata_dolga_str,
	S.sum_dolg_nak,
	S.sum_uplata_dolga_nak
FROM 
	dbo.SZV4_PACHKA D
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_UP = D.LINK
	INNER JOIN PERSON P on P.LINK = S.link_pers
	INNER JOIN dbo.SA_PFR_KATEG K on K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND


GO


GRANT SELECT ON dbo.[SA_SZV4_SVEDENIA] 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_SAVED_FORMS_VIEW_SVOD]') AND 
                 OBJECTPROPERTY([ID], N'IsView') = 1)
BEGIN
   DROP VIEW dbo.[RO_SAVED_FORMS_VIEW_SVOD]
END

GO

/*
© Кейсистемс (Keysystems), 2006
*/
CREATE VIEW dbo.[RO_SAVED_FORMS_VIEW_SVOD] AS     
     select  
      link_saved_form as link,
      RSF.link_saved_form,
      RSF.Link_form,
      RF.code,
      RF.name,
      (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) as period,
      convert(CHAR(10),DD.CODE) as dep_code,
      convert(VARCHAR(100),dbo.GetDepName(RSF.Link_Organization, RSF.begin_date)) as dep_name,
  convert(VARCHAR(10), DD.BUDG) as dep_budg,
      RSF.Version,
--  (CASE WHEN RSF.isChangeAnalit=1 THEN coalesce('Разд:' + (select code from BI_Diction_DIV where link = RSF.LinkRazdel) + ' ','')
--         + coalesce('Цел.Ст:' + (select code from BI_Diction_CSR where link = RSF.LinkCelSt) + ' ','')
--         + coalesce('Вид расх:' + (select code from BI_Diction_EXP where link = RSF.LinkRashod) + ' ','')
--    else '' end) 
      '' as Str_Analit,
      RSF.begin_date,
      RSF.period_type,
      RSF.period_number,
      RSF.link_organization,
      RSF.isUpload,
      RSF.isSvod,
  isnull(RSF.Link_Type_Svod,0) Link_Type_Svod,
 [Type_Svod] = isnull((select Name from KL_BUDG_TYPE D where D.link = RSF.Link_Type_Svod), ''),
      RSF.isChangeAnalit,
  Note = convert(VARCHAR(254),RSF.NOTE),
   RSF.IsRO,
 RSF.IsRightKS,
  RF.Export_Proc,
 RF.IsSvod as Svod_Form,
--255 as rules,
 RF.RULES,
  RSF.CountSave,
  DateLastEdit = SJ.date,
 WhoLastEdit = CONVERT (VARCHAR(254), (Isnull (ltrim(rtrim(SJ.FIO)), '') + ' ('+ltrim(rtrim(SJ.Login))+') - ' + ltrim(rtrim(SJ.HOSTNAME)))),
  RSF.isExam,
 IsSign = isnull((select max(type_who) from dbo.report_sign S  where S.lsf = RSF.link_saved_form), 0), --(select top 1 'sign' from report_sign where lsf = RSF.link_saved_form),
	left(RF.atributs,250) atributs,
case when RF.atributs<>'' then 
--then left(dbo.rn_get_atr_val(RSF.link_saved_form,0,0),250) 
 isnull(RSF.atr,'') 
else '' end  as atr_val,
  [START_DATE] = CONVERT(CHAR(10),[RF].[START_DATE],104),
RF.code as form_code,
	date_transfer_web,
	IsXMl = case when exists(select top 1 * from dbo.report_export_xml_forms X where X.Code_Form = RF.Code) then 1 else 0 end
  from report_saved_forms RSF (NOLOCK)
   --INNER hash join  dbo.I_Report_Forms RF on RSF.Link_Form = RF.Link_Form  
   INNER join  dbo.I_Report_Forms RF on RSF.Link_Form = RF.Link_Form   
   left outer join  dictionary_department DD on DD.link = RSF.link_organization
   left outer join  dbo.RO_SF_OWNER SJ on SJ.Link = RSF.link_saved_form
--   INNER join (SELECT distinct link_report_org,link_report_budg FROM RO_SVOD_TREE WHERE dbo.RN_ACCESS_ORG(link_REPORT_ORG,link_REPORT_BUDG)=1) O
--  ON RSF.link_organization=O.link_REPORT_ORG and isnull(RSF.link_type_svod,0)=O.link_REPORT_BUDG
--  where   dbo.RN_ACCESS_ORG(RSF.link_organization,RSF.link_type_svod)=1
   INNER join (SELECT distinct link_report_org,link_report_budg FROM dbo.RN_ACCESS_ORG_TABLE() where Access=1) O
  ON RSF.link_organization=O.link_REPORT_ORG and isnull(RSF.link_type_svod,0)=O.link_REPORT_BUDG
     WHERE    (RSF.[Owner_SID] = SUSER_SID() OR ISNULL((SELECT VALUE
						FROM S_OPTIONS
						WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'REPORT_VIEW_ONLY_OWN')
								AND  SID = suser_sid()), 0) = 0)
              AND del = 0


--where RSF.IsSvod = 1

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


/*
use orel_svod
select * from report_forms
update report_saved_forms set link_type_svod=null where link_form=419
select * from report_saved_forms where link_form=419


select * from dbo.RN_ACCESS_ORG_TABLE()
*/

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_KS_ATR_VALUE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RO_KS_ATR_VALUE]
GO
--на входе линк сохран. формы и код атрибута, на выходе значение этого атрибута
CREATE FUNCTION dbo.RO_KS_ATR_VALUE  (@cAtr varchar(250), @LSF int)
returns varchar(4000)
as
  begin
    declare @str_val varchar(250)
    SET @str_val = dbo.RN_GET_ATR_VALUE(@LSF, @cAtr)
    return @str_val
 end
GO
GRANT ALL ON dbo.[RO_KS_ATR_VALUE] 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.[KU_EMPL_PLACING_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[KU_EMPL_PLACING_FN]

GO

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



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

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

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

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


-- Сведения о статусе сотрудников -----------------------------------------------------------------------
DECLARE @STATUS_EMPL TABLE(EMPL_LINK INT, [STATUS] INT, STATUS_NAME VARCHAR(60))
---------------------------------------------------------------------------------------------------------
INSERT INTO @STATUS_EMPL (EMPL_LINK, [STATUS], STATUS_NAME)
SELECT EMPL_LINK, [STATUS], dbo.PrintKadrGetStatus([STATUS]) AS STATUS_NAME
FROM dbo.EMPL_STATUS(@dDATE)


-- Сведения о ФИО сотрудников
DECLARE @FIO_EMPL TABLE(PERS_LINK int, [FIO] VARCHAR(100),	[NAME_EMPL] VARCHAR(100))
---------------------------------------------------------------------------------------------------------
INSERT INTO @FIO_EMPL(PERS_LINK, [FIO], [NAME_EMPL])
SELECT  [PERS_LINK] = LINK,
		[FIO] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LTRIM(RTRIM(IM)) + ' ' + LTRIM(RTRIM(OT)),'Не заполнено'))),100),
	    [NAME_EMPL] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30)
FROM dbo.PERSON

-- Сведения о телефонах, эл.адресах сотрудников ---------------------------------------------------------
DECLARE @PHONE_MAIL_EMPL TABLE(EMPL_LINK INT, [EMAIL] VARCHAR(254), [PHONE_WORK] VARCHAR(254), [PHONE_MOB] VARCHAR(254))
---------------------------------------------------------------------------------------------------------
INSERT INTO @PHONE_MAIL_EMPL(EMPL_LINK, [EMAIL], [PHONE_WORK],[PHONE_MOB])
SELECT	LINK,
		[EMAIL]		=	LEFT(ISNULL(LTRIM(RTRIM((select DBO.ConcatEmplPhoneValues (2,0,link)) )),' '),254),
		[PHONE_WORK]=	LEFT(ISNULL(LTRIM(RTRIM((select DBO.ConcatEmplPhoneValues (1,3,link)) )),' '),254),
		[PHONE_MOB]	=	LEFT(ISNULL(LTRIM(RTRIM((select DBO.ConcatEmplPhoneValues (1,1,link)) )),' '),254)
FROM dbo.EMPL

-- Заполнение результирующей таблицы --------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
INSERT INTO @RESULT([LINK],
		[PERS_LINK],		[DEP_LINK],		[DEP_NAME],
		[TAB],		[FM],	[IM],	[OT],	[FIO],
		[NAME_EMPL],		[SUBDIV_HEAD],	[SUBDIV_LINK],
		[SUBDIV_CODE],		[SUBDIV_NAME],	[POST_LINK],
		[POST_CODE],		[POST_NAME],	[STAFF_HEAD],
		[STAFF_LINK],		[NUM_STAKE],	[STATUS],
		[STATUS_NAME],		[NOTWORK],		[DATE_BEGIN], [DATE_MOV],
		[OKLAD],			[GRAPH_LINK],	[GRAPH_NAME],
		[DATE_SACK],		[ITEM_MOVE_LINK],		[VIS],
		[LINK_KBK], 		[CODE_KBK], 	[NAME_KBK],
		[RAZR],				[SYST_PAY],		[POST_GROUP], [KATEG],
		[CHIN],				[CHIN_DATE],	[EMAIL],
		[PHONE_WORK],		[PHONE_MOB],	[INN],
		[SNILS],			[SACK],			[SACK_PER])
SELECT	distinct
	T.*,
	CASE
		WHEN datediff(day,T.DATE_SACK, @dDATE) > 0  THEN 1
		ELSE 0
	END AS SACK,
	CASE
		WHEN YEAR(T.DATE_SACK) = YEAR(@dDATE)
		     AND MONTH(T.DATE_SACK) = MONTH(@dDATE) THEN 1
		ELSE 0
	END AS SACK_PER
FROM	(
	SELECT 
		[LINK] 			= 	E.LINK, 
		[PERS_LINK]		= 	P.LINK, 
		[DEP_LINK]		= 	E.DEP_LINK,
		[DEP_NAME]		=	DEP.NAME,
		[TAB]			= 	E.TAB,
		[FM]			= 	P.FM,
		[IM]			= 	P.IM, 
		[OT]			=	P.OT,
		[FIO]			=	FE.FIO,
		[NAME_EMPL]		= 	FE.NAME_EMPL,
		[SUBDIV_HEAD]	=	DS.link_up,
		[SUBDIV_LINK]	=	DS.LINK,
		[SUBDIV_CODE]	=	DS.CODE,
		[SUBDIV_NAME]	=	DS.NAME,
		[POST_LINK]		=	DP.LINK,
		[POST_CODE]		=	DP.CODE,
		[POST_NAME]		=	DP.NAME,
		[STAFF_HEAD]	=	PE.STAFF_HEAD,
		[STAFF_LINK]	= 	PE.STAFF_LINK,
		[NUM_STAKE]		=	PE.NUM_STAKE,
		[STATUS]		=	SE.STATUS,
		[STATUS_NAME]	=	SE.STATUS_NAME,
		[NOTWORK]		=	E.NOTWORK,
		[DATE_BEGIN]	=	IM.DATE_BEGIN,
		[DATE_MOV]		=	PE.DATE_BEG,
		[OKLAD]			=	PE.oklad,
		[GRAPH_LINK]	= 	G.LINK,
		[GRAPH_NAME]	=	G.NAME,
		[DATE_SACK]		=	IDF.DIS_DATE,
		[ITEM_MOVE_LINK] =	PE.MOVE_LINK,
		[VIS]			=	CONVERT(bit, 0),
		LINK_KBK		=	KBK.LINK,
		CODE_KBK		=	KBK.CODE,
		NAME_KBK		=	KBK.NAME,
		RAZR			=	COALESCE(IM.ETS_RAZR,0),
		[SYST_PAY]		=	E.SYST_PAY,		
		[POST_GROUP]	=	GR.NAME,
		[KATEG]			=	KAT.NAME,
		[CHIN]			=	CE.CHIN_NAME,
		[CHIN_DATE]		=	CE.CHIN_DATE,		
		[EMAIL]			=	PME.[EMAIL] ,
		[PHONE_WORK]	=	PME.[PHONE_WORK],
		[PHONE_MOB]		=	PME.[PHONE_MOB],
		[INN]			=	P.INN,
		[SNILS]			=	P.INSUR_NUM
	FROM			dbo.EMPL		E
		INNER JOIN	dbo.PERSON 			P	 ON e.pers_link=p.link
		LEFT JOIN   @FIO_EMPL       FE	 ON P.LINK = FE.PERS_LINK
		LEFT JOIN	dbo.GRAPH			G	 ON e.graph_link=g.link
		LEFT JOIN	@POST_EMPL		PE	 ON E.LINK = PE.EMPL_LINK
		LEFT JOIN	dbo.SAL_SFIN		KBK	 ON KBK.LINK = PE.LINK_KBK		
		LEFT JOIN	dbo.SUBDIV			DS	 ON PE.subdiv_link = DS.LINK
		LEFT JOIN	dbo.POST			DP	 ON PE.post_link = DP.LINK
		LEFT JOIN	dbo.ITEM_MOVE		IM	 ON IM.ACTIVE = 1 AND IM.NEW_FACE = 1 AND IM.EMPL_LINK = E.LINK
		LEFT JOIN	dbo.DEPARTMENTS		DEP	 ON E.DEP_LINK = DEP.LINK
		LEFT JOIN	@STATUS_EMPL	SE	 ON E.LINK = SE.EMPL_LINK	
		LEFT JOIN	@ITEM_DIS_FACE	IDF	 ON E.LINK = IDF.EMPL_LINK
		LEFT JOIN	@CHIN_EMPL		CE	 ON E.LINK = CE.EMPL_LINK
		LEFT JOIN   @PHONE_MAIL_EMPL PME ON E.LINK = PME.EMPL_LINK
		LEFT JOIN	dbo.STAFF ST ON ST.LINK = PE.STAFF_LINK
		LEFT JOIN	dbo.GR_GOS GR ON GR.LINK = ST.GR_GOS_LINK
		LEFT JOIN   DBO.KAT_GOS KAT ON KAT.LINK = ST.KAT_GOS_LINK
		--LEFT JOIN	dbo.KATEG KAT ON KAT.LINK = ST.KAT_LINK

	) T

RETURN
END





GO


GRANT SELECT ON dbo.[KU_EMPL_PLACING_FN] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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


CREATE   VIEW RECEPTION_CASH_TABLE_VIEW
AS

Select 
	F.LINK, 
	F.LINK_UP, 
	RECORD_NO 	= convert(NUMERIC(9), F.RECORD_NO),
	KBK 		= F.KBK, 
	KBK_CODE 	= KBK.CODE,
	KBK_NAME 	= KBK.NAME,
	KBK_TYPE	= KBK.TYPE, 
	EKR 		= F.EKR, 
	EKR_CODE 	= EKR.CODE,
	EKR_NAME 	= EKR.NAME,
	D_CL_LINK 	= F.DOP_CLASSIF,
	D_CL_CODE 	= DC.CODE,
	D_CL_NAME 	= DC.NAME,
	FS_CODE 	= DFS.CODE,
	FS_NAME 	= DFS.NAME,
	VID_SR 		= VS.LINK,
	VID_SR_NAME 	= VS.NAME,
	VID_SR_SNAME 	= VS.SNAME,
	BK_CODE	    = replace(rtrim(KBK.CODE) + isnull('.' + EKR.CODE,'') + isnull('.' + DC.CODE,''),'.',isnull(DO.DELIVKBK,'')),	
	SUMMA		= F.SUMMA,
	F.REASON,
	F.TITLE,
	F.LINK_G1_PP,
	LINK_PP       	= GP.LINK,
	DOC_NAME      	= CONVERT(VARCHAR(254),RTRIM(SO.NAME) + ' №' + LTRIM(RTRIM(GP.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),GP.DATE,104))	,
	F.KP
From RECEPTION_CASH_TABLE F  
LEFT JOIN dbo.bi_diction_kbk KBK ON KBK.LINK = F.KBK
LEFT JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
LEFT JOIN dbo.BD_DOP_CLASSIF DC ON DC.LINK = F.DOP_CLASSIF
LEFT JOIN dbo.BB_FIN_SOURCE DFS ON DFS.CODE = F.SOURCE
LEFT JOIN dbo.BB_ZAYAVKA_KR_SOURCE VS ON VS.LINK = F.VID_SR
LEFT JOIN dbo.G_PROV1 GP1 ON F.LINK_G1_PP = GP1.LINK
LEFT JOIN dbo.G_PROV GP ON GP1.LINK_UP = GP.LINK
LEFT JOIN dbo.S_OBJECTS SO ON GP.OBJECT = SO.LINK
left join dbo.DOCUMENTS_REC_CASH_OPTIONS DO on 1=1


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.[RO_RECYCLE]') AND 
                 OBJECTPROPERTY([ID], N'IsView') = 1)
BEGIN
   DROP VIEW dbo.[RO_RECYCLE]
END

GO

/*
© Кейсистемс (Keysystems), 2006
*/
CREATE VIEW dbo.[RO_RECYCLE] AS     
     select  
      link_saved_form as link,
      RSF.link_saved_form,
      RSF.Link_form,
      RF.code,
      RF.name,
      (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) as period,
      convert(CHAR(10),DD.CODE) as dep_code,
      convert(VARCHAR(100),dbo.GetDepName(RSF.Link_Organization, RSF.begin_date)) as dep_name,
  convert(VARCHAR(10), DD.BUDG) as dep_budg,
      RSF.Version,
      RSF.begin_date,
      RSF.period_type,
      RSF.period_number,
      RSF.link_organization,
      RSF.isUpload,
      RSF.isSvod,
  isnull(RSF.Link_Type_Svod,0) Link_Type_Svod,
 [Type_Svod] = isnull((select Name from KL_BUDG_TYPE D where D.link = RSF.Link_Type_Svod), ''),
  Note = convert(VARCHAR(254),RSF.NOTE),
   RSF.IsRO,
 RSF.IsRightKS,
 RF.IsSvod as Svod_Form,
--255 as rules,
 RF.RULES,
  RSF.CountSave,
  DateLastEdit = SJ.date, 
 WhoLastEdit = CONVERT (VARCHAR(254), (Isnull (ltrim(rtrim(SJ.FIO)), '') + ' ('+ltrim(rtrim(SJ.Login))+') - ' + ltrim(rtrim(SJ.HOSTNAME)))),
  RSF.isExam,
 IsSign = isnull((select max(type_who) from dbo.report_sign S  where S.lsf = RSF.link_saved_form), 0), --(select top 1 'sign' from report_sign where lsf = RSF.link_saved_form),
	left(RF.atributs,250) atributs,
case when RF.atributs<>'' then 
--then left(dbo.rn_get_atr_val(RSF.link_saved_form,0,0),250) 
 isnull(RSF.atr,'') 
else '' end  as atr_val,
  [START_DATE] = CONVERT(CHAR(10),[RF].[START_DATE],104),
RF.code as form_code,
	date_transfer_web
  from report_saved_forms RSF (NOLOCK)
   inner join  dbo.I_Report_Forms RF on RSF.Link_Form = RF.Link_Form  
   left outer join  dictionary_department DD on DD.link = RSF.link_organization
   left outer join  dbo.RO_SF_OWNER SJ on SJ.Link = RSF.link_saved_form
--   INNER join (SELECT distinct link_report_org,link_report_budg FROM RO_SVOD_TREE WHERE dbo.RN_ACCESS_ORG(link_REPORT_ORG,link_REPORT_BUDG)=1) O
--  ON RSF.link_organization=O.link_REPORT_ORG and isnull(RSF.link_type_svod,0)=O.link_REPORT_BUDG
--  where   dbo.RN_ACCESS_ORG(RSF.link_organization,RSF.link_type_svod)=1
   INNER join (SELECT distinct link_report_org,link_report_budg FROM dbo.RN_ACCESS_ORG_TABLE() where Access=1) O
  ON RSF.link_organization=O.link_REPORT_ORG and isnull(RSF.link_type_svod,0)=O.link_REPORT_BUDG
     WHERE    (RSF.[Owner_SID] = SUSER_SID() OR ISNULL((SELECT VALUE
						FROM S_OPTIONS
						WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'REPORT_VIEW_ONLY_OWN')
								AND  SID = suser_sid()), 0) = 0)
              AND del = 1


--where RSF.IsSvod = 1

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


/*
use orel_svod
select * from report_forms
update report_saved_forms set link_type_svod=null where link_form=419
select * from report_saved_forms where link_form=419


select * from dbo.RN_ACCESS_ORG_TABLE()
*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


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

CREATE             FUNCTION dbo.RO_FORM14 (@varKSiLSF int, @varKScShifr varchar(50) = NULL,
  @varKSNotPrintNull bit = 0 -- если 0, то пустые не выводить
)

RETURNS @t_Form14 TABLE 
  (Shifr varchar(10), 
  KBK varchar(50), 
  [Table] char(2), 
  Kods varchar(50), 
  Name varchar(254), 
  GR3 numeric(20,2), 
  GR3_Name varchar(254), 
  GR3_Formula varchar(254), 
  GR4 numeric(20,2), 
  GR4_Name varchar(254), 
  GR4_Formula varchar(254), 
  GR5 numeric(20,2), 
  GR5_Name varchar(254), 
  GR5_Formula varchar(254), 
  Table_Name tinyint default(0),
  Link_Table int,
  GR3_LEN int,
  GR4_LEN int,
  GR5_LEN int)
AS
BEGIN
declare @LinkForm int
declare @t_NameCode table (Code varchar(50), Name varchar(250), TableOrder tinyint, q1 int default(0), Link_Table int,gr3_len int,gr4_len int,gr5_len int)



/*Oleg-----------------------------------------*/
  declare @ord3 table (Name varchar(250),Link_Col int,Link_Table int)
  insert @ord3 (Name,Link_Col,Link_Table) select Name,Link_Col,Link_Table from report_coloumns where orders = 3

  declare @ord4 table (Name varchar(250),Link_Col int,Link_Table int)
  insert @ord4 (Name,Link_Col,Link_Table) select Name,Link_Col,Link_Table from report_coloumns where orders = 4

  declare @ord5 table (Name varchar(250),Link_Col int,Link_Table int)
  insert @ord5 (Name,Link_Col,Link_Table) select Name,Link_Col,Link_Table from report_coloumns where orders = 5

  declare @rt table (Orders tinyint,Link_Form int,Link_Table int,gr3_len int,gr4_len int,gr5_len int)
/*Oleg-----------------------------------------*/

if @varKSiLSF > 0
begin
	
   DECLARE @Date DATETIME 
  declare @t_Data table (Link_Col int, Shifr varchar(10), Kods varchar(10), Float_Val Numeric(20,4))
  insert @t_Data
    select Link_Col, LEFT(Code_Row, CHARINDEX('#', Code_Row) - 1), 
      RIGHT(Code_Row, LEN(Code_Row) - CHARINDEX('#', Code_Row)),
      Float_Val
    from report_dinamics_all
    where Link_SF = @varKSiLSF and CHARINDEX('#', Code_Row) > 0 and (@varKScShifr is NULL or (@varKScShifr is not NULL and LEFT(Code_Row, CHARINDEX('#', Code_Row) - 1) = @varKScShifr)) and abs(Float_Val) > 0.0001

  select @LinkForm = Link_Form, @Date = begin_date from report_saved_forms where link_saved_form = @varKSiLSF

   DELETE @t_Data
   WHERE shifr NOT IN (SELECT [Shifr] 
                       FROM  dbo.REPORT_FORM14_RAZD_NAME 
                       WHERE (begin_date is NULL or begin_date <= @Date) 
                              and (end_date is NULL or end_date >= @Date ))


  insert @rt (Orders,Link_Form,Link_Table,gr3_len,gr4_len,gr5_len) 
select rt.Orders,rt.Link_Form,rt.Link_Table,
  isnull(RC1.val_len,0) gr3_len, 
  isnull(RC2.val_len,0) gr4_len,
  isnull(RC3.val_len,0) gr5_len
   from report_tables rt 
		left join report_coloumns RC1 on RC1.link_table=rt.link_table and RC1.orders=3
		left join report_coloumns RC2 on RC2.link_table=rt.link_table and RC2.orders=4
		left join report_coloumns RC3 on RC3.link_table=rt.link_table and RC3.orders=5
	where rt.Link_Form = @LinkForm



	declare @t_formula table (formula varchar(250), Link_Col int, Link_Row int, Code varchar(50), Link_Table int, orders int)
	insert @t_formula
	select RF.formula, RF.Link_Col, RF.Link_Row, RR.Code, RR.Link_Table, RR.orders
	from @rt RT inner join i_report_rows RR on RR.Link_Table = RT.Link_Table
		join report_formula RF on RF.link_row = RR.link_row
		
	--where Link_Table in (select Link_Table from report_tables where Link_Form = @LinkForm)

  insert @t_NameCode (Name, Code, TableOrder, Link_Table,gr3_len,gr4_len,gr5_len)
    select RF.formula as Name,
      Code, RT.Orders, RT.Link_Table,rt.gr3_len,rt.gr4_len,rt.gr5_len
    from @rt RT
		join report_coloumns RC on RT.Link_Table = RC.Link_Table and RC.orders = 1
		join @t_formula RF  on RC.Link_Col = RF.Link_Col
    order by RT.Orders, RF.Orders


  insert @t_Form14 (Shifr, [Table], Kods, Link_Table,gr3_len,gr4_len,gr5_len)
    select  
      [Shifr] = RD.Shifr,
      [Table] = '0' + LTRIM(STR(C.TableOrder)),
      [Kods] = RD.Kods,
      C.Link_Table,
      [GR3_LEN]=C.GR3_LEN,
      [GR4_LEN]=C.GR4_LEN,
      [GR5_LEN]=C.GR5_LEN
    from  (select distinct Shifr, Kods from @t_Data) RD
      inner join @t_NameCode C on RD.Kods = C.Code

  if @varKScShifr is not NULL
  begin
    delete @t_form14
    where Shifr <> @varKScShifr
  END
  
  if @varKSNotPrintNull = 1 -- выводить пустые
  begin

	insert @t_Form14 (Shifr, [Table], Kods, Link_Table,gr3_len,gr4_len,gr5_len)
      select 
        [Shifr] = I.Shifr, 
        [Table] = '0' + RTRIM(LTRIM(STR(NC.TableOrder))),
        [Kods] = NC.Code,
        NC.Link_Table,
        [GR3_LEN]=NC.GR3_LEN,
        [GR4_LEN]=NC.GR4_LEN,
        [GR5_LEN]=NC.GR5_LEN
      from  (select distinct shifr from @t_Form14) I, @t_NameCode NC
      where not exists(select * from @t_Form14 I1 where I.shifr = I1.shifr and I1.Kods = NC.Code)



    if not exists(select * from @t_Form14) --and @varKScShifr is NULL
    begin
      set @varKSiLSF = -@LinkForm
      delete @t_NameCode
    end
  end
	
  update @t_Form14
      set
        GR3 = isnull(RD.float_val, 0),
        GR3_Name = RC.Name,
        GR3_Formula = formula--(select formula from report_formula RF where RF.Link_Col = RC.Link_Col and RF.Link_Row in (select top 1 Link_Row from i_report_rows RR where Code = I.Kods and RR.Link_Table = RC.Link_Table))
      from  @ord3 RC
        inner merge join @t_Form14 I on (RC.Link_Table = I.Link_Table)
        left merge join @t_Data RD on (RD.Link_Col = RC.Link_Col and I.Shifr = RD.Shifr and I.Kods = RD.Kods)
		left join @t_formula F on F.Link_Col = RC.Link_Col and  F.Code = I.Kods and F.Link_Table = RC.Link_Table
  
  
  
  update @t_Form14
      set
        GR4 = RD.float_val,
        GR4_Name = RC.Name,
        GR4_Formula = formula--(select formula from report_formula RF where RF.Link_Col = RC.Link_Col and RF.Link_Row in (select top 1 Link_Row from i_report_rows RR where Code = I.Kods and RR.Link_Table = RC.Link_Table))
      from @ord4 RC
        inner merge join @t_Form14 I on (RC.Link_Table = I.Link_Table)
        left merge join @t_Data RD on (RD.Link_Col = RC.Link_Col and I.Shifr = RD.Shifr and I.Kods = RD.Kods)
		left join @t_formula F on F.Link_Col = RC.Link_Col and  F.Code = I.Kods and F.Link_Table = RC.Link_Table
  
   update @t_Form14
      set
        GR5 = RD.float_val,
        GR5_Name = RC.Name,
        GR5_Formula = formula--(select formula from report_formula RF where RF.Link_Col = RC.Link_Col and RF.Link_Row in (select top 1 Link_Row from i_report_rows RR where Code = I.Kods and RR.Link_Table = RC.Link_Table))
      from @ord5 RC
        inner merge join @t_Form14 I on (RC.Link_Table = I.Link_Table)
        left merge join @t_Data RD on (RD.Link_Col = RC.Link_Col and I.Shifr = RD.Shifr and I.Kods = RD.Kods)
		left join @t_formula F on F.Link_Col = RC.Link_Col and  F.Code = I.Kods and F.Link_Table = RC.Link_Table

  
  update @t_Form14
    set KBK = Razd_Code + ' ' + Cel_st_Code + ' ' + VR_Code,
      Name = NC.Name
  from @t_Form14 I left join REPORT_FORM14_RAZD_NAME RN on RN.shifr = I.shifr
		left join @t_NameCode NC on NC.Code = I.Kods
end



if @varKSiLSF < 0
begin -- новая форма
  set @LinkForm = abs(@varKSiLSF)

  insert @t_NameCode (Name, Code, TableOrder,gr3_len,gr4_len,gr5_len)
    select (select formula from report_formula RF where RF.Link_Row = RR.Link_Row and Link_Col = (select top 1 Link_Col from report_coloumns RC where RC.Link_Table = RR.Link_Table and RC.Orders = 1)) as Name,
      Code, RT.Orders,
    isnull((select RC.val_len FROM report_coloumns RC where RC.orders=3 and RC.link_table=rt.link_table),0) gr3_len, 
    isnull((select RC.val_len FROM report_coloumns RC where RC.orders=4 and RC.link_table=rt.link_table),0) gr4_len,
    isnull((select RC.val_len FROM report_coloumns RC where RC.orders=5 and RC.link_table=rt.link_table),0) gr5_len
    from i_report_rows RR left join report_tables RT on RR.Link_Table = RT.Link_Table
    where RT.Link_Form = @LinkForm
    order by RT.Orders, RR.Orders


  insert @t_Form14 (Shifr, KBK, [Table], Kods, Name, GR3, GR3_Name, GR3_Formula, GR4, GR4_Name, GR4_Formula, GR5, GR5_Name, GR5_Formula,gr3_len,gr4_len,gr5_len)
    select  [Shifr] = '',
      [KBK] = '', 
      [Table] = '0' + LTRIM(RTRIM(STR(RT.Orders))),
      [Kods] = Code,
      [Name] = NC.Name,
      [GR3] = 0,
      [GR3_Name] = RC.Name,
      [GR3_Formula] = (select top 1 formula from report_formula RF where RF.Link_Row = (select top 1 Link_Row from i_report_rows RR where Code = NC.Code and RR.Link_Table = RT.Link_Table) and RF.Link_Col = RC.Link_Col),
      [GR4] = 0,
      [GR4_Name] = '',
      [GR4_Formula] = '',
      [GR5] = 0,
      [GR5_Name] = '',
      [GR5_Formula] = '',
      [GR3_LEN]=NC.GR3_LEN,
      [GR4_LEN]=NC.GR4_LEN,
      [GR5_LEN]=NC.GR5_LEN
    from @t_NameCode NC, report_coloumns RC
      left join report_tables RT on RC.Link_Table = RT.Link_Table
    where RT.Link_Form = @LinkForm
      and RC.Orders = 3 and RT.Orders = NC.TableOrder


  update @t_Form14
    set [GR4_Name] = RC.Name,
      [GR4_Formula] = (select formula from report_formula RF where RF.Link_Col = RC.Link_Col and RF.Link_Row in (select top 1 Link_Row from i_report_rows RR where Code = I.Kods and RR.Link_Table = RT.Link_Table))
    from @t_Form14 I, @t_NameCode NC, report_coloumns RC
      left join report_tables RT on RC.Link_Table = RT.Link_Table
    where RT.Link_Form = @LinkForm
      and RC.Orders = 4 and RT.Orders = NC.TableOrder
      and I.Kods = NC.Code
  

  update @t_Form14
    set [GR5_Name] = RC.Name,
      [GR5_Formula] = (select formula from report_formula RF where RF.Link_Col = RC.Link_Col and RF.Link_Row in (select top 1 Link_Row from i_report_rows RR where Code = I.Kods and RR.Link_Table = RT.Link_Table))
    from @t_Form14 I, @t_NameCode NC, report_coloumns RC
      left join report_tables RT on RC.Link_Table = RT.Link_Table
    where RT.Link_Form = @LinkForm
      and RC.Orders = 5 and RT.Orders = NC.TableOrder
      and I.Kods = NC.Code

  if @varKScShifr is not NULL
  begin
    update @t_form14
    set   Shifr = @varKScShifr,
      KBK = (select top 1 Razd_Code + ' ' + Cel_st_Code + ' ' + VR_Code from REPORT_FORM14_RAZD_NAME where shifr = @varKScShifr)
  end
end



if @varKScShifr is not NULL
begin
  delete @t_form14
  where Shifr <> @varKScShifr
end

declare @Shifr varchar(10), @KBK varchar(50)

update  @t_form14
  set GR3 = isnull(GR3, 0),
    GR4 = isnull(GR4, 0),
    GR5 = isnull(GR5, 0)

declare cur_TableName cursor local Static
for select distinct Shifr, KBK from @t_form14

open cur_TableName

fetch next from cur_TableName
into @Shifr, @KBK

while @@fetch_status = 0
begin
  insert @t_Form14 (Shifr, KBK, [Table], Name, Table_Name)
  select @Shifr, @KBK, '01', 'Расходы', 1
  union
  select @Shifr, @KBK, '02', 'Численность', 1
  union
  select @Shifr, @KBK, '03', 'Справка', 1
  union
  select @Shifr, @KBK, '04', 'Справка', 1

  fetch next from cur_TableName
  into @Shifr, @KBK
end

close cur_TableName
deallocate cur_TableName

RETURN
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.[FB_REST_FINANS_PERIOD]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[FB_REST_FINANS_PERIOD]

GO

CREATE FUNCTION dbo.FB_REST_FINANS_PERIOD(	@dDateBeg 		datetime = null, 
					@dDateEnd 		datetime,
					@cFinObjCode 	char(100), 
					@cTypeBudg 	Char(1) = '1',
					@iIsRBS		INT	= 0,
					@iOwnDep	int = null)
RETURNS @tRes TABLE
	(DEP	 [int] NULL,
	 DEP_ACC [int] NULL,
	 RBS_DEP [int] NULL,
	 RBS_ACC [int] NULL,
	 VKR	 [int] NULL,
	 EKR	 [int] NULL, 
	 DOP_CL	 [int] NULL, 
	 TITLE	 varchar(254),
	 SUMMA	 [numeric](28, 2) NULL)

AS
BEGIN
DECLARE @iAccount 	int,
	@iObjLink 	int,
	@iFyear		int,
	@iBegMonth	int,
	@iEndMonth	int,
	@iLimType	int,
	@iLimPer	int,
	@cSinth		char(3)
DECLARE @tTemp TABLE 
	(DEP	[int] NULL,
	 DEP_ACC [int] NULL,
	 RBS_DEP [int] NULL,
	 RBS_ACC [int] NULL,
	 VKR	 [int] NULL,
	 EKR	 [int] NULL, 
	 DOP_CL	 [int] NULL,
	 PER_NUM int,
	 TITLE	 varchar(254),
	 P1	 [numeric](19, 2) NULL,
	 P2	 [numeric](19, 2) NULL,
	 P3	 [numeric](19, 2) NULL,
	 P4	 [numeric](19, 2) NULL,
	 P5	 [numeric](19, 2) NULL,
	 P6	 [numeric](19, 2) NULL,
	 P7	 [numeric](19, 2) NULL,
	 P8	 [numeric](19, 2) NULL,
	 P9	 [numeric](19, 2) NULL,
	 P10	 [numeric](19, 2) NULL,
	 P11	 [numeric](19, 2) NULL,
	 P12	 [numeric](19, 2) NULL)

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

set @iBegMonth = month(@dDateBeg)
set @iEndMonth = month(@dDateEnd)

set @iFyear = year(@dDateEnd)
if @dDateBeg is null
	set @dDateBeg = cast(@iFyear as char(4)) + '0101'
					

if @iOwnDep is null
	set @iOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
IF @iIsRBS < 1 or @iIsRBS is null
	set @iIsRBS = dbo.FB_GetDepIS_RBS(@iOwnDep,default) 

IF @cFinObjCode like '%_ASSIGN%'
	SELECT	@iLimType = 0,
		@iLimPer = max(FIN_SMETA_PER)
		FROM WorkMode
ELSE
	IF @cFinObjCode = 'FB_RESULT_FINANS'
		SELECT	@iLimType = 1,
			@iLimPer = 3
			FROM WorkMode
	ELSE
		IF @cFinObjCode  = 'FB_PLAN'
			SELECT	@iLimType = 0,
			@iLimPer = PERIOD
			FROM dbo.FB_PLAN_OPTIONS
		ELSE
			IF @cFinObjCode  = 'FB_ZAYAVKA'
				SELECT	@iLimType = 0,
				@iLimPer = PERIOD
				FROM dbo.FB_ZAYAVKA_OPTIONS
			ELSE
				SELECT	@iLimType = max(FIN_LIM_TYPE),
				@iLimPer = max(FIN_LIM_PER)
				FROM WorkMode


	   

select  @iObjLink = LINK from dbo.S_OBJECTS where code = @cFinObjCode

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


if @cFinObjCode like '%_SVOD' 
		SELECT @iAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '12' and cSource = @cTypeBudg  
else 
	IF @iIsRBS > 1
		SELECT @iAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '14' and cSource = @cTypeBudg  
	ELSE
		SELECT @iAccount = link 
		FROM s_accounts 
		WHERE cSinth = @cSinth and cAnalit = '13' and cSource = @cTypeBudg  

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

IF /*@cFinObjCode like '%_ASSIGN%' or*/ @cFinObjCode LIKE '%_SMETA%' or @cFinObjCode = 'FB_RESULT_FINANS'  or @cFinObjCode = 'FB_PLAN'  or @cFinObjCode = 'FB_ZAYAVKA'
begin
	if @cFinObjCode = 'FB_PLAN'  or @cFinObjCode = 'FB_ZAYAVKA'
		INSERT INTO @tTemp (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, PER_NUM, TITLE, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
		SELECT DA.LINK_UP, GP.ACC, GP.dep, GP.ACC, F.VKR, F.EKR, F.DOP_CL, 0, 
		/*(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 1)) then sum(F.p1) else 0 end) as p1,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 2)) then sum(F.p2) else 0 end) as p2,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 1) or (@varKSintTypePer = 13 and @varKSintPer_num = 3)) then sum(F.p3) else 0 end) as p3,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 4)) then sum(F.p4) else 0 end) as p4,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 5)) then sum(F.p5) else 0 end) as p5,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 4) or (@varKSintTypePer = 13 and @varKSintPer_num = 6)) then sum(F.p6) else 0 end) as p6,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 7)) then sum(F.p7) else 0 end) as p7,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 8)) then sum(F.p8) else 0 end) as p8,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 7) or (@varKSintTypePer = 13 and @varKSintPer_num = 9)) then sum(F.p9) else 0 end) as p9,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 10)) then sum(F.p10) else 0 end) as p10,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 11)) then sum(F.p11) else 0 end) as p11,
		(case when (@varKSintPer_num = 0 or @varKSintTypePer < 12 or (@varKSintTypePer = 12 and @varKSintPer_num = 10) or (@varKSintTypePer = 13 and @varKSintPer_num = 12)) then sum(F.p12) else 0 end) as p12*/
		MAX(F.COMMENT),
		sum(F.p1) as p1,
		sum(F.p2) as p2,
		sum(F.p3) as p3,
		sum(F.p4) as p4,
		sum(F.p5) as p5,
		sum(F.p6) as p6,
		sum(F.p7) as p7,
		sum(F.p8) as p8,
		sum(F.p9) as p9,
		sum(F.p10) as p10,
		sum(F.p11) as p11,
		sum(F.p12) as p12
		from dbo.FINANSE F
		inner join dbo.G_PROV GP on GP.object in (select link from s_objects where REPLACE(Code,'_CC','') = @cFinObjCode)
					and GP.DATE_PROV is not null  
					and GP.DEP = @iOwnDep
					and GP.DATE_PROV between @dDateBeg and @dDateEnd
					and F.link_up = GP.link
		inner join dbo.DEPARTMENT_ACCOUNTS DA on da.LINK = GP.ACC
							and ((DA.TYPE = 2 or DA.TYPE = 3) and @cTypeBudg = '1'
							or (DA.TYPE = 1 or DA.TYPE = 4)  and @cTypeBudg = '2' or @cTypeBudg is null)
		group by DA.LINK_UP, GP.ACC, GP.DEP, F.VKR, F.EKR, F.DOP_CL
	else	
	INSERT INTO @tTemp (DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, PER_NUM, TITLE, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
	SELECT DA.LINK_UP, FH.ACCOUNT, GP.dep, GP.ACC, F.VKR, F.EKR, F.DOP_CL, FH.PER_NUM, 
	MAX(F.COMMENT),
	sum(F.p1) as p1,
	sum(F.p2) as p2,
	sum(F.p3) as p3,
	sum(F.p4) as p4,
	sum(F.p5) as p5,
	sum(F.p6) as p6,
	sum(F.p7) as p7,
	sum(F.p8) as p8,
	sum(F.p9) as p9,
	sum(F.p10) as p10,
	sum(F.p11) as p11,
	sum(F.p12) as p12
	from dbo.FINANSE F
	inner join dbo.G_PROV GP on GP.object in (select link from s_objects where REPLACE(Code,'_CC','') = @cFinObjCode)
				and GP.DATE_PROV is not null  
				and GP.DEP = @iOwnDep
				and GP.DATE_PROV <= @dDateEnd
				and F.link_up = GP.link
	inner join dbo.FINANSE_HEAD FH on FH.LINK = GP.LINK and FH.FYEAR = @iFyear
	inner join dbo.DEPARTMENT_ACCOUNTS DA on da.LINK = FH.ACCOUNT
						and ((DA.TYPE = 2 or DA.TYPE = 3) and @cTypeBudg = '1'
						or (DA.TYPE = 1 or DA.TYPE = 4)  and @cTypeBudg = '2' or @cTypeBudg is null)
	group by DA.LINK_UP, FH.ACCOUNT, GP.DEP, GP.ACC, F.VKR, F.EKR, F.DOP_CL, FH.PER_NUM
	
	if @iLimType = 0
	begin	
		if @iLimPer = 1
			insert into @tRes(DEP, DEP_ACC, RBS_DEP, RBS_ACC , VKR, EKR, DOP_CL, TITLE, SUMMA)
			select DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, TITLE, P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10 + P11 + P12
			from @tTemp T
		if @iLimPer = 2
			insert into @tRes(DEP, DEP_ACC, RBS_DEP, RBS_ACC , VKR, EKR, DOP_CL, TITLE, SUMMA)
			select DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, TITLE, 
				/*case when @iBegMonth = 1 or @iBegMonth = 2 or @iEndMonth = 2 or @iEndMonth = 3 then P1 + P2 + P3 else 0 end + 
				case when @iBegMonth = 4 or @iBegMonth = 5 or @iEndMonth = 5 or @iEndMonth = 6 then P1 + P2 + P3 else 0 end + 
				case when @iBegMonth = 7 or @iBegMonth = 8 or @iEndMonth = 8 or @iEndMonth = 9 then P1 + P2 + P3 else 0 end + 
				case when @iBegMonth = 10 or @iBegMonth = 11 or @iEndMonth = 11 or @iEndMonth = 12 then P1 + P2 + P3 else 0 end
				*/case when @iBegMonth < 4 then P1 + P2 + P3 else 0 end + 
				case when @iBegMonth < 7 AND @iEndMonth > 3 then P4 + P5 + P6 else 0 end + 
				case when @iBegMonth < 10 and @iEndMonth > 6 then P7 + P8 + P9 else 0 end + 
				case when @iEndMonth > 9 then P10 + P11 + P12 else 0 end
			from @tTemp T
		if @iLimPer = 3
			insert into @tRes(DEP, DEP_ACC, RBS_DEP, RBS_ACC , VKR, EKR, DOP_CL, TITLE, SUMMA)
			select DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, TITLE, 
				case when 1 between @iBegMonth and @iEndMonth then P1 else 0 end + 
				case when 2 between @iBegMonth and @iEndMonth then P2 else 0 end + 
				case when 3 between @iBegMonth and @iEndMonth then P3 else 0 end + 
				case when 4 between @iBegMonth and @iEndMonth then P4 else 0 end + 
				case when 5 between @iBegMonth and @iEndMonth then P5 else 0 end + 
				case when 6 between @iBegMonth and @iEndMonth then P6 else 0 end + 
				case when 7 between @iBegMonth and @iEndMonth then P7 else 0 end + 
				case when 8 between @iBegMonth and @iEndMonth then P8 else 0 end + 
				case when 9 between @iBegMonth and @iEndMonth then P9 else 0 end + 
				case when 10 between @iBegMonth and @iEndMonth then P10 else 0 end + 
				case when 11 between @iBegMonth and @iEndMonth then P11 else 0 end + 
				case when 12 between @iBegMonth and @iEndMonth then P12 else 0 end
			from @tTemp T
	end
	else 
		insert into @tRes(DEP, DEP_ACC, RBS_DEP, RBS_ACC , VKR, EKR, DOP_CL, TITLE, SUMMA)
		select DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, TITLE, P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10 + P11 + P12
		from @tTemp T
		where PER_NUM between @iBegMonth and @iEndMonth
end	
ELSE 
	insert into @tRes(DEP, DEP_ACC, RBS_DEP, RBS_ACC, VKR, EKR, DOP_CL, TITLE, SUMMA)
	select DEP, DEP_ACC, DEP_LINK, ACC_LINK, KBK AS VKR, EKR, AP2 AS DOP_CL, '', sum(isnull(K_SUMMA,0))
	from FB_LimitOborotByPeriod(@dDateBeg,@dDateEnd, @iAccount)
	where DEP_LINK = @iOwnDep
		and not DATE_PROV > @dDateEnd
	group by DEP, DEP_ACC, DEP_LINK, ACC_LINK, KBK, EKR, AP2


RETURN
END



GO


GRANT SELECT ON dbo.[FB_REST_FINANS_PERIOD] 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.[XD_DEP_KBK_PROC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.XD_DEP_KBK_PROC

GO


CREATE	PROCEDURE XD_DEP_KBK_PROC @iDepLink int
AS
SELECT	CHECKED = convert(bit, 0),
		LINK = K.LINK, 
		KBK_LINK = K.LINK, 
		KBK_CODE = K.code, 
		KBK_NAME = K.Name, 
		USED_ALL   = K.USED_ALL,
		OSN		   = isnull(DKBK.OSN,0),
		DKBK.DEP_LINK

FROM BI_DICTION_KBK K 
left join dbo.DEPARTMENT_KBK DKBK on DKBK.KBK_LINK = K.LINK and DKBK.DEP_LINK = @iDepLink
where USED_ALL = 1 or DKBK.DEP_LINK is not null

return 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE VIEW [dbo].[DOCUMENTS_KADR_WRIT]  AS 
SELECT
	[LINK]				= S.LINK,
	[NUMBER]			= S.NUMBER,
	[DATE]				= S.[DATE],
	[CODE_PAY]			= P1.CODE,
	[NAME_PAY]			= P1.NAME,
	[REF_PAY]			= SD.LINK_PAY,
	[COMMENTARY]			= S.[COMMENTARY],
	[FLAG_JC]			= (CASE WHEN EXISTS(SELECT * FROM SDOC_TISP WHERE REF_DOC = S.LINK) THEN 1 ELSE 0 END),
	[TAB_NUMER]			= E.TAB,
	[NAME_EMPL]			= dbo.sd_GetEmplName(SD.LINK_EMPL),
	[REF_EMPL] 			= SD.LINK_EMPL,
	[COD_ORGANIZATION]		= DD1.CODE,
	[NAM_ORGANIZATION]		= DD1.NAME,
	[REF_ORGANIZATION]		= SD.LINK_ORG,
	[DATE1]				= SD.DATE1,
	[DATE2]				= SD.DATE2,
	[SUMMA]				= SD.SUMMA,
	[PAYMENT]			= SD.PAYMENT,
	[WAY]				= SD.WAY,
	[SUM_ENUM]			= SD.SUM_ENUM,
	[PERCENT]			= SD.PERC,
	[SUMMA_NEED]			= SD.SUMMA_NEED,
	[COD_ORGP]			= DD2.CODE,
	[NAM_ORGP] 			= DD2.NAME,
	[REF_ORGP]			= SD.LINK_ORGP,
	[CODE_PAYP]			= P2.CODE,
	[NAME_PAYP]			= P2.NAME,
	[REF_PAYP]			= SD.LINK_PAYP,
	[NAME_VKR]			= CASE WHEN COALESCE(SD.LINK_VKR,0) <> 0 THEN F.CODE ELSE 'Пропорционально' END,
	[LINK_VKR]			= SD.LINK_VKR,
	[INO]				= SD.INO,
	[LINK_DEP]  			= S.LINK_DEP,
	dep.NAME as name_dep,
	PERC_SFIN,
	NO_NDFL,
	BY_EKR
FROM SDOC S INNER JOIN SDOC_WRIT SD ON S.LINK = SD.LINK_UP 
	INNER JOIN dbo.EMPL E ON E.LINK = SD.LINK_EMPL 
	INNER JOIN dbo.DEPARTMENTS dep on dep.link = s.LINK_DEP
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DD1 ON SD.LINK_ORG = DD1.LINK	
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DD2 ON SD.LINK_ORGP = DD2.LINK
	LEFT OUTER JOIN PAYS P1 ON SD.LINK_PAY = P1.LINK	
	LEFT OUTER JOIN PAYS P2 ON SD.LINK_PAYP = P2.LINK
	LEFT JOIN dbo.SAL_SFIN F ON F.LINK = SD.LINK_VKR
WHERE S.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_KADR_WRIT')





GO


GRANT SELECT ON dbo.[DOCUMENTS_KADR_WRIT] TO PUBLIC

GO

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

GO
CREATE FUNCTION dbo.RK_GET_NASTR_CALC_REPORT
	(@intLSF	INT, @iOtherCaclc tinyint = 0)	--- Ссылка сохраненной формы ---
	RETURNS INT
AS
BEGIN
	DECLARE @intLINK_CALC	INT,
			@intLINK_FORM	INT

	SELECT @intLINK_FORM = RSF.LINK_fORM 
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE RSF.LINK_SAVED_FORM = @intLSF

	if @iOtherCaclc = 0 and exists(select * from dbo.REPORT_FORMS where LINK_FORM = @intLINK_FORM and CODE like '%0503[17]25%')
		return NULL
	--- Поиск расчета по заданным атрибутам ---
	SET @intLINK_CALC = (SELECT TOP 1 LINK
							from dbo.REPORT_CALC_FORMS 
							WHERE LINK_FORM =  @intLINK_FORM and dbo.RN_GET_ATR_VAL(@intLSF,@intLINK_FORM,0) like dbo.BB_CALC_GET_ATR_VAL(LINK,@intLINK_FORM,2) and USED = 1 
							ORDER BY [ORDER] DESC, LEN(dbo.BB_CALC_GET_ATR_VAL(LINK,@intLINK_FORM,2)))
	
	--- Если нет расчета с заданными атрибутами, то поиск расчета без атрибутов ---
	IF @intLINK_CALC is null 
		SET @intLINK_CALC = (SELECT TOP 1 LINK
							from dbo.REPORT_CALC_FORMS 
							WHERE LINK_FORM =  @intLINK_FORM and rtrim(dbo.BB_CALC_GET_ATR_VAL(LINK,@intLINK_FORM,0)) = '' and USED = 1 
							ORDER BY [ORDER] DESC)

	RETURN @intLINK_CALC
END


GO


GRANT EXECUTE ON dbo.[RK_GET_NASTR_CALC_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].[RS_ECP_SERTIFICATE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[RS_ECP_SERTIFICATE]
GO


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


CREATE       
VIEW dbo.[RS_ECP_SERTIFICATE] AS
select  SID = dbo.AdminGetSidByUID(dbu.uid), UID = dbu.UID, Login = dbu.name, SERT_NAME = usert.sert_name from db_users dbu 
left join dbo.user_sert usert on usert.sid = dbo.AdminGetSidByUID(dbu.uid)
where (dbu.[isSQLuser] = 1 OR dbu.[isNTuser] = 1)	 and dbo.AdminGetSidByUID(dbu.uid) is not null

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].[PrintPlatporGetNDSString]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[PrintPlatporGetNDSString]
GO




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









CREATE FUNCTION dbo.PrintPlatporGetNDSString (@varKSnLinkDoc int, @iLF tinyint = 0)
RETURNS VARCHAR(254)
AS
BEGIN
	DECLARE @varKSNDSKIND VARCHAR(254), 
        @varKSSumma NUMERIC(28,2), @varKSNDS NUMERIC(28,2), @varKSSUMNDS NUMERIC(28,2)
		
	SELECT @varKSNDSKIND = isnull((SELECT SHABLON FROM DICTIONARY_PAY_NDS NDS WHERE NDS.LINK = NDS_LINK), ''),
			@varKSSumma = isnull(SUMMA, 0),
			@varKSNDS = ISNULL(NDS, 0),
			@varKSSUMNDS = isnull(SUMMA_NDS,0)
	FROM DOCUMENTS_PAY
	WHERE LINK = @varKSnLinkDoc

	--SELECT @varKSSUMNDS = CASE WHEN @varKSNDS = 0.0 THEN 0.0 ELSE @varKSSumma * @varKSNDS / (100.0 + @varKSNDS) END

	SET @varKSNDSKIND = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@varKSNDSKIND,
						'<Процент>', rtrim(ltrim(str(@varKSNDS)))),
						'<Руб>', rtrim(ltrim(str(floor(@varKSSumma))))),
						'<Коп>', right('00' + rtrim(ltrim(str((@varKSSumma - floor(@varKSSumma)) * 100))),2)),
						'<НДС_Руб>', rtrim(ltrim(str(floor(@varKSSUMNDS))))),
						'<НДС_Коп>', right('00' + rtrim(ltrim(str((@varKSSUMNDS - floor(@varKSSUMNDS)) * 100))),2))
	
	
	if @iLF = 1
		SET @varKSNDSKIND = REPLACE(@varKSNDSKIND, '<Перевод_строки>', char(10))
	else
		SET @varKSNDSKIND = ltrim(REPLACE(@varKSNDSKIND, '<Перевод_строки>', ''))

	RETURN 	@varKSNDSKIND
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_BK_FOR_SHABLON]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[BB_BK_FOR_SHABLON]
GO

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

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

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

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

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

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


GRANT ALL ON dbo.BB_BK_FOR_SHABLON 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_P_CREDIT]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[BB_P_CREDIT]
GO


CREATE VIEW dbo.BB_P_CREDIT
AS
 	SELECT 	
		GP.LINK,
		GP.NUMBER,
		GP.SUMMA,
		GP.COMMENT,
		GP.[DATE],
		GP.DATE_PROV,
		[FLAG_JC]   = CASE WHEN GP.DATE_PROV IS NULL THEN 0 ELSE 1 END,
		[TYPE]	    = CT.LINK,
		[TYPE_CODE] = CT.CODE,
		[TYPE_NAME] = CT.NAME,
		[ACC_LINK]  = GP.ACC,
		[ACC_CODE]  = DA.CODE,
		[ACC_NAME]  = DA.ANAME,
		[DEP_LINK]  = GP.DEP,
		[DEP_CODE]  = D.CODE,
		[DEP_NAME]  = D.NAME,
		[KACC_LINK] = CH.ACC,
		[KACC_CODE] = DAP.CODE,
		[KACC_NAME] = DAP.ANAME,
		[KDEP_LINK] = CH.DEP,
		[KDEP_CODE] = DP.CODE,
		[KDEP_NAME] = DP.NAME,
		[DOC_LINK]  = CH.DOC_LINK,
		[DOC_NUM]   = O.[NUMBER],
		[DOC_DATE]  = O.[DATE],
		[DOC_NAME]  = RTRIM(O.TYPE),
		[ADOC_NAME] = O.INFO,
		CH.FIN_SOURCE,
		CH.NUM_ACC,
		DATE_BEG = dbo.BB_CREDIT_DATE_BEG(GP.LINK),
		DATE_END = dbo.BB_CREDIT_DATE_END(GP.LINK, default, default)
	FROM dbo.G_PROV as GP WITH (NOLOCK)
	INNER JOIN dbo.CREDIT_HEAD CH 	   	ON CH.LINK  = GP.LINK
	LEFT  JOIN dbo.DEPARTMENTS D   	   	ON D.LINK   = GP.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DA	ON DA.LINK  = GP.ACC
	LEFT  JOIN dbo.DEPARTMENTS DP   	ON DP.LINK  = CH.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DAP	ON DAP.LINK = CH.ACC
	LEFT  JOIN dbo.BD_OSNOV O 			ON O.LINK   = CH.DOC_LINK
	LEFT  JOIN dbo.CREDIT_TYPES CT 		ON CT.LINK  = CH.TYPE
	WHERE GP.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BB_P_CREDIT')


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_P_CREDIT to public
GO

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

GO

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

CREATE FUNCTION dbo.ARestFullCalc (@varKSRestDate DateTime = null, @varKSaccount int = null)

RETURNS @varKSRestTable TABLE 
	([ACCOUNT] [int] NOT NULL,
	[D_SUMMA] [numeric](28, 2) NOT NULL,
	[K_SUMMA] [numeric](28, 2) NOT NULL,
	[R_SUMMA] [numeric](28, 2) NOT NULL,
	[D_QUANTITY] [numeric](28, 4) NOT NULL,
	[K_QUANTITY] [numeric](28, 4) NOT NULL,
	[KBK]	[int] NULL,
	[EKR]	[int] NULL,
	[DEP]	[int] NULL,
	[SUB]	[int] NULL,
	[EMP]	[int] NULL,
	[NOMEN]	[int] NULL,
	[INV]	[int] NULL,
	[KAU]	[int] NULL,
	[DEP_ACC]	[int] NULL,
	[TMC]	[int] NULL,
	[INDATE]	[datetime] NULL,
	[AP1]	[int] NULL,
	[AP2]	[int] NULL,
	[AP3]	[int] NULL,
	[SGU]	[int] NULL,
	[DEP_LINK] [int] NOT NULL,
	[PRICE] [numeric](28, 6) NOT NULL,
	[PRICE_TYPE] [TINYINT] NOT NULL)
AS
BEGIN
	Declare @varKSPreviosDATE DateTime,
		@varKSLastOborotDay Datetime,
		@varKSStartDate DateTime,
		@dBeginDateYear	DATETIME

	IF @varKSRestDate IS NULL
		SELECT @varKSRestDate = ENDDATE + 1 FROM dbo.ADMIN_INFO

	SET @varKSLastOborotDay = @varKSRestDate - 1
        
	SET @varKSPreviosDATE = dbo.RestGetLastDate(@varKSRestDate)

	Select @varKSStartDate = dbo.RestGetStartDate()

	SET @dBeginDateYear = dbo.DateBeginOfYear (@varKSRestDate)
	
	INSERT INTO @varKSRestTable(ACCOUNT, D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3, SGU, DEP_LINK, PRICE, PRICE_TYPE)
       	SELECT ACCOUNT,
       		SUM(D_SUMMA),
       		SUM(K_SUMMA),
       		SUM(R_SUMMA),
       		SUM(D_QUANTITY),
       		SUM(K_QUANTITY),
       		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3,
		CASE WHEN SA.p_Kassa = 1 THEN SI.SGU ELSE NULL END,
		DEP_LINK,
		PRICE, PRICE_TYPE
       	FROM 
	(SELECT ACCOUNT,
		CASE WHEN B_YEAR0 = 1 AND DATE_PROV <  @dBeginDateYear THEN 0 ELSE D_SUMMA END AS D_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND DATE_PROV <  @dBeginDateYear THEN 0 ELSE K_SUMMA END AS K_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND DATE_PROV <  @dBeginDateYear THEN 0 ELSE R_SUMMA END AS R_SUMMA,
		D_QUANTITY,K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3, SGU,DEP_LINK, PRICE, PRICE_TYPE
	 FROM dbo.ARestPackedOborotByPeriod (@varKSPreviosDATE, @varKSLastOborotDay, @varKSaccount)
	 UNION ALL
	 SELECT ACCOUNT,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE D_SUMMA END AS D_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE K_SUMMA END AS K_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE R_SUMMA END AS R_SUMMA,
		D_QUANTITY,  K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3, SGU,DEP_LINK, PRICE, PRICE_TYPE
	 FROM dbo.SALDO_CLEARED
	 WHERE  @varKSaccount IS NULL 
		AND
		(  [DATE] = @varKSPreviosDATE AND ISOBOROT = 0
		OR [DATE] BETWEEN @varKSPreviosDATE AND @varKSLastOborotDay AND ISOBOROT = 2)
	 UNION ALL
	 SELECT ACCOUNT,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE D_SUMMA END AS D_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE K_SUMMA END AS K_SUMMA,
		CASE WHEN B_YEAR0 = 1 AND [DATE] <  @dBeginDateYear THEN 0 ELSE R_SUMMA END AS R_SUMMA,
		D_QUANTITY, K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3, SGU,DEP_LINK, PRICE, PRICE_TYPE
	 FROM dbo.SALDO_CLEARED
	 WHERE @varKSaccount IS NOT NULL AND
		ACCOUNT IN (Select LINK From dbo.AccountsSubtreeByRoot(@varKSaccount))
		AND
		(  [DATE] = @varKSPreviosDATE AND ISOBOROT = 0
		OR [DATE] BETWEEN @varKSPreviosDATE AND @varKSLastOborotDay AND ISOBOROT = 2)
	) SI INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = SI.ACCOUNT
	GROUP BY ACCOUNT, KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, INDATE, AP1, AP2, AP3,
		CASE WHEN SA.p_Kassa = 1 THEN SI.SGU ELSE NULL END,
		DEP_LINK, PRICE, PRICE_TYPE
	
	UPDATE @varKSRestTable
	SET 
		D_SUMMA = dbo.ARestCalcDtSaldo(1, 1, D_SUMMA, K_SUMMA),
		K_SUMMA = dbo.ARestCalcKtSaldo(1, 1, D_SUMMA, K_SUMMA)
	WHERE D_SUMMA <> 0 AND K_SUMMA <> 0

	DELETE FROM @varKSRestTable
	WHERE D_SUMMA = 0 AND K_SUMMA = 0 AND R_SUMMA = 0 AND D_QUANTITY = 0 AND K_QUANTITY = 0

	-- !!!Обновление фактической цены списания, если послупление и списание было в 1 день!!! --
	UPDATE T1
	SET PRICE = T2.PRICE
	FROM @varKSRestTable	T1
	INNER JOIN @varKSRestTable T2 ON 
				(T2.D_QUANTITY > 0 AND T2.D_SUMMA > 0)
				AND ISNULL (T2.ACCOUNT, 0) = ISNULL (T1.ACCOUNT, 0)
				AND ISNULL (T2.KBK, 0) = ISNULL (T1.KBK, 0)
				AND ISNULL (T2.EKR, 0) = ISNULL (T1.EKR, 0)
				AND ISNULL (T2.DEP, 0) = ISNULL (T1.DEP, 0)
				AND ISNULL (T2.SUB, 0) = ISNULL (T1.SUB, 0)
				AND ISNULL (T2.EMP, 0) = ISNULL (T1.EMP, 0)
				AND ISNULL (T2.DEP_LINK, 0) = ISNULL (T1.DEP_LINK, 0)
				AND ISNULL (T2.NOMEN, 0) = ISNULL (T1.NOMEN, 0)
				AND ISNULL (T2.INV, 0) = ISNULL (T1.INV, 0)
				AND ISNULL (T2.KAU, 0) = ISNULL (T1.KAU, 0)
				AND ISNULL (T2.DEP_ACC, 0) = ISNULL (T1.DEP_ACC, 0)
				AND ISNULL (T2.TMC, 0) = ISNULL (T1.TMC, 0)
				AND ISNULL (T2.INDATE, '17530101') = ISNULL (T1.INDATE, '17530101')
				AND ISNULL (T2.AP1, 0) = ISNULL (T1.AP1, 0)
				AND ISNULL (T2.AP2, 0) = ISNULL (T1.AP2, 0)
				AND ISNULL (T2.AP3, 0) = ISNULL (T1.AP3, 0)
				AND CONVERT (NUMERIC (28,2), T2.PRICE) = CONVERT (NUMERIC (28,2), T1.PRICE)
	WHERE T1.PRICE_TYPE = 1
		AND (T1.D_QUANTITY < 0 OR T1.D_SUMMA < 0)

RETURN
END


GO


GRANT SELECT ON dbo.[ARestFullCalc] TO PUBLIC

GO


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


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

GO

CREATE FUNCTION dbo.XK_GetTable_Doc_FOREIGN (@intLINK_PRIMARY	INT = -1)
RETURNS TABLE 
AS RETURN
	SELECT G_REF.DOC_REF_PRIMARY AS [G_PRIMARY],
		G.*,
		[FLAG_JC] = CASE WHEN G.DATE_PROV IS NULL THEN 0 ELSE 1 END,
		SO_REF.CODE AS REF_CODE,
		SO.CODE AS DOC_CODE,
		dbo.GetDocumentName (G.LINK, SO.LINK) AS DOC_NAME,
		ISNULL (dbo.GetDocumentName (G.LINK, SO.LINK), '')
			+ ' № ' + RTRIM (G.NUMBER)
			+ ' от ' + CONVERT (VARCHAR (10), G.[DATE], 104) AS DOC_INFO
	FROM dbo.G_PROV_REF G_REF
	INNER JOIN dbo.S_OBJECTS SO_REF ON (SO_REF.LINK = G_REF.OBJECT)
	INNER JOIN dbo.G_PROV G ON (G.LINK = DOC_REF_FOREIGN)
	INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = G.OBJECT)
	WHERE G_REF.DOC_REF_PRIMARY = @intLINK_PRIMARY
		OR @intLINK_PRIMARY = -1



GO


GRANT SELECT ON dbo.[XK_GetTable_Doc_FOREIGN] TO PUBLIC

GO


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


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

GO

-- ДОБАВЛЕНЫ ПОЛЯ:
-- группа должностей
-- классный чин
-- дата присвоения (классного чина)
-- дата назначеняи на дожность
-- электронная почта
-- телефон (служебный)
-- телефон (мобильный)
-- ИНН
-- СНИЛС

CREATE  VIEW dbo.KU_EMPL_PLACING
AS
SELECT *
FROM dbo.KU_EMPL_PLACING_FN(default)


GO


GRANT SELECT ON dbo.[KU_EMPL_PLACING] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * 
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_GET_USER_INFO]') AND 
                 XTYPE IN (N'FN', N'IF', N'TF'))
   DROP FUNCTION dbo.[RA_GET_USER_INFO]
GO

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

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

*******************************************************************************/
-- Функция получения информации о пользователе БД для отчетности.
CREATE FUNCTION dbo.[RA_GET_USER_INFO]
(
   @iUSER_ID VARBINARY(85) = NULL -- Пользователь БД (если NULL - текущий пользователь).
 )
-- Возвращаемый динамический запрос.
RETURNS @tabReturn TABLE ([EMPL_LINK] INT,
                          [FIO]       VARCHAR(254),
                          [POST]      VARCHAR(254),
                          [PHONES]    VARCHAR(254))
BEGIN
   IF @iUSER_ID IS NULL
   BEGIN
      SET @iUSER_ID = SUSER_SID()
   END   

/*   
select * from person where fm like '%Стариков%'
select * from empl where pers_link=17464
select * from departments where link = 75534
select * from empl_phone where empl_link = 17209

select dbo.ku_GetEmplPostName(17151,  null)
*/

   INSERT
   INTO @tabReturn ([EMPL_LINK],
                    [FIO],
                    [POST],
                    [PHONES])
   SELECT [W].[USER_REF],
          dbo.[XA_ALLTRIM](dbo.[SD_GetEmplName]([W].[USER_REF])),
          dbo.[XA_ALLTRIM](dbo.[KU_GetEmplPostName]([W].[USER_REF],NULL)),
          dbo.[XA_ENUM_EMPL_PHONES]([W].[USER_REF],3)
   FROM dbo.[WHO_IS_WHO] [W]
   WHERE [W].[SID] = @iUSER_ID
   
   RETURN
END

GO
GRANT ALL ON dbo.[RA_GET_USER_INFO] TO PUBLIC   
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*
select * from dbo.[RA_GET_USER_INFO](null)

select * from empl where link in (17209)


select *   FROM dbo.[WHO_IS_WHO]      [W]
xd_context '%WHO_IS_WHO%'
*/
GO

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

GO


CREATE VIEW dbo.DOCUMENTS_ADD_CHILD_TABLE
AS
SELECT
	[LINK]			= SD.LINK_UP,
	SD.ORDERS,
	SD.LINK_VAC_CHILD,
	VC.LINK_EMPL,
	E.TAB,
	FIO = E.FIO,
	SD.LINK_SFIN,
	CODE_SFIN = F.CODE,
	VC.TYP_CALC,
	NAME_CALC = CASE VC.TYP_CALC WHEN 1 THEN 'без учёта дней' WHEN 2 THEN 'пропорц.раб.дн.' ELSE 'пропорц.календ.дн.' END,
	BASE_SUM = VC.SUMMA,
	SD.[DAYS],
	SD.[HOURS],
	SD.DAYS_NORM,
	SD.HOURS_NORM,
	SD.SUMMA_NEW,
	SD.SUMMA_OLD,
	SD.SUMMA,
	DATE_BEG = CONVERT(VARCHAR(10),[DATE_BEG],104),
	DATE_END = CONVERT(VARCHAR(10),[DATE_END],104),	
	SD.[REGION],
	SD.[REGSUM],
	SD.[NORTH],
	SD.[NORTHSUM],
	SUBDIV_NAME,
	POST_NAME,
	VC.LINK_PAYS,
	CODE_PAYS = P.CODE,
	NAME_PAYS = P.NAME
FROM 
	dbo.SDOC_ACHILD_TABLE SD
	INNER JOIN dbo.VAC_CHILD VC ON VC.LINK = SD.LINK_VAC_CHILD
	INNER JOIN dbo.KU_EMPL_PLACING E ON VC.LINK_EMPL = E.LINK
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = SD.LINK_SFIN
	INNER JOIN dbo.PAYS P ON P.LINK = VC.LINK_PAYS
GO

GRANT SELECT ON dbo.[DOCUMENTS_ADD_CHILD_TABLE] TO PUBLIC

GO

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

GO


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

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

BEGIN

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

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


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

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

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

RETURN

END

GO


GRANT SELECT ON dbo.[DICTIONARY_STAFF_FN] TO PUBLIC

GO

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

GO

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

BEGIN

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

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

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

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

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

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

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

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

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

		  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(16), (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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ku_EmplNormVacation]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[ku_EmplNormVacation]

GO

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

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

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


SELECT @countDate = min(date) FROM empl_vac_notused

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

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

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

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


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

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

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

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

RETURN
END



GO


GRANT SELECT ON dbo.[ku_EmplNormVacation] TO PUBLIC

GO


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


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

GO


/*
© Кейсистемс (Keysystems), 2007
Возвращает государственных гражданских служащих в учреждении @dep_link на дату @date
*/
CREATE   FUNCTION dbo.GetGSGREmplToDepAndDate(
					   @dep_link int,	-- организация
					   @date datetime, 	-- дата
					   @Sack tinyint = 0)
RETURNS TABLE
AS 
RETURN
	
SELECT	EM_PL.LINK as empl_link, 											-- ссылка на государственного служащего
	case	when day(@date) = day(PER.BIRTHDATE) and month(@date) = month(PER.BIRTHDATE)
			then dbo.ku_GetPersAge(EM_PL.PERS_LINK,@date) - 1
		else dbo.ku_GetPersAge(EM_PL.PERS_LINK,@date)
	end as age, -- возраст служащего
	dbo.ku_GetEmplExpir(EM_PL.LINK,'YEAR','GOS_NADB',@date) as expir, 						-- стаж государственной службы государственного служащего
	PER.SEX - 1  as sex, -- пол служащего
	(SELECT	count(*) FROM KU_PERS_EDUCATION WHERE PERS_LINK = EM_PL.PERS_LINK AND EDUC_CODE = 18)AS VIS_ED, 	-- колиесчтво высших образовавний государственного служащего
	(SELECT	count(*) FROM KU_PERS_EDUCATION WHERE PERS_LINK = EM_PL.PERS_LINK AND EDUC_CODE = 11)AS SR_SPEC_ED, 	-- количество средне-специальных образований государственного служащего
	(SELECT	count(*) FROM KU_PERS_EDUCATION WHERE PERS_LINK = EM_PL.PERS_LINK AND EDUC_CODE = 07)AS SR_ED, 		--количество средних образований государственного служащего
	CASE
		WHEN (SELECT CODE FROM ACAD_DEGREE WHERE LINK = PER.ACAD_DEGREE_LINK) = 1 THEN 1
		ELSE 0
	END as DOC_NAUK, 												-- наличие ученой степени доктора наук государственного служащего
	CASE
		WHEN (SELECT count(*) FROM KU_PERS_EDUCATION
		      WHERE PERS_LINK = EM_PL.PERS_LINK AND (EDUC_CODE = 11 OR EDUC_CODE = 18)) >= 2 THEN 1
		ELSE 0
	END as TWO_ED, 													-- наличие двух и более образований государственного служащего
	D_ST.KAT_GOS_CODE as kat_gs_code, 										-- код категории государственной должности государственного служащего
	D_ST.KAT_GOS_NAME as kat_gs_name, 										-- категория государственной должности государственного служащего
	D_ST.GR_GOS_CODE as gr_gs_code, 										-- код группы государственной должности государственного служащего
	D_ST.GR_GOS_NAME as gr_gs_name, 										-- группа государственной должности государственного служащего
	(SELECT TOP 1 CHIN_CODE FROM KU_EMPL_CHIN WHERE @date >= DATE AND EMPL_LINK = EM_PL.LINK ORDER BY DATE DESC)
		as kl_chin 												-- класс классного чина государственного служащего
FROM	KU_EMPL_PLACING_FN(@date) EM_PL LEFT JOIN PERSON PER
	ON EM_PL.PERS_LINK = PER.LINK LEFT JOIN DICTIONARY_STAFF_FN(@date) D_ST
	ON EM_PL.STAFF_LINK = D_ST.STAFF_LINK
WHERE	D_ST.GOSSL IN (1,2)
	AND EM_PL.DEP_LINK = @dep_link
	AND ISNULL(EM_PL.DATE_BEGIN,0) != 0
	AND (SACK = 0  
	or (SACK = (case when @Sack = 1 then 1 else 0 end ) and YEAR(DATE_SACK) = (case when @sack = 1 then year(@date) else null end)) ) 		   


GO


GRANT SELECT ON dbo.[GetGSGREmplToDepAndDate] TO PUBLIC

GO





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

GO


CREATE       VIEW [dbo].NEW_FACE
AS
SELECT im.link, o.number, o.date, o.dep_link, order_status=o.status, im.empl_link, 
	im.order_link, 
	[tab_num] = dbo.ku_GetEmplTab(im.empl_link), [fio] = dbo.ku_GetEmplFIO(im.empl_link), 
	im.staff_link, s.subdiv_link,
	[new_subdiv] = S.subdiv_name,
	[new_post] = S.post_name,
	im.num_stake, im.status, im.date_begin,
	im.date_end2, im.usl_pr, 
	[oklad] = isnull((SELECT sum(summa) FROM order_money_period WHERE isoklad=1 and item_link=im.link), 0),
	im.ets_razr,
	im.isp, im.kontr_date, im.kontr_num,
	im.active,
	case	when im.temp_link is null then 0
		else 1
	end as [temp],
	im.temp_link,
	case	when im.temp_link is null then ''
		else dbo.ku_GetEmplFIO(im.temp_link)
	end as [temp_fio],
	e.pers_link,
	im.io
FROM item_move im inner join orders o on im.order_link=o.link and im.new_face=1
inner JOIN USER_INFO UI ON (UI.CODE_TASK = 'KADRY' OR UI.DEP_LINK = O.DEP_LINK)
LEFT OUTER JOIN dictionary_staff_all S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
left join empl e on e.link = im.empl_link



GO


GRANT SELECT ON dbo.[NEW_FACE] TO PUBLIC

GO


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


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

GO


CREATE      VIEW [dbo].MOVES
AS
SELECT im.link, o.number, o.date, o.dep_link, im.empl_link,  
	im.order_link, 
	[tab_num] = dbo.ku_GetEmplTab(im.empl_link), [fio] = dbo.ku_GetEmplFIO(im.empl_link), 
	[subdiv] = dbo.ku_GetEmplSubdivName(im.empl_link, im.date_begin-1), 
	[post] = dbo.ku_GetEmplPostName(im.empl_link, im.date_begin-1),
	im.staff_link,
	[new_subdiv] = S.subdiv_name ,
	[new_post] = S.post_name ,
	im.num_stake, im.status,
	im.date_begin, im.date_end2, im.type, im.reason,
	[oklad] = isnull((SELECT sum(summa) FROM order_money_period WHERE isoklad=1 and item_link=im.link), 0),
	im.ets_razr,
	k_date = im.kontr_date, k_num = im.kontr_num,
	im.active,
	im.io
FROM item_move im inner join orders o on im.order_link=o.link and im.new_face=0
inner JOIN USER_INFO UI ON (UI.CODE_TASK = 'KADRY' OR UI.DEP_LINK = O.DEP_LINK)
LEFT OUTER JOIN dictionary_staff_all S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end


GO


GRANT SELECT ON dbo.[MOVES] TO PUBLIC

GO


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


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

GO

CREATE VIEW [dbo].[STO_W_HOURS_TABLE]  AS 
/* Тарификация в образовани. Педагогическая нагрузка1*/
SELECT 
	date_begin,
	date_end,
	link = link_wh,
	link_up = link_doc_wh,	
	DOC_NAME,
	link_empl,
	link_tar_empl,
	fio,
	tab,
	POST_NAME,
	link_pay,
	pays_name,
	link_les,
	l_name,
	t,
	link_paral,
	p_name,
	link_clas,
	c_name,	
	NORM_WEEK_HOURS = norm,
	[HOURS] = fact,
	FACT_WEEK_HOURS = convert(numeric(18,2),/*Часов в месяц*/
		(case when t = 3 then 0
		else
			(case when t = 4 and type_period = 1
				then (case when coalesce(weeks,0) > 0 then fact * 1 / weeks else 0 end)	
				else fact
			end)
		end)),
	perc,
	summa = coalesce(summa,0) * coalesce(num_stake,0),
	ETS_SUMMA= base,
	name_period = (case when t in (1,2) or (t = 4 and coalesce(type_period,0) = 2) then 'неделя' else 'месяц' end),
	/*Часовая ставка*/	
	h_rate = convert(numeric(18,2), 
			(case when t = 3 then 0
				else
					(case when 
							(case when t = 4 and type_period = 1
								then (case when coalesce(weeks,0) > 0 then fact * 1 / weeks else 0 end)	
								else fact
							end) > 0
					then 
						summa / 
							(case when t = 4 and type_period = 1
								then (case when coalesce(weeks,0) > 0 then fact * 1 / weeks else 0 end)	
								else fact
							end)
					else 0 end) * perc / 100 * COALESCE(NUM_STAKE,0)
			end)),  
	weeks,/*Кол-во недель в месяце*/
	month_hours = convert(numeric(20,2), norm * weeks),	/*Нормочасы в месяц*/
	link_ets,
	link_pkg,
	LINK_KBK = link_sfin,
	CODE_KBK = CODE_SFIN,
	SUBDIV_NAME,
	num_stake,
	OBJ_CODE,
	CODE_TYPE,
	NO_CALC,
	M_STAVKA,
	FOT
from
	dbo.sa_dict_wh_pays_empl(default,default,default,default,default)

GO


GRANT SELECT ON dbo.[STO_W_HOURS_TABLE] TO PUBLIC

GO

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

/*
© Кейсистемс (Keysystems), 2005
*/
--- Функция вычисляет объекты для налога на имущества ---
CREATE         FUNCTION dbo.CalcNalogBalanceOS (@varKSDate DATETIME = NULL, @varKSDepLink INT = NULL)
-- Если @varKSDepLink = NULL то расчет без учета DEP_LINK, т.е. для всех организаций
RETURNS @varKSOUT_TABLE TABLE
	(	[ACCOUNT] [INT],
		[GRP_CODE] [CHAR] (8) NOT NULL,
		[INV]	[INT] NOT NULL,
		[OST_SUM] [NUMERIC] (20,2) NULL,
		[BALANS] [NUMERIC] (20,2) NULL,
		[AMORT] [NUMERIC] (20,2) NULL,
		[NO_NALOG] BIT NOT NULL,
		[DATE_BEGIN] DATETIME NULL
	)
AS
BEGIN
	DECLARE @AMORT_FULL NUMERIC (28,2),
		@DATE_BEGIN	DATETIME,
		@intNOT_USE_NASTR	INT,
		@intACCOUNT	INT

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

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

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

	--- Сумма амортизации ---
	DECLARE @varDEPRE_SUM TABLE (LINK_OS INT, DEPRE_SUM [NUMERIC] (20,2))
	
	SELECT @intACCOUNT = LINK
	FROM dbo.S_ACCOUNTS WITH (NOLOCK)
	WHERE CODE = '104'
		AND ZABALANS = 0 

	INSERT @varDEPRE_SUM 
	SELECT ART.INV,
		SUM(K_SUMMA)
	FROM dbo.ARestGroupedTableByDate (@varKSDate, @intACCOUNT, DEFAULT) ART
	WHERE @varKSDepLink IS NULL
		OR ART.DEP_LINK = @varKSDepLink
	GROUP BY ART.INV, ART.ACCOUNT

	--- Балансовая стоимость ---
	SET @intACCOUNT = (SELECT LINK
			FROM dbo.S_ACCOUNTS WITH (NOLOCK)
			WHERE CODE = '101'
				AND ZABALANS = 0)

	DECLARE @TAB_BALANSE TABLE (INV INT, ACCOUNT INT,
			QTY NUMERIC (20,2), SUMMA NUMERIC (20,2))
	
	INSERT INTO @TAB_BALANSE
	SELECT ART.INV,
		ART.ACCOUNT,
		SUM(D_QUANTITY),
		SUM(D_SUMMA)
	FROM dbo.ARestGroupedTableByDate (@varKSDate, @intACCOUNT, DEFAULT) ART
	WHERE @varKSDepLink IS NULL
			OR ART.DEP_LINK = @varKSDepLink
		AND ART.INV IS NOT NULL
	GROUP BY ART.INV, ART.ACCOUNT

	--- !!!Результат!!! ---
	INSERT @varKSOUT_TABLE
	SELECT	[ACCOUNT] = ART.ACCOUNT,
		[GRP_CODE] = SA.cSinth + SA.cAnalit,

		[INV] = ISNULL (ART.INV, 0),
		[OST_SUM] = 0,
		[BALANS] = ART.SUMMA,
		[AMORT] = ISNULL (AM.DEPRE_SUM, 0),
		[NO_NALOG] = ISNULL(NO_TAX, 0),
		DATE_BEGIN = ASS.DATE_BEGIN
	FROM @TAB_BALANSE ART
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = ART.ACCOUNT)
--	INNER JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = ART.INV)
	LEFT JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = ART.INV)
	LEFT JOIN @varDEPRE_SUM AM ON (AM.LINK_OS = ART.INV)
	WHERE (@intNOT_USE_NASTR = 0
		AND ASS.DATE_BEGIN <= @varKSDate
		AND (ART.SUMMA <> 0
			AND (ART.QTY = 0 AND ART.SUMMA > @AMORT_FULL
				OR ART.QTY <> 0
					AND ABS (ART.SUMMA) > ABS (ART.QTY) * @AMORT_FULL
				))
		OR @intNOT_USE_NASTR = 1)

	UPDATE @varKSOUT_TABLE
	SET [OST_SUM] = ISNULL(BALANS, 0) - ISNULL(AMORT, 0)

	RETURN
END
GO


GRANT SELECT ON dbo.[CalcNalogBalanceOS] 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_get_ogs_code]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].rn_get_ogs_code
GO

-- получение кода ОГС по ИНН или КБП организации
--@codeOrg - ИНН или КБП
--@iType- 0 - не известно что, 1 - ИНН, 2 - КБП

CREATE FUNCTION dbo.rn_get_ogs_code  
(@cCodeOrg VARCHAR(100), @cCodeRegion varchar(100), @iType INT)

returns varchar(4000)
as
    begin
      declare @cstr varchar(1000), @cINN VARCHAR(100), @iCount int
      SET @cstr = ''
      IF EXISTS(SELECT * FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_OGS' AND CODE = @cCodeOrg)
         RETURN @cCodeOrg


      -- неизвестно что пришло, ИНН или КБП
      IF @iType = 0
         BEGIN
            set @cstr = dbo.rn_get_ogs_code(@cCodeOrg, @cCodeRegion, 1)
            IF @cstr =''
               set @cstr = dbo.rn_get_ogs_code(@cCodeOrg, @cCodeRegion, 2)
            RETURN @cstr   
         END   

      IF @iType = 1
         SELECT @cINN = @cCodeOrg

      IF @iType = 2
         BEGIN
            SELECT @cINN = INN  FROM  DEPARTMENTS WHERE CODE = @cCodeOrg
         END
      set @iCount = 0

         IF @cCodeRegion=''
			BEGIN
			   SELECT @iCount = COUNT(*) FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_OGS' AND CODE_STR = @cINN
			IF @iCount = 1	
					SELECT @cstr = CODE FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_OGS' AND CODE_STR = @cINN
			ELSE
				--попробуем найти в справочнике организаций для передачи
				SELECT @cstr = LONG_NAME FROM REPORT_KBK WHERE Code_Form = 'R_86n_SEND_ORG' AND CODE_STR = @cINN
			END	
         ELSE   
      	   IF (SELECT COUNT(*) FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_OGS' AND CODE_STR = @cINN AND ADD_INFO = @cCodeRegion) = 1	
	           SELECT @cstr = CODE FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_OGS' AND CODE_STR = @cINN AND ADD_INFO = @cCodeRegion                
			ELSE
			--попробуем найти в справочнике организаций для передачи
			SELECT @cstr = LONG_NAME FROM REPORT_KBK WHERE Code_Form = 'R_86n_SEND_ORG' AND CODE_STR = @cINN
			       
      return @cstr
    end
GO
GRANT ALL ON dbo.rn_get_ogs_code 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.[BK_DOC_TABLE_MZ_NDS_FN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[BK_DOC_TABLE_MZ_NDS_FN]

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

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

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

	TNDS_LINK	INT,
	TNDS_CODE	VARCHAR (2)
	)
AS
BEGIN
	DECLARE @intTAB_LINK	INT,
		@intFS_OBJ_LINK	INT

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

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

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

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

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

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

		SMWT.UM_LINK

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

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

	SELECT OTR.LINK,

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

		SMWT.UM_LINK

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

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

	SELECT OTR.LINK,

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

		SMWT.UM_LINK

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

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

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

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

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

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

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

		TO_NDS.LINK,
		TO_NDS.CODE
	
	FROM @TAB0 T0 
	LEFT MERGE JOIN @TAB1 T1 ON (T1.LINK_UP = T0.LINK)
--	LEFT JOIN @TAB1 T1 ON (T1.LINK_UP = T0.LINK)
	LEFT JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = T0.LINK)

	LEFT JOIN dbo.DICTIONARY_DIGIT UM ON (UM.LINK = T1.UM_LINK)
	LEFT JOIN dbo.KOSGU EKR ON (EKR.LINK = OTMS.EKR)	
--	LEFT JOIN dbo.OUT_TABLE_FIN_SOURCE OTFS ON (OTFS.LINK_UP = OTR.LINK
--		AND OTFS.OBJECT = @intFS_OBJ_LINK)
--	LEFT JOIN dbo.FIN_SOURCE FS ON (FS.LINK = OTFS.FIN_SOURCE)
	LEFT JOIN dbo.FIN_SOURCE FS ON (FS.CODE = OTMS.FIN_SOURCE)
	LEFT JOIN dbo.KL_COUNTRY KC ON (KC.LINK = OTMS.COUNTRY_LINK)
	LEFT JOIN dbo.TYPE_OPER_NDS TO_NDS ON (TO_NDS.LINK = OTMS.TYPE_NDS)
--	WHERE OTR.OBJECT = @intTAB_LINK
--		AND (@intLINK_DOC IS NULL
--			OR OTR.LINK_UP = @intLINK_DOC)


	RETURN 
END


GO


GRANT SELECT ON dbo.[BK_DOC_TABLE_MZ_NDS_FN] TO PUBLIC

GO


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


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

GO

CREATE VIEW dbo.DOC_TABLE_MZ_NDS
AS
	SELECT *
	FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (DEFAULT)
GO


GRANT SELECT ON dbo.[DOC_TABLE_MZ_NDS] TO PUBLIC

GO



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

GO
--- Счет-фактура (корректировочный) шапочная часть ---
CREATE FUNCTION dbo.BK_DOC_INVOICE_COR_FN
	(@DOC_OBJ_CODE	VARCHAR (30),
	@intDOC_LINK	INT = NULL,
	@intDEP_LINK	INT = NULL)

RETURNS @INVOICE_COR TABLE
	(LINK		INT,
	NUMBER		VARCHAR (25),
	SUMMA		NUMERIC (28,4),
	COMMENT		VARCHAR (254),
	[DATE]		DATETIME,
	DATE_PROV	DATETIME,
	FLAG_JC		TINYINT,
	DEP_LINK	INT,

	INBOOK		TINYINT,

	OSN_LINK	INT,
	OSN_NUM		VARCHAR (25),
	OSN_DATE	DATETIME,
	OSN_INFO	VARCHAR (254),

	OSN_NUM_C	VARCHAR (25),
	OSN_DATE_C	DATETIME,

	DATE_BASE	DATETIME,

	-- Продавец --
	SEL_LINK	INT,
	SEL_CODE	VARCHAR (10),
	SEL_NAME	VARCHAR (254),

	-- Покупатель --
	BUY_LINK	INT,
	BUY_CODE	VARCHAR (10),
	BUY_NAME	VARCHAR (254),
	
	COR_NUM		VARCHAR (25),
	COR_DATE	DATETIME
	)
AS
BEGIN
	DECLARE	
		@DOC_OBJ_LINK	INT,
		@DOC_LINK	INT,
		@DEP_LINK	INT,
	
		@OBJ_PAY_LINK	INT
	
	SET @DOC_OBJ_LINK = dbo.GetObjLink (@DOC_OBJ_CODE)
	
	INSERT INTO @INVOICE_COR
	SELECT 	
		G.LINK,
		G.NUMBER,
		[SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		FLAG_JC = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
		DEP_LINK	=	G.DEP,
	
		INBOOK = ISNULL (GPI_COR.INBOOK, 0),

		OSN.LINK,
		OSN.NUMBER,
		OSN.[DATE],
		CONVERT(VARCHAR (254), OSN.INFO),

		GPI.COR_NUM,
		GPI.COR_DATE,

		GPI.PAY_DATE,		

		-- Продавец --
		SEL_LINK	=	DEP1.LINK,
		SEL_CODE	=	DEP1.CODE,
		SEL_NAME	=	DEP1.[NAME],
	
		-- Покупатель --
		BUY_LINK	=	DEP2.LINK,
		BUY_CODE	=	DEP2.CODE,
		BUY_NAME	=	DEP2.[NAME],
	
		GPI_COR.COR_NUM,
		GPI_COR.COR_DATE
	
	FROM dbo.G_PROV as G WITH (NOLOCK)
	LEFT JOIN dbo.G_PROV_INVOICE_COR GPI_COR ON (GPI_COR.DOC_LINK = G.LINK)
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = GPI_COR.OSNOV)
	LEFT JOIN dbo.G_PROV_INVOICE GPI ON (GPI.DOC_LINK = OSN.DOC_LINK)
	LEFT JOIN dbo.DEPARTMENTS DEP1 ON (DEP1.LINK = GPI.SELLER)	-- Продавец  
	LEFT JOIN dbo.DEPARTMENTS DEP2 ON (DEP2.LINK = GPI.BUYER)	-- Покупатель
	WHERE G.OBJECT = @DOC_OBJ_LINK
		AND (G.LINK = @intDOC_LINK 
			OR @intDOC_LINK IS NULL )
		AND (G.DEP = @intDEP_LINK
			OR @intDEP_LINK IS NULL)
	
	RETURN 
END

GO


GRANT SELECT ON dbo.[BK_DOC_INVOICE_COR_FN] TO PUBLIC

GO


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


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

GO
CREATE VIEW dbo.DOCUMENTS_INVOICE_COR_IN
AS

	SELECT *
	FROM dbo.BK_DOC_INVOICE_COR_FN ('DOCUMENTS_INVOICE_COR_IN',
					DEFAULT,
					DEFAULT)

GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_COR_IN] TO PUBLIC

GO


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


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

GO
CREATE VIEW dbo.DOCUMENTS_INVOICE_COR_OUT
AS

	SELECT *
	FROM dbo.BK_DOC_INVOICE_COR_FN ('DOCUMENTS_INVOICE_COR_OUT',
					DEFAULT,
					DEFAULT)


GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_COR_OUT] TO PUBLIC

GO


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


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

GO
--- Счет-фактура шапочная часть ---
CREATE FUNCTION dbo.BK_DOC_INVOICE_FN
	(@DOC_OBJ_CODE	VARCHAR (30),
	@intDOC_LINK	INT = NULL,
	@intDEP_LINK	INT = NULL)

RETURNS @INVOICE TABLE
	(LINK		INT,
	NUMBER		VARCHAR (25),
	SUMMA		NUMERIC (28,4),
	COMMENT		VARCHAR (254),
	[DATE]		DATETIME,
	DATE_PROV	DATETIME,
	FLAG_JC		TINYINT,
	DEP_LINK	INT,

	INBOOK		BIT,

	-- Продавец --
	SEL_LINK	INT,
	SEL_CODE	VARCHAR (10),
	SEL_NAME	VARCHAR (254),

	-- Покупатель --
	BUY_LINK	INT,
	BUY_CODE	VARCHAR (10),
	BUY_NAME	VARCHAR (254),
	
	-- Грузоотправитель --
	CONS1_LINK	INT,
	CONS1_CODE	VARCHAR (10),
	CONS1_NAME	VARCHAR (254),

	-- Грузополучатель --
	CONS2_LINK	INT,
	CONS2_CODE	VARCHAR (10),
	CONS2_NAME	VARCHAR (254),

	-- Производитель --
	PROD_LINK	INT,
	PROD_CODE	VARCHAR (10),
	PROD_NAME	VARCHAR (254),

	OSNOV		INT,
	DOG_LINK	INT,
	DOG_CODE	VARCHAR (30),

	NALOG_DOC	NUMERIC(13,2),

	NUM_BASE	VARCHAR(10),
	DATE_BASE	DATETIME,

	PAYS_LINK	INT,

	CONS1_SELF	BIT,	-- Продавец - грузоотправитель
	CONS2_SELF	BIT,	-- Покупатель - грузополучатель

	TAX_RATE	NUMERIC(5,2),

	COR_NUM		VARCHAR (25),
	COR_DATE	DATETIME
	)
AS
BEGIN
	DECLARE	
		@DOC_OBJ_LINK	INT,
		@DOC_LINK	INT,
		@DEP_LINK	INT,
	
		@OBJ_PAY_LINK	INT
	
	SET @DOC_OBJ_LINK = dbo.GetObjLink (@DOC_OBJ_CODE)
	
	IF @DOC_OBJ_CODE = 'DOCUMENTS_INVOICE_ISSUED'
		SET @OBJ_PAY_LINK = dbo.GetObjLink ('PAYS_LINK_ISSUED')
	
	IF @DOC_OBJ_CODE = 'DOCUMENTS_INVOICE_RECEIVED'
		SET @OBJ_PAY_LINK = dbo.GetObjLink ('PAYS_LINK_RECEIVED')
	
	INSERT INTO @INVOICE
	SELECT 	
		G.LINK,
		G.NUMBER,
		[SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		FLAG_JC = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
		DEP_LINK	=	G.DEP,
	
		INBOOK = CONVERT(BIT, ISNULL (GPI.INBOOK, 0)),
		
		-- Продавец --
		SEL_LINK	=	DEP1.LINK,
		SEL_CODE	=	DEP1.CODE,
		SEL_NAME	=	DEP1.[NAME],
	
		-- Покупатель --
		BUY_LINK	=	DEP2.LINK,
		BUY_CODE	=	DEP2.CODE,
		BUY_NAME	=	DEP2.[NAME],
		
		-- Грузоотправитель --
		CONS1_LINK	=	DEP3.LINK,
		CONS1_CODE	=	DEP3.CODE,
		CONS1_NAME	=	DEP3.[NAME],
	
		-- Грузополучатель --
		CONS2_LINK	=	DEP4.LINK,
		CONS2_CODE	=	DEP4.CODE,
		CONS2_NAME	=	DEP4.[NAME],
	
		-- Производитель --
		PROD_LINK	=	DEP5.LINK,
		PROD_CODE	=	DEP5.CODE,
		PROD_NAME	=	DEP5.[NAME],
	
		[OSNOV] = OSN.LINK, 
		[DOG_LINK]= OSN.DOC_LINK,
		[DOG_CODE]= OSN.NUMBER,
	
		[NALOG_DOC] = CONVERT(NUMERIC(13,2), GPI.TAX_SUM),
	
		[NUM_BASE] = CONVERT (VARCHAR(6), GPI.PAY_NUM),
		[DATE_BASE] = GPI.PAY_DATE,
	
		[PAYS_LINK]  =	GPR.DOC_REF_FOREIGN, 
	
		[CONS1_SELF] = CONVERT(BIT, GPI.SEL_SHIP),	-- Продавец - грузоотправитель
		[CONS2_SELF] = CONVERT(BIT, GPI.BUY_RECIVE),	-- Покупатель - грузополучатель
	
		[TAX_RATE] = CONVERT(NUMERIC(4,2), GPI.TAX_RATE),
	
		GPI.COR_NUM,
		GPI.COR_DATE
	
	FROM dbo.G_PROV as G WITH (NOLOCK)
	LEFT JOIN dbo.G_PROV_INVOICE GPI ON (GPI.DOC_LINK = G.LINK)
	LEFT JOIN dbo.DEPARTMENTS DEP1 ON (DEP1.LINK = GPI.SELLER)	-- Продавец  
	LEFT JOIN dbo.DEPARTMENTS DEP2 ON (DEP2.LINK = GPI.BUYER)	-- Покупатель
	LEFT JOIN dbo.DEPARTMENTS DEP3 ON (DEP3.LINK = GPI.SHIPPER)	-- Грузоотправитель  
	LEFT JOIN dbo.DEPARTMENTS DEP4 ON (DEP4.LINK = GPI.RECEIVER)	-- Грузополучатель 
	LEFT JOIN dbo.DEPARTMENTS DEP5 ON (DEP5.LINK = GPI.PRODUCER)	-- Производитель  
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = GPI.OSNOV)
	LEFT JOIN dbo.G_PROV_REF GPR ON (GPR.DOC_REF_PRIMARY = G.LINK
					AND GPR.OBJECT = @OBJ_PAY_LINK)
	WHERE G.OBJECT = @DOC_OBJ_LINK
		AND (G.LINK = @intDOC_LINK
			OR @intDOC_LINK IS NULL )
		AND (G.DEP = @intDEP_LINK
			OR @intDEP_LINK IS NULL)
	
	RETURN 
END



GO


GRANT SELECT ON dbo.[BK_DOC_INVOICE_FN] TO PUBLIC

GO


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


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

GO


CREATE VIEW  dbo.DOCUMENTS_INVOICE_ISSUED
AS
	SELECT *,
		INBOOK AS BOOK_SALES 
	FROM dbo.BK_DOC_INVOICE_FN ('DOCUMENTS_INVOICE_ISSUED',
					DEFAULT,
					DEFAULT)
GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_ISSUED] TO PUBLIC

GO


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


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

GO

CREATE VIEW dbo.DOCUMENTS_INVOICE_RECEIVED
AS
	SELECT *,
		INBOOK AS BOOK_PUR 
	FROM dbo.BK_DOC_INVOICE_FN ('DOCUMENTS_INVOICE_RECEIVED',
					DEFAULT,
					DEFAULT)
GO


GRANT SELECT ON dbo.[DOCUMENTS_INVOICE_RECEIVED] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_177]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @vcExec VARCHAR(8000)
SET NOCOUNT ON

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
   SET @vcExec = '
   DECLARE @iORDERS INT
   SELECT @iORDERS = [ORDERS]
   FROM #FileExportReport
   WHERE [TXT] = ''ТБ=02''

  /* IF @iORDERS > 0
   BEGIN
      DELETE
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDERS - 2 AND @iORDERS + 1
   END*/

   SELECT @iORDERS = [ORDERS]
   FROM #FileExportReport
   WHERE [TXT] = ''ТБ=03''

   IF @iORDERS > 0
   BEGIN
      DELETE
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDERS - 2 AND @iORDERS + 1
   END

   SELECT @iORDERS = [ORDERS]
   FROM #FileExportReport
   WHERE [TXT] = ''ТБ=04''

   IF @iORDERS > 0
   BEGIN
      DELETE
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDERS - 2 AND @iORDERS + 1
   END

   SELECT @iORDERS = [ORDERS]
   FROM #FileExportReport
   WHERE [TXT] = ''ТБ=05''

   IF @iORDERS > 0
   BEGIN
      DELETE
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDERS - 2 AND @iORDERS + 1
   END'

   EXEC(@vcExec)

END



GO
GRANT ALL ON dbo.RA_EXPORT_FORM_177 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_kbk where code= 'send'

select * from report_kbk where link_self in (168972,210085)
sp_helptext ra_script_send

select *
FROM dbo.[REPORT_KBK]
WHERE [CODE_FORM] = 'SEND'

exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].SD_N_CHILD_PROV
@varKSparLINK int
AS
DECLARE  @varKSovDOCUMENTS_ADD_SUMMA int


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

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

Declare @varKStrancount int

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

EXEC SALARY_SDOC_FLAG_JC @varKSparLINK,0

INSERT INTO CALCULATE_JURNAL (LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,LINK_VKR,LINK_EKR)
SELECT 
		[LINK_EMPL] = TAB.LINK_EMPL,
		[LINK_PAYS] = TAB.LINK_PAYS,
		[LINK_DOC] = DOC.LINK,
		[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = TAB.[DAYS],
		[HOURS] = TAB.[HOURS],
		[SUMMA_BASE] = TAB.BASE_SUM,
		[SUMMA] = TAB.SUMMA,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = TAB.DATE_BEG, 
		[DATE_END] = TAB.DATE_END, 
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = TAB.LINK_SFIN,
		[LINK_EKR] = P.LINK_EKR
FROM 
	dbo.SDOC DOC 
	INNER JOIN dbo.DOCUMENTS_ADD_CHILD_TABLE TAB on DOC.LINK = TAB.LINK
	INNER JOIN dbo.PAYS P ON P.LINK = TAB.LINK_PAYS
	INNER JOIN dbo.USER_INFO UI ON 1=1
WHERE 
	UI.SID = SUSER_SID() AND DOC.LINK = @varKSparLINK  and TAB.Summa<>0

--Районные
INSERT INTO CALCULATE_JURNAL (LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,PROCENT,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,LINK_VKR,LINK_EKR)
SELECT [LINK_EMPL] = TAB.LINK_EMPL,
		[LINK_PAYS] = DOC.LINK_PAY1,
		[LINK_DOC] = DOC.LINK,
		[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = TAB.DAYS,
		[HOURS] = TAB.HOURS,
		[SUMMA_BASE] = TAB.SUMMA,
		[PERC] = TAB.REGION,
		[SUMMA] = TAB.REGSUM,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = TAB.DATE_BEG, 
		[DATE_END] = TAB.DATE_END, 
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = TAB.LINK_SFIN,
		[LINK_EKR] = P.LINK_EKR
FROM 
	dbo.DOCUMENTS_ADD_CHILD DOC 
	inner join dbo.DOCUMENTS_ADD_CHILD_TABLE TAB on DOC.LINK = TAB.LINK
	INNER JOIN DBO.PAYS P ON P.LINK = DOC.LINK_PAY1, USER_INFO UI
WHERE 
	UI.SID = SUSER_SID() 
	AND
	DOC.LINK_PAY1 IS NOT NULL
	AND
	DOC.LINK = @varKSparLINK  and TAB.REGSUM <> 0

-- Северные
INSERT INTO CALCULATE_JURNAL (LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,PROCENT,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,LINK_VKR,LINK_EKR)
SELECT [LINK_EMPL] = TAB.LINK_EMPL,
		[LINK_PAYS] = DOC.LINK_PAY2,
		[LINK_DOC] = DOC.LINK,
		[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = TAB.DAYS,
		[HOURS] = TAB.HOURS,
		[SUMMA_BASE] = TAB.SUMMA,
		[PERC] = TAB.NORTH,
		[SUMMA] = TAB.NORTHSUM,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = TAB.DATE_BEG, 
		[DATE_END] = TAB.DATE_END, 
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = TAB.LINK_SFIN,
		[LINK_EKR] = P.LINK_EKR
FROM 
	dbo.DOCUMENTS_ADD_CHILD DOC inner join dbo.DOCUMENTS_ADD_CHILD_TABLE TAB on DOC.LINK = TAB.LINK
	INNER JOIN DBO.PAYS P ON P.LINK = DOC.LINK_PAY2, USER_INFO UI
WHERE 
	UI.SID = SUSER_SID() 
	AND
	DOC.LINK_PAY2 IS NOT NULL
	AND
	DOC.LINK = @varKSparLINK  and TAB.NORTHSUM <> 0

EXEC SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GRANT  EXECUTE  ON [dbo].[SD_N_CHILD_PROV]  TO [public]


GO


GRANT EXECUTE ON dbo.[SD_N_CHILD_PROV] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RB_CALC_0503725G_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RB_CALC_0503725G_NEW]
GO

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

CREATE PROCEDURE dbo.RB_CALC_0503725G_NEW @iLSF int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						DEP_CODE varchar(10), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 DEP_CODE varchar(10), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9), 
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(20))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)


select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
--select  @iLinkCalcForm
if @iLinkCalcForm is null 
	RETURN 0

set @iLinkColDt = (select RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = 1 and RC.Export_Order = 3)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)


-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/

--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)

---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			DEP_CODE = isnull(D.CODE, ''), 
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	FROM dbo.G_PROV G
	INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and SO.CODE = 'NOTICE_LINK_DEP_RECEIVER'), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
			
			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			DEP_CODE = isnull(D.CODE, ''), 
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME, DEP_CODE, ACC_CODE, summa_db, summa_kr, KORR_ACC, D_ND)
select DEP_NAME, DEP_CODE, ACC_CODE, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME, DEP_CODE, ACC_CODE, KORR_ACC, D_ND
union
select DEP_NAME,DEP_CODE, ACC_CODE, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME, DEP_CODE, ACC_CODE, KORR_ACC, D_ND



	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(DEP_CODE)+'000000000',8) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = DEP_CODE, -- 
	[COL3] = SUMMA_DB, -- сумма дебет
	[COL4] = SUMMA_KR, -- сумма кредит
	[COL11] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL12] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL13] = LEFT(RTRIM(DEP_CODE)+'00000000',8) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8) -- Код строки.
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP



GO
GRANT EXECUTE ON dbo.[RB_CALC_0503725G_NEW] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
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,
	@PERCENT	numeric(15,2) = 0.0,
	@SUMMA_YEAR	numeric(15,2) = 0.0,
	@SUMMA_OLD	numeric(15,2) = 0.0,
	@LinkVKR	int,
	@LinkEKR	int
AS
DECLARE @ERROR	tinyint, @trancount	int, @soObject int, @SQLError int


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

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]) 
VALUES (@LINK, @soObject, @ORDERS, @PERS_LINK, @LinkPay, @SummaBase, @Summa, @LinkDog, @LinkVKR, @LinkEKR, @SUMMA_YEAR, @SUMMA_OLD, @BASE_YEAR, @PERCENT)

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].[BS_GET_KASSA_MAX_NUMBER]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BS_GET_KASSA_MAX_NUMBER]
GO



--Определяет номер следующего кассового документа в текущем году. 
CREATE      PROCEDURE dbo.BS_GET_KASSA_MAX_NUMBER
	@strObject 	varchar(30),
	@strCodeValue	CHAR(30) OUTPUT,
	@intDEP_LINK	INT = NULL
AS
declare @varKSLink as int,
	@varKSCountList as int,
	@varKSCountList_G as int,
	@varKSCountList_F as int,
	@intMODE_PAGE_COUNT int,

	@strCodeValue_G	CHAR(30),
	@strCodeValue_F	CHAR(30),

	@intNastrDocNumZB	INT,
	@intNastrDocNumPeriod	INT


SET @strCodeValue = '1'

SELECT @strCodeValue_G = REPLACE (SPACE (29) + '1', SPACE (1), '0'), 
	@strCodeValue_F = REPLACE (SPACE (29) + '1', SPACE (1), '0') 

SELECT @intMODE_PAGE_COUNT = dbo.XK_GET_NASTR_INT ('XK_NASTR_BOOK_KASSA_UNION_PAGE')
SELECT @intMODE_PAGE_COUNT = ISNULL (@intMODE_PAGE_COUNT, 0)

-- Проверка настроек нумерации -- 
SET @intNastrDocNumZB = ISNULL (dbo.XK_GET_NASTR_INT ('XK_NASTR_DOC_NUMBER_ZB'), 0)
IF @intNastrDocNumZB = 1 AND EXISTS (SELECT * FROM dbo.S_OBJECTS SO, dbo.DOC_NASTR NASTR 
					WHERE SO.CODE = @strObject
						AND NASTR.LINK = SO.LINK
						AND NASTR.AN_ORG = 0)
	SET @intDep_Link = NULL

SET @intNastrDocNumPeriod = ISNULL (dbo.XK_GET_NASTR_INT ('XK_NASTR_DOC_NUM_PERIOD'), 1)
IF @intNastrDocNumPeriod = 0 
	select @intNastrDocNumPeriod = ISNULL(AN_PERIOD, 1)
	from dbo.XD_DOC_NASTR 
	where CODE = @strObject 

SELECT top 1 @varKSLink = g.link
FROM dbo.S_OBJECTS SO, dbo.G_PROV G, dbo.USER_INFO UI
WHERE (@intMODE_PAGE_COUNT = 1 AND SO.CODE IN ('KASSA_BOOK_GENERAL', 'KASSA_BOOK_F')
		OR @intMODE_PAGE_COUNT = 0 AND SO.CODE = @strObject)
	AND G.OBJECT = SO.LINK AND YEAR(G.DATE) = YEAR(UI.WORKDATE)
	AND (@intDEP_LINK IS NULL OR G.DEP = @intDEP_LINK)
order by (REPLACE(SPACE(30-len(RTRIM(G.NUMBER)))+RTRIM(G.NUMBER), ' ','0')) DESC

SELECT @varKSCountList_G = 0,
	@varKSCountList_F = 0

IF @varKSLink is not null 
BEGIN 
	IF @strObject = 'KASSA_BOOK_GENERAL'
		OR @intMODE_PAGE_COUNT = 1
	BEGIN 
   		SELECT @strCodeValue_G = REPLACE(SPACE(30-len(RTRIM(G.NUMBER)))+RTRIM(G.NUMBER), ' ','0'), 
			@varKSCountList_G = g.ListCount 
		FROM dbo.KASSA_BOOK_GENERAL G
		WHERE G.LINK = @varKSLink
	END

	IF @strObject = 'KASSA_BOOK_F'
		OR @intMODE_PAGE_COUNT = 1
	BEGIN
		SELECT @strCodeValue_F = REPLACE(SPACE(30-len(RTRIM(G.NUMBER)))+RTRIM(G.NUMBER), ' ','0'), 
			@varKSCountList_F = g.ListCount 
		FROM dbo.KASSA_BOOK_F G
		WHERE g.link = @varKSLink
	END

	SELECT @varKSCountList	= ISNULL (@varKSCountList_G, 0) + ISNULL (@varKSCountList_F, 0)
	SELECT @strCodeValue = CASE WHEN @strCodeValue_G > @strCodeValue_F THEN @strCodeValue_G ELSE @strCodeValue_F END

	IF ISNUMERIC(@strCodeValue) = 1 and @varKSCountList IS NOT NULL
		BEGIN
			SET @strCodeValue = rtrim ( ltrim( STR (convert (numeric (30), @strCodeValue) + @varKSCountList)))
		END
	ELSE
		BEGIN 
			SELECT @strCodeValue = NUMBER 
			FROM dbo.G_PROV
			WHERE LINK = @varKSLink
		END
END

RETURN 0
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.RO_WEB_VR_USER_2011_EDIT
	@cObject varchar(30),
	@varKSnLink int
AS
BEGIN
	DECLARE @cSQL varchar(1000), @cTitle varchar(100)

	EXEC x_get_prop @cObject, 'TITLE', @cTitle OUTPUT

	SELECT [alias] = @cObject,
		[order] = 1,
		[tab_name] = @cTitle,
		[link_table] = 0,
		[table_type] = 2
	FROM s_objects
	WHERE code=@cObject

   declare @Link_Tree int
   select @Link_Tree = T.link
   from dbo.report_svod_tree T join dbo.user_form_access U on T.link_report_org = U.dep_link and isnull(T.link_report_budg, 0) = isnull(U.budg_link, 0) and U.sid = suser_sid()
   where isnull(link_self, 0) = 0

   if @Link_Tree is NULL
      select @Link_Tree = T.link
      from dbo.report_svod_tree T join dbo.user_form_access U on T.link_report_org = U.dep_link and isnull(T.link_report_budg, 0) = isnull(U.budg_link, 0) and u.sid = suser_sid()
      where not exists(select top 1 * from dbo.report_svod_tree T1 join dbo.user_form_access U1 on T1.link_report_org = U1.dep_link and isnull(T1.link_report_budg, 0) = isnull(U1.budg_link, 0) and u1.sid = suser_sid()
                        where T.link_self = T1.link)

   select Link, Code, @Link_Tree as Link_Tree,
         Name = dbo.RO_KBK_FOR_ORG(@Link_Tree, link, 1, Name),
         Long_Name = dbo.RO_KBK_FOR_ORG(@Link_Tree, link, 2, Long_Name)
   from dbo.REPORT_KBK
   where Code_Form = 'ВР_2011_USER' and Link = @varKSnLink


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_ANALYZE]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_ANALYZE]
END
GO

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

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

*******************************************************************************/
-- Процедура анализа импортируемой формы (получения ее параметров).
-- Вход: таблица #IMPORT_TABLE с загруженными данными формы.
-- Коды ошибок
-- -1  - Неправильный формат даты				
-- -2  - Отсутствует раздел кода вида бюджета (ВБ или ВИД)   
-- -3  - Отсутствует раздел кода бюджетополучателя (БП, КБП или ИСТ)
-- -4  - Отсутствует раздел периодичности формы (ПРД)
-- -5  - Неправильная дата. Число должно быть 01
-- -6  - Неправильная дата. Месяц квартальной формы должен быть 01,04,07 или 10
-- -7  - Неправильная дата. Неправильная дата. Месяц для годовой формы должен быть 01
-- -9  - Организации с таким кодом бюджетополучателя не существует
-- -10 - В отчете отсутствует код бюджета
-- -11 - Выгружаемый код бюджета не уникален
-- -12 - Выгружаемый код бюджета не найден
-- -13 - Ошибка в dbo.[RA_IMPORT_FORM_GET_LINK_FORM]
-- -14 - Неверное значение в разделе периодичности формы (ПРД)
-- -15 - Неуникальный КБП в базе данных
-- -16 - Отсутствует лицензия на использование Свод-EXCEL.
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_ANALYZE]
   @iLINK_SAVED_FORM INT OUTPUT, -- Возвращаемая ссылка на REPORT_IMPORT_SAVED_FORMS, с результатами анализа.   
   @iLINK_SELF       INT = NULL,
   @vcFILENAME       VARCHAR(500) = NULL,
   @tMode            TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
WITH ENCRYPTION
AS
SET NOCOUNT ON
PRINT 'dbo.[RA_IMPORT_FORM_ANALYZE]'

DECLARE @i            INT,        
        @vcTXT        VARCHAR(1000), 
        @bIsEmptyVB   BIT,
        @bRA          BIT,
        @bRD          BIT,
        @bVF0         BIT,
        @bVF1         BIT,
        @bVF2         BIT,
        @bEnd         BIT,
        @iRightLen    INT,
        @vcAtr        VARCHAR(8000),
        @vcAtrValue   VARCHAR(8000),
        @vcCODE_TASK  VARCHAR(50),
        @vcKSBU       VARCHAR(8000),
        @vcPRP        VARCHAR(8000),

     	  @vcKBP        VARCHAR(100),
        @vcTmp        VARCHAR(8000),
        @vcVB         VARCHAR(10),
        @dDT          DATETIME,
        @tPRD         TINYINT,        
        @cCODE_FORM   CHAR(20),
        @vcSOFT       VARCHAR(500),
        @tTABLE_ORDER TINYINT,
        @iLINK_FORM   INT,
        @iError       INT,
        @tPERIODIC    TINYINT,
        @vcDB_NAME    VARCHAR(100),
        @vcSUB_CONFIG VARCHAR(100),
        @bIsXML       BIT,
        @bIs1C        BIT,
        @vcUK         VARCHAR(50),
        @cDate        VARCHAR(10), 
        @iXML_DOC_HANDLE INT,
		  @iLinkTree		int,
		  @lvcLINK_SAVED_FORM varchar(50),
		  @dDT_DAY DATETIME

EXEC dbo.[RA_ERRORS_LOG_CLEAR] @@PROCID

SELECT @bVF0   = 0,
       @bVF1   = 0,
       @bVF2   = 0,
       @bRA    = 0,
       @bRD    = 0,
       @bEnd   = 0,
       @bIsXML  = CASE  
                     WHEN EXISTS(SELECT *
                                 FROM #IMPORT_TABLE
                                 WHERE LEFT([TXT],5)='<?xml') OR
                          EXISTS(SELECT *
                                 FROM #IMPORT_TABLE
                                 WHERE SUBSTRING([TXT],2,5)='<?xml') THEN 1
                     ELSE 0
                  END,
       @bIs1C = CASE  
                     WHEN EXISTS(SELECT *
                                 FROM #IMPORT_TABLE
                                 WHERE UPPER([TXT])='ТИПФОРМ=1С:СВОДОТЧЕТОВ') THEN 1
                     ELSE 0
                  END

-- Создание записи в кэше импортируемых форм.

INSERT dbo.[REPORT_IMPORT_SAVED_FORMS](CODE_FORM) VALUES(DEFAULT)
SET @iLINK_SAVED_FORM = @@IDENTITY

UPDATE dbo.[REPORT_IMPORT_SAVED_FORMS]
SET [LINK_SELF] = ISNULL(@iLINK_SELF,@iLINK_SAVED_FORM)
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

IF @bIsXML = 1
BEGIN   
   EXEC dbo.[RA_IMPORT_FORM_ANALYZE_XML] @cCODE_FORM      OUTPUT,
                                         @vcKBP           OUTPUT,
                                         @vcVB            OUTPUT,
                                         @dDT             OUTPUT,
                                         @vcSOFT          OUTPUT,
                                         @bVF0            OUTPUT,
                                         @iXML_DOC_HANDLE OUTPUT

   EXEC sp_xml_removedocument @iXML_DOC_HANDLE
END
ELSE BEGIN
   IF @bIs1C = 1
   BEGIN
      EXEC dbo.[RA_IMPORT_FORM_ANALYZE_1C] @cCODE_FORM OUTPUT,
                                           @vcKBP      OUTPUT,
                                           @vcVB       OUTPUT,
                                           @dDT        OUTPUT,
                                           @vcSOFT     OUTPUT,
                                           @bVF0       OUTPUT,
                                           @tPRD       OUTPUT
   END
   ELSE BEGIN      
      IF EXISTS(SELECT TOP 1 * FROM #IMPORT_TABLE WHERE TXT LIKE 'IVBK_M|%')
      BEGIN
         EXEC dbo.[RO_IMPORT_FORM_ANALYZE_0503815] @cCODE_FORM OUTPUT,
                                           @vcKBP      OUTPUT,
                                           @vcVB       OUTPUT,
                                           @dDT        OUTPUT,
                                           @vcSOFT     OUTPUT,
                                           @bVF0       OUTPUT,
                                           @tPRD       OUTPUT

      END
      ELSE BEGIN
         IF LEFT(dbo.[RA_GETWORDNUM](@vcFILENAME,2,'.'),2) = 'PW'
         BEGIN
            SELECT @bVF0=0,
                   @cCODE_FORM = '0503151'

            SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],7,'|')),104)
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='PW|' AND 
	               ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],7,'|'))) = 1

  		      SELECT TOP 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
            FROM #IMPORT_TABLE
 	         WHERE LEFT([TXT],3) IN ('TO|')

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = ISNULL([KBP],'')      
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'
            END

            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = ISNULL([VB],'')
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'
            END

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = [VAL_STR]
               FROM dbo.[REPORT_OPTIONS] 
               WHERE [RAZDEL] = 'FORM_151' AND
                     [CODE] = 'IMPORT_KBP_151'
		      END

            IF @vcVB IS NULL 
            BEGIN
			      SELECT @vcVB = [VAL_STR]
			      FROM dbo.[REPORT_OPTIONS] 
			      WHERE [RAZDEL] = 'FORM_151' AND
 			            [CODE] = 'IMPORT_VB_151'
		      END

            SELECT @vcSOFT = LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) + ' ' + LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],4,'|')))
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='FK|' 
         END

         IF LEFT(dbo.[RA_GETWORDNUM](@vcFILENAME,2,'.'),2) = 'BO'
         BEGIN
            SELECT @bVF0=0,
                   @cCODE_FORM = '0503154G'

            SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|')),104)
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='BO|' AND 
	               ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) = 1

		      SELECT TOP 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
		      FROM #IMPORT_TABLE
		      WHERE LEFT([TXT],3) IN ('TO|')

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = ISNULL([KBP],'')      
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'
            END

            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = ISNULL([VB],'')
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'
            END

            IF @vcKBP IS NULL
            BEGIN
			      SELECT @vcKBP = [VAL_STR]
			      FROM dbo.[REPORT_OPTIONS] 
			      WHERE [RAZDEL] = 'FORM_151' AND
				         [CODE] = 'IMPORT_KBP_151'
		      END

            IF @vcVB IS NULL 
            BEGIN
     	         SELECT @vcVB = [VAL_STR]
			      FROM dbo.[REPORT_OPTIONS] 
			      WHERE [RAZDEL] = 'FORM_151' AND
				         [CODE] = 'IMPORT_VB_151'
		      END

            SELECT @vcSOFT = LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) + ' ' + LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],4,'|')))
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='FK|' 
         END

         IF LEFT(dbo.[RA_GETWORDNUM](@vcFILENAME,2,'.'),2) = 'OS'
         BEGIN
            SELECT @bVF0=0,
                   @cCODE_FORM = '0503155G'

            SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|')),104)
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='OS|' AND 
	               ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) = 1

		      SELECT top 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
  		      FROM #IMPORT_TABLE
		      WHERE LEFT([TXT],3) IN ('TO|')

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = ISNULL([KBP],'')      
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'

            END

            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = ISNULL([VB],'')
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503151'
            END

            IF @vcKBP IS NULL
            BEGIN
			      SELECT @vcKBP = [VAL_STR]
			      FROM dbo.[REPORT_OPTIONS] 
			      WHERE [RAZDEL] = 'FORM_151' AND
				         [CODE] = 'IMPORT_KBP_151'
		      END

            IF @vcVB IS NULL 
            BEGIN
			      SELECT @vcVB = [VAL_STR]
			      FROM dbo.[REPORT_OPTIONS] 
			      WHERE [RAZDEL] = 'FORM_151' AND
				         [CODE] = 'IMPORT_VB_151'
		      END

            SELECT @vcSOFT = LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) + ' ' + LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],4,'|')))
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3)='FK|' 
         END

         IF @vcFILENAME LIKE '%622%' 
--         AND 
--             SUBSTRING(@vcFILENAME,6,1) in ('o','r')) 
OR
            (SUBSTRING(@vcFILENAME,3,4)='660z')
         BEGIN   
            SELECT @vcKBP = REPLACE(REPLACE(REPLACE([TXT], 'KБП=', ''), 'ИСТ=', ''), 'KБ=', '')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
                  LEFT([TXT],3) IN ('KБ=')

            SELECT @vcVB = REPLACE(REPLACE([TXT], 'ВИД=', ''), 'ВБ=', '')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

            SELECT @vcUK = REPLACE([TXT],'УК=','')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3) IN ('УК=')

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = ISNULL([KBP],'')      
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503152'
            END

            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = ISNULL([VB],'')
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503152'
            END
      
            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = [VAL_STR]
               FROM dbo.[REPORT_OPTIONS] 
               WHERE [RAZDEL] = 'FORM_152' AND
                     [CODE] = 'IMPORT_KBP_152'
            END
         
            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = [VAL_STR]
               FROM dbo.[REPORT_OPTIONS] 
               WHERE [RAZDEL] = 'FORM_152' AND
                     [CODE] = 'IMPORT_VB_152'
            END
         END

         IF RTRIM(@vcFILENAME) LIKE '%155%.txt'
            OR RTRIM(@vcFILENAME) LIKE '%154%.txt'
         BEGIN   
            SELECT @vcKBP = REPLACE(REPLACE(REPLACE([TXT], 'KБП=', ''), 'ИСТ=', ''), 'KБ=', '')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
                  LEFT([TXT],3) IN ('KБ=')

            SELECT @vcVB = REPLACE(REPLACE([TXT], 'ВИД=', ''), 'ВБ=', '')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

            SELECT @vcUK = REPLACE([TXT],'УК=','')
            FROM #IMPORT_TABLE
            WHERE LEFT([TXT],3) IN ('УК=')

            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = ISNULL([KBP],'')      
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503155'
            END

            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = ISNULL([VB],'')
               FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
               WHERE [UK] = @vcUK and form_code = '0503155'
            END
      
            IF @vcKBP IS NULL
            BEGIN
               SELECT @vcKBP = [VAL_STR]
               FROM dbo.[REPORT_OPTIONS] 
               WHERE [RAZDEL] = 'FORM_155' AND
                     [CODE] = 'IMPORT_KBP_155'
            END
         
            IF @vcVB IS NULL 
            BEGIN
               SELECT @vcVB = [VAL_STR]
               FROM dbo.[REPORT_OPTIONS] 
               WHERE [RAZDEL] = 'FORM_155' AND
                     [CODE] = 'IMPORT_VB_155'
            END
         END         

         DECLARE curIMPORT_TABLE CURSOR LOCAL FORWARD_ONLY STATIC	FOR 
            SELECT [TXT] = RTRIM([TXT])
            FROM #IMPORT_TABLE
            ORDER BY [ORDER]

         OPEN curIMPORT_TABLE

         FETCH NEXT
         FROM curIMPORT_TABLE
         INTO @vcTXT

         WHILE @@FETCH_STATUS = 0 AND 
               @bEnd = 0
         BEGIN
            -- Определение кода формы 
            IF LEFT(@vcTXT, 14) = 'FK|TXSD090101|'
		         BEGIN
			         SET @cCODE_FORM = '0531467'
   			      
			         SELECT TOP 1 @vcKBP = B.BUDG, @vcVB = C.OUTCODE FROM dbo.REPORT_SVOD_TREE A
   	            INNER JOIN dbo.departments B ON A.LINK_REPORT_ORG = B.LINK
                  INNER JOIN dbo.kl_budg_type C ON A.LINK_REPORT_BUDG = C.Link
                  WHERE B.BUDG <> '' AND C.OUTCODE <> ''
   			      
                  SET @tPRD = 4 
                  SELECT @cDate = dbo.RA_GETWORDNUM([TXT], 3, '|') FROM #IMPORT_TABLE WHERE LEFT([TXT],3)='SD|'
                  -- Первый день след. месяца
                  IF PATINDEX('__.__.____', @cDate) > 0
	                  BEGIN
                        SELECT @i = 104
                        SET @dDT_DAY = CONVERT(DATETIME, @cDate, @i)
                        SET @dDT =  dateadd(month,1,dateadd(day,1-day(@dDT_DAY),@dDT_DAY))
	                  END
                     
                  SELECT @vcSOFT = LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))) + ' ' + LTRIM(RTRIM(dbo.[RA_GETWORDNUM]([TXT],4,'|')))
                  FROM #IMPORT_TABLE
                  WHERE LEFT([TXT],3)='FK|' 
                
		         END

	         IF @bRD = 1 AND @vcTXT <> '#$'
	         BEGIN
			   IF @cCODE_FORM IN ('214','217','224','234','227','228','237','238','263','264','277','280','284','429','484', '117')
               BEGIN 
			         SELECT @i = CASE 
					    	            WHEN @cCODE_FORM	IN ('429','263','280', 264) THEN 1
						    	         ELSE 2							
					               END,
					          @vcAtr = CASE 
					    			           WHEN @cCODE_FORM	IN ('429') THEN 'REPORTS_ATR_PKI'                   
						    		           ELSE 'REPORTS_ATR_ADM'
								           END,
  					          @vcAtrValue = dbo.[RA_GETWORDNUM](@vcTXT, @i,'|')
   	           
                  IF dbo.[RA_ISNUMERIC](@vcAtrValue) = 1 AND @vcAtrValue <> '000'
                  BEGIN
                     SET @bEnd = 1           
                     INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                                            [CODE_ATR],
                                                            [STR_VAL]) 
                     VALUES(@iLINK_SAVED_FORM,
                               @vcAtr,
                               @vcAtrValue)
                  END
               END
               ELSE BEGIN
                  SET @bEnd = 1
               END
            END

	         IF @bRD = 0 AND 
               @vcTXT <> '#$' -- заголовок
	         BEGIN
		         SELECT @iRightLen = LEN(@vcTXT) - CHARINDEX('=', @vcTXT)                

   	         IF CHARINDEX('ВФ=0', @vcTXT) = 1 
               BEGIN
                  SET @bVF0 = 1
               END

   	         IF CHARINDEX('ВФ=1', @vcTXT) = 1 
               BEGIN
                  SELECT @bVF0 = 1,
                         @bVF1 = 1
      IF @tMode<>2                  
                  UPDATE #IMPORT_TABLE                
                  SET [TXT] = SUBSTRING([TXT],CHARINDEX('|',[TXT])+1,8000)
                  WHERE CHARINDEX('|',[TXT]) > 0

               END

   	         IF CHARINDEX('ВФ=2', @vcTXT) = 1 
               BEGIN
                  SET @bVF2 = 1
                         
                  UPDATE #IMPORT_TABLE                
                  SET [TXT] = SUBSTRING([TXT],CHARINDEX('|',[TXT])+1,8000)
                  WHERE CHARINDEX('|',[TXT]) > 0
               END

		         IF CHARINDEX('БП=',@vcTXT)  = 1 OR 
                  CHARINDEX('КБП=',@vcTXT) = 1 OR 
                  CHARINDEX('ИСТ=',@vcTXT) = 1
		         BEGIN
			         SET @vcKBP = RTRIM(RIGHT(@vcTXT, @iRightLen))
		         END

		         IF CHARINDEX('ДТ=', @vcTXT) = 1 OR 
                  CHARINDEX('РДТ=', @vcTXT) = 1
		         BEGIN				   	   	   
			         SET @vcTmp = RIGHT(@vcTXT, @iRightLen)
			         IF PATINDEX('__.__.__%', @vcTmp) > 0
			         BEGIN
                     SELECT @i = CASE 
                                    WHEN LEN(@vcTmp) = 8 THEN 4
                                    ELSE 104
                                 END,
                            @dDT = CONVERT(DATETIME, @vcTmp, @i)
			         END
			         ELSE BEGIN				
				         EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-1 -- Неправильный формат даты
                     --SET @bEnd = 1
			         END
		         END

		         IF CHARINDEX('ПРД=', @vcTXT) = 1
		         BEGIN
		            SET @vcTmp = RTRIM(RIGHT(@vcTXT,@iRightLen))
		            IF LEN(@vcTmp)=1 AND dbo.[RA_ISNUMERIC](@vcTmp)=1
		            BEGIN
		               IF @bVF0=1
		               BEGIN
			               SET @tPRD = CAST(@vcTmp AS TINYINT)
			               IF @tPRD NOT IN (1,2,4)
			               BEGIN
			                  SET @tPRD = NULL
			               END
		               END
		               ELSE BEGIN
			               SET @tPRD = CASE @vcTmp
                                        WHEN '3' THEN 4 
                                        WHEN '4' THEN 2 
                                        WHEN '5' THEN 1                                                     
                                        WHEN '7' THEN 2
                                     END
                     END
                  END
                  
                  IF @tPRD IS NULL
                  BEGIN
                     EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-14 -- Неверное значение в разделе периодичности формы (ПРД)
                  END
		         END

		         IF CHARINDEX('КСБУ=', @vcTXT) = 1 
		         BEGIN
			         SET @vcKSBU = RTRIM(RIGHT(@vcTXT,@iRightLen))
		         END

		         IF CHARINDEX('ПРП=', @vcTXT) = 1 
		         BEGIN
			         SET @vcPRP = RTRIM(RIGHT(@vcTXT,@iRightLen))
		         END
         		
		         IF CHARINDEX('КФ=', @vcTXT) = 1 OR 
                  CHARINDEX('КОДФ=', @vcTXT) = 1
		         BEGIN
			         SET @cCODE_FORM = RTRIM(RIGHT(@vcTXT,@iRightLen))
		         END

		         IF CHARINDEX('ВБ=', @vcTXT) = 1 OR
                  CHARINDEX('ВИД=', @vcTXT) = 1
		         BEGIN
			         SELECT @vcVB = RTRIM(RIGHT(@vcTXT,@iRightLen))			          
		         END
               IF @bRA = 1
               BEGIN
                  SELECT @i = PATINDEX('%=%',@vcTXT),
                         @vcAtr = LEFT(@vcTXT,@i-1),
                         @vcAtrValue = SUBSTRING(@vcTXT,@i+1,8000)
                  
                  INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                                      [CODE_ATR],
                                                      [STR_VAL])
                  VALUES (@iLINK_SAVED_FORM,
                          @vcAtr,
                          @vcAtrValue)         
               END
               -- Включатель раздела атрибутов (РА).
               IF CHARINDEX('РА=0', @vcTXT) = 1
               BEGIN
			         SELECT @bRD = 0,
                         @bRA = 1
               END

               -- Включатель раздела данных (РД).
		         IF CHARINDEX('РД=', @vcTXT) = 1 OR 
                  CHARINDEX('ТБ=', @vcTXT) = 1
		         BEGIN
			         SELECT @bRD = 1,
                         @bRA = 0
		         END
	         END

            FETCH NEXT
            FROM curIMPORT_TABLE
	         INTO @vcTXT
         END
         
         CLOSE curIMPORT_TABLE
         DEALLOCATE curIMPORT_TABLE

         SELECT @vcSOFT = RTRIM(RIGHT([TXT], LEN([TXT]) - CHARINDEX('=', [TXT])))
         FROM #IMPORT_TABLE
         WHERE CHARINDEX('ПО=',[TXT]) = 1  OR
               CHARINDEX('ППО=',[TXT]) = 1
      END
   END
END

IF LEFT(@cCODE_FORM,3) IN ('337','338','368', '369', '359', '379') AND SUBSTRING(@cCODE_FORM, 4, 1) IN ('d', 'v', 'z', 'c', 'i', 'm')  
BEGIN
   INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                       [CODE_ATR],
                                      [STR_VAL]) 
   SELECT @iLINK_SAVED_FORM, 'REPORTS_ATR_VID', CASE SUBSTRING(@cCODE_FORM, 4, 1) WHEN 'd' THEN '2' 
                                                                                  WHEN 'v' THEN '3'
                                                                                  WHEN 'z' THEN '4'
                                                                                  WHEN 'c' THEN '5' 
                                                                                  WHEN 'i' THEN '6'
                                                                                  WHEN 'm' THEN '7' ELSE '' END
   SET @cCODE_FORM = LEFT(@cCODE_FORM,3)                                                                                  
END 

IF LEFT(@cCODE_FORM,3) IN ('373','379') AND SUBSTRING(@cCODE_FORM, 4, 1) IN ('b', 'v', 't')  
BEGIN
   INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                       [CODE_ATR],
                                      [STR_VAL]) 
   SELECT @iLINK_SAVED_FORM, 'REPORTS_ATR_VID_773', SUBSTRING(@cCODE_FORM, 4, 1)


   INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                       [CODE_ATR],
                                      [STR_VAL]) 
   SELECT @iLINK_SAVED_FORM, 'REPORTS_ATR_VID_NAME_773', Name
   FROM R_SPR_ATR_VID_773
   WHERE Code = SUBSTRING(@cCODE_FORM, 4, 1)
                                                                                
   SET @cCODE_FORM = LEFT(@cCODE_FORM,3)                                                                                  
END 

IF LEFT(@cCODE_FORM,3) IN ('325') AND SUBSTRING(@cCODE_FORM, 4, 1) IN ('d', 'v', 'z', 'c', 'i', 'm')  
BEGIN
   IF @vcKSBU IS NOT NULL
   BEGIN   
      INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                          [CODE_ATR],
                                         [STR_VAL]) 
      SELECT @iLINK_SAVED_FORM, 'REPORTS_ATR_ACC_725', @vcKSBU
   END 
   SET @cCODE_FORM = LEFT(@cCODE_FORM,3)                                                                                  
END 

IF EXISTS(SELECT * FROM #IMPORT_TABLE WHERE TXT LIKE 'FK|%TXKS120101|%')
BEGIN
   SET @cCODE_FORM = '622'
   SET @bVF0 = 0
   
   SELECT @dDT = CONVERT(SMALLDATETIME,dbo.[RA_GETWORDNUM]([TXT],5,'|'),104)
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) = 'KS|'   
   
   SET @tPRD = 4
   
   SELECT @vcKBP = REPLACE(REPLACE(REPLACE([TXT], 'KБП=', ''), 'ИСТ=', ''), 'KБ=', '')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
         LEFT([TXT],3) IN ('KБ=')

   SELECT @vcVB = REPLACE(REPLACE([TXT], 'ВИД=', ''), 'ВБ=', '')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

   SELECT @vcUK = dbo.[RA_GETWORDNUM]([TXT],3,'|')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) = 'TO|'   

   IF @vcKBP IS NULL
   BEGIN
      SELECT @vcKBP = ISNULL([KBP],'')      
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503152'
   END

   IF @vcVB IS NULL 
   BEGIN
      SELECT @vcVB = ISNULL([VB],'')
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503152'
   END

   IF @vcKBP IS NULL
   BEGIN
      SELECT @vcKBP = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_KBP_152'
   END

   IF @vcVB IS NULL 
   BEGIN
      SELECT @vcVB = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_VB_152'
   END
END       

IF EXISTS(SELECT * FROM #IMPORT_TABLE WHERE TXT LIKE 'FK|%TXPW090810|%')
BEGIN
   SET @cCODE_FORM = '0503151'
   SET @bVF0 = 0
   
   SELECT @dDT = CONVERT(SMALLDATETIME,dbo.[RA_GETWORDNUM]([TXT],7,'|'),104)
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) = 'PW|'   
   
   SET @tPRD = 4
   
   SELECT @vcKBP = REPLACE(REPLACE(REPLACE([TXT], 'KБП=', ''), 'ИСТ=', ''), 'KБ=', '')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
         LEFT([TXT],3) IN ('KБ=')

   SELECT @vcVB = REPLACE(REPLACE([TXT], 'ВИД=', ''), 'ВБ=', '')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

   SELECT @vcUK = dbo.[RA_GETWORDNUM]([TXT],3,'|')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) = 'TO|'   

   IF @vcKBP IS NULL
   BEGIN
      SELECT @vcKBP = ISNULL([KBP],'')      
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503151'
   END

   IF @vcVB IS NULL 
   BEGIN
      SELECT @vcVB = ISNULL([VB],'')
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503151'
   END

   IF @vcKBP IS NULL
   BEGIN
      SELECT @vcKBP = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_151' AND
            [CODE] = 'IMPORT_KBP_151'
   END

   IF @vcVB IS NULL 
   BEGIN
      SELECT @vcVB = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_151' AND
            [CODE] = 'IMPORT_VB_151'
   END
END           
    

IF @tMode = 1
BEGIN
   SET @vcKBP = 'DEMO'
   
   SELECT @vcVB = [OUTCODE]
   FROM dbo.[KL_BUDG_TYPE]
   WHERE [CODE]='К'
END
/*
IF LEFT(@vcKBP,1) = '0' AND
   @cCODE_FORM IN ('0503725','0503730G_B',
                   '310','321','325','330','337','338','359','360','361','366','367','368','369','371','372','373','376','379','381','384','385','386','387',
                   '710','725','737','738','759','769','779')
BEGIN
   SET @vcKBP = SUBSTRING(@vcKBP,2,8000)
END
*/

IF @tPRD = 2 AND LEFT(@cCODE_FORM,3) IN ('325','337','359','369','379')
BEGIN
   SET @tPRD = 4
END

SET @bIsEmptyVB = 0			   			
SELECT @bIsEmptyVB = 1
FROM dbo.[RA_VIEW_EMPTY_BUDGET] 
WHERE @vcVB IN ([OUTCODE],'')


IF @vcVB IS NULL
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-2 -- Отсутствует раздел кода вида бюджета (ВБ или ВИД)   
END

IF @vcKBP IS NULL
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-3 -- Отсутствует раздел кода бюджетополучателя (БП, КБП или ИСТ)
END

IF @tPRD IS NULL AND 
   @bVF0=0
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-4 -- Отсутствует раздел периодичности формы (ПРД)
END

IF DAY(@dDT)<>1
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-5 -- Неправильная дата. Число должно быть 01
END

IF @tPRD = 2 AND MONTH(@dDT) NOT IN (1,4,7,10)
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-6 -- Неправильная дата. Месяц квартальной формы должен быть 01,04,07 или 10
END

IF @tPRD = 1 AND MONTH(@dDT) <> 1
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-7 -- Неправильная дата. Неправильная дата. Месяц для годовой формы должен быть 01
END

-- Проверка лицензии на использование выгрузок Свод-ЕXCEL.
IF (@bVF1=1 OR @bVF2=1) AND YEAR(@dDT)>2009
BEGIN
   CREATE TABLE #tabSUBCONFIG([SUBCONFIG] VARCHAR(8000))
   
   SET @vcDB_NAME = DB_NAME()
   INSERT #tabSUBCONFIG([SUBCONFIG])
   EXEC master.dbo.[XP_SMETA_GETSUBCONFIG] @vcDB_NAME, @vcSUB_CONFIG OUTPUT
   
   DROP TABLE #tabSUBCONFIG
      
   IF (NOT ','+RTRIM(LTRIM(@vcSUB_CONFIG))+',' LIKE '%,EC,%') /*AND NOT(@@SERVERNAME='KSDB2\BUH' AND @vcDB_NAME = 'buh_new')*/
   BEGIN
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-16 -- Отсутствует лицензия на использование Свод-EXCEL.
   END  
END

SELECT @vcCODE_TASK = [CODE_TASK]
FROM dbo.[USER_INFO]

/*
IF @vcCODE_TASK = 'OUTPUTS' AND 
   @bIsEmptyVB = 1
BEGIN
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-10 -- В отчете отсутствует код бюджета
END
*/

delete dbo.Buffer
where sid = suser_sid() and ID = 'IMPORT_REPORT_WITH_TREE'
		
insert dbo.Buffer(ID, link)
select 'IMPORT_REPORT_WITH_TREE', dbo.RO_SVOD_TREE_Link_History(@dDT)


SELECT @i = COUNT(*) 
FROM dbo.[KL_BUDG_TYPE]
WHERE [OUTCODE] = @vcVB AND
      LEN([OUTCODE])>0   
IF @i > 1
BEGIN
   SET @vcTmp = 'Выгружаемый код бюджета ' + RTRIM(@vcVB) + ' не уникален.'
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-11,@vcTmp -- Выгружаемый код бюджета не уникален.
END
ELSE BEGIN
   IF @i = 0 AND 
      @bIsEmptyVB = 0
   BEGIN  
		EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
		SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))	
			
		IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
		BEGIN
		INSERT #t_RepeatRequest ([RES],[bExcess])
			VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 3)
		END
      SET @vcTmp = 'Не найден бюджет с выгружаемым кодом ' + RTRIM(@vcVB)
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-12,@vcTmp -- Не найден бюджет.
   END
END

IF @bIsEmptyVB = 1 AND
   NOT EXISTS(SELECT *
              FROM dbo.[RO_SVOD_TREE] [A]
              JOIN dbo.[KL_BUDG_TYPE] [B] ON [B].[LINK] = [A].[LINK_REPORT_BUDG]
              JOIN dbo.[DEPARTMENTS]  [C] ON [C].[LINK] = [A].[LINK_REPORT_ORG]
              WHERE [C].[BUDG] = @vcKBP AND
                    [B].[OUTCODE] = @vcVB)
BEGIN
   SET @vcVB = ''
   
   SELECT @vcVB = [B].[OUTCODE]
   FROM dbo.[RO_SVOD_TREE]         [A]
   JOIN dbo.[KL_BUDG_TYPE]         [B] ON [B].[LINK] = [A].[LINK_REPORT_BUDG]   
   JOIN dbo.[RA_VIEW_EMPTY_BUDGET] [C] ON [C].[OUTCODE] = [B].[OUTCODE]
   JOIN dbo.[DEPARTMENTS]          [D] ON [D].[LINK] = [A].[LINK_REPORT_ORG]
   WHERE [D].[BUDG] = @vcKBP
END

IF @cCODE_FORM IN ('201','204','207')
BEGIN
   SET @dDT = DATEADD(YEAR, 1, @dDT)   
END

-- Проверки полученных признаков форм.
EXEC @iError = dbo.[RA_IMPORT_FORM_GET_LINK_FORM] @iLINK_FORM OUTPUT,
                                                  @cCODE_FORM,
                                                  @tPRD OUTPUT,
                                                  @dDT,
                                                  @bVF0,
                                                  @vcFILENAME


-- Сохранение ошибки в лог ошибок.
IF @iError < 0
BEGIN
   SET @i = OBJECT_ID('dbo.[RA_IMPORT_FORM_GET_LINK_FORM]')
   EXEC dbo.[RA_ERRORS_LOG_ADD] @i,@iError   
   
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-13,'' -- Не найден бюджет.
END

/*
exec xa_watchi '@cCODE_FORM ',@cCODE_FORM 
exec xa_watchs
select * from report_forms where code = '0505140'
*/

SELECT @i = COUNT(*)
FROM dbo.[DEPARTMENTS] 
WHERE [BUDG] = NULLIF(@vcKBP,'')      

IF @i = 0
BEGIN
	EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
	SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))	
		
	IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
	BEGIN
	INSERT #t_RepeatRequest ([RES],[bExcess])
		VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 3)
	END

   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-9 -- Организации с таким кодом бюджетополучателя не существует
END
ELSE BEGIN
   IF @i > 1
   BEGIN
      SET @vcTmp = 'Код бюджетополучателя ' + RTRIM(@vcKBP) + ' соответствует следующим организациям : '
      
      SELECT @vcTmp = @vcTmp + RTRIM([NAME]) + ', '
      FROM dbo.[DEPARTMENTS] 
      WHERE [BUDG] = @vcKBP
      ORDER BY [NAME]
         
      SET @vcTmp = LEFT(@vcTmp,LEN(@vcTmp)-1)
         
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-15,@vcTmp -- Неуникальный КБП в базе данных.
   END
END

UPDATE dbo.[REPORT_IMPORT_SAVED_FORMS]
SET [CODE_FORM] = @cCODE_FORM,
    [LINK_FORM] = @iLINK_FORM,
    [KBP]       = @vcKBP,
    [VB]        = @vcVB,
    [DT]        = @dDT,
    [PRD]       = @tPRD,   
    [VF0]       = @bVF0,
    [SOFT]      = @vcSOFT
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

-- Атрибут для 0531467
IF @cCODE_FORM = '0531467' AND @dDT_DAY IS NOT NULL
   BEGIN
      INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                       [CODE_ATR],
                                       [STR_VAL]) 
      VALUES(@iLINK_SAVED_FORM,
          'REPORTS_ATR_DATA_DAY',
          CONVERT(VARCHAR(10),@dDT_DAY, 104))
   
   END

-- Атрибут КСБУ для 125 форм.
IF @vcKSBU IS NOT NULL
BEGIN
   if @dDT <= convert(datetime, '20110101', 112)
   BEGIN
      INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                          [CODE_ATR],
                                          [STR_VAL]) 
      VALUES(@iLINK_SAVED_FORM,
             'REPORTS_ATR_ACC',
             @vcKSBU)
   END
   ELSE BEGIN
      INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                          [CODE_ATR],
                                          [STR_VAL]) 
      VALUES(@iLINK_SAVED_FORM,
             'REPORTS_ATR_ACC_2011',
             @vcKSBU)
   END
   
   SELECT @vcKSBU = [CODE2]
   FROM dbo.[RT_VIEW_KSBU_125]
   WHERE [CODE] = @vcKSBU
   
   IF @vcKSBU IS NOT NULL
   BEGIN
      INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                          [CODE_ATR],
                                          [STR_VAL]) 
      VALUES(@iLINK_SAVED_FORM,
             'REPORTS_ATR_NAFO',
             @vcKSBU)
   END
END

IF @vcPRP IS NOT NULL
BEGIN
   INSERT dbo.[REPORT_IMPORT_ATRIBUTS]([LINK_SAVED_FORM],
                                       [CODE_ATR],
                                       [STR_VAL]) 
   VALUES(@iLINK_SAVED_FORM,
          'REPORTS_ATR_PRP',
          @vcPRP)          
END

UPDATE dbo.[REPORT_IMPORT_SAVED_FORMS]
SET [ATRIBUTS]  = dbo.[RN_GET_ATR_VAL](@iLINK_SAVED_FORM,
                                       @iLINK_FORM,
                                       2)
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

RETURN dbo.[RA_GET_ERROR](OBJECT_ID('dbo.[RA_IMPORT_FORM_ANALYZE]'))
GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_ANALYZE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
select ra_getwordpos('123|222',2,'|')

SELECT * FROM report_import_saved_forms where link_saved_form=562

select dbo.[RN_GET_ATR_VAL](562,
                            1378,
                            2)
exec xa_watchd

delete from report_errors where context='RA_IMPORT_FORM_ANALYZE'

insert report_errors values('RA_IMPORT_FORM_ANALYZE',-1,'Неправильный формат даты')				
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-2,'Отсутствует раздел кода вида бюджета (ВБ или ВИД)')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-3,'Отсутствует раздел кода бюджетополучателя (БП, КБП или ИСТ)')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-4,'Отсутствует раздел периодичности формы (ПРД)')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-5,'Неправильная дата. Число должно быть 01')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-6,'Неправильная дата. Месяц квартальной формы должен быть 01,04,07 или 10')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-7,'Неправильная дата. Неправильная дата. Месяц для годовой формы должен быть 01')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-9,'Организации с таким кодом бюджетополучателя не существует')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-10,'В отчете отсутствует код бюджета')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-11,'Выгружаемый код бюджета не уникален')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-12,'Выгружаемый код бюджета не найден')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-13,'Ошибка в dbo.[RA_IMPORT_FORM_GET_LINK_FORM]')
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-14,'Неверное значение в разделе периодичности формы (ПРД)',1)
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-15,'Неуникальный КБП в базе данных',1)
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-16,'Отсутствует лицензия на использование Свод-EXCEL',1)
insert report_errors values('RA_IMPORT_FORM_ANALYZE',-17,'Ошибка при разборе XML-файла.',1)

select * from report_errors order by description

ra_script_errors



*/	


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





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

CREATE  PROCEDURE dbo.RO_REPORT_MODIFY
		@varKSiLink	int
AS

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

delete report_sign where LSF = @varKSiLink

DECLARE @LF INT , @cForm VARCHAR(50), @cOrg VARCHAR(50), @Link_Org INT, @atr VARCHAR(50) 
SELECT @LF = link_form, @Link_Org = [Link_Organization], @atr = [atr]
  FROM dbo.report_saved_forms WHERE [Link_Saved_Form] = @varKSiLink
SELECT @cForm = Code FROM dbo.report_forms WHERE [Link_Form] = @LF

IF @cForm LIKE '(86н)00%'
BEGIN
   SELECT @cOrg = D.Code
   FROM dbo.[DEPARTMENTS] d
   WHERE d.[LINK] = @Link_Org
   
   DELETE report_kbk WHERE  code_form = 'spr_info_send_razdel_'+@cForm AND code = @cOrg AND @atr = LONG_NAME
   DELETE report_kbk WHERE  code_form = 'spr_info_send_razdel_'+SUBSTRING(@cForm,8,1) AND code = @cOrg AND @atr = LONG_NAME
END    

RETURN 0

GO
GRANT ALL ON RO_REPORT_MODIFY 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.[XD_DEP_KBK_OSN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XD_DEP_KBK_OSN]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].XD_DEP_KBK_OSN
 @varKSparLINK int, @varKSDepLink int 
AS 

/* Почистить всё */
UPDATE dbo.DEPARTMENT_KBK
SET OSN = 0
WHERE DEP_LINK = @varKSDepLink 



/* Установить основной ВКР */
UPDATE dbo.DEPARTMENT_KBK
SET OSN = 1
WHERE KBK_LINK = @varKSparLINK and DEP_LINK =@varKSDepLink 

if @@rowcount = 0
	insert into DEPARTMENT_KBK(KBK_LINK, DEP_LINK, OSN)
	values (@varKSparLINK, @varKSDepLink, 1)   		 

GO


GRANT EXECUTE ON dbo.[XD_DEP_KBK_OSN] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

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

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

CREATE PROCEDURE dbo.[RO_WEB_VR_USER_2011]
AS

   declare @Link_Tree int
   select @Link_Tree = T.link
   from dbo.report_svod_tree T join dbo.user_form_access U on T.link_report_org = U.dep_link and isnull(T.link_report_budg, 0) = isnull(U.budg_link, 0) and U.sid = suser_sid()
   where isnull(link_self, 0) = 0

   if @Link_Tree is NULL
      select @Link_Tree = T.link
      from dbo.report_svod_tree T join dbo.user_form_access U on T.link_report_org = U.dep_link and isnull(T.link_report_budg, 0) = isnull(U.budg_link, 0) and u.sid = suser_sid()
      where not exists(select top 1 * from dbo.report_svod_tree T1 join dbo.user_form_access U1 on T1.link_report_org = U1.dep_link and isnull(T1.link_report_budg, 0) = isnull(U1.budg_link, 0) and u1.sid = suser_sid()
                        where T.link_self = T1.link)

   select Link, Code, 
         Name = dbo.RO_KBK_FOR_ORG(@Link_Tree, link, 1, Name),
         Long_Name = dbo.RO_KBK_FOR_ORG(@Link_Tree, link, 2, Long_Name)
   from dbo.REPORT_KBK
   where Code_Form = 'ВР_2011_USER'
   order by Code

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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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

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


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

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

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


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



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


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

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

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


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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_EXPORT_UF to public
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_127]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_127]
END
GO

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_127]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,     -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn     INT,
        @liLSF        INT,
        @lvcAdm       VARCHAR(3),                
        @lvcTXT   VARCHAR(8000),
        @lvcWord1 VARCHAR(8000),
        @lvcWord2 VARCHAR(8000),
        @lvcKBP   VARCHAR(50),
        @lvcVB    VARCHAR(50),
        @liORDER  INT,
        @i        INT,
        @k        INT,
        @iAdmCount INT

--select * from #IMPORT_TABLE

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN   
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE] @lbSvodWEB,
                                                                 @liRepeatRequest,
                                                                 @tIsAppend,
                                                                 @bDinamicRows,
                                                                 @iLINK_SELF,
                                                                 @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1')) OR           
   ((SELECT COUNT(DISTINCT dbo.[RA_GETWORDNUM] ([TXT],2, '|'))
     FROM #IMPORT_TABLE
     WHERE [TXT] LIKE '%|%' AND
     dbo.[RA_GETWORDNUM] ([TXT],2, '|')<>'***')=1)
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,                                                  
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

UPDATE #IMPORT_TABLE 
SET [TXT] = REPLACE([TXT],',','.')
WHERE [TXT] LIKE '%|%'

DECLARE @tabRD TABLE ([TXT]   VARCHAR(7000),                        
                      [RD]    INT,
                      [ORDER] INT IDENTITY(1,1))

SELECT @i = MIN([ORDER])
FROM #IMPORT_TABLE
WHERE [TXT] = '#' --LEFT([TXT],5) = 'ТБ=01'

INSERT @tabRD([TXT],
              [RD])
SELECT [TXT],
       0
FROM #IMPORT_TABLE
WHERE [ORDER] <= @i --<= (@i + 1)
ORDER BY [ORDER]

DELETE #IMPORT_TABLE
WHERE [ORDER] <= @i -- <= (@i + 1)

SET @i = NULL
SELECT @i = [ORDER] + 2
FROM #IMPORT_TABLE
WHERE LEFT([TXT],5) = 'ТБ=01'

SET @k = NULL
SELECT @k = MIN([ORDER]) - 1
FROM #IMPORT_TABLE
WHERE [ORDER] > @i AND
      [TXT] = '#' 

IF @i IS NOT NULL AND
   @k IS NOT NULL
BEGIN
   SET @iAdmCount = 0
   SELECT @iAdmCount = ISNULL(COUNT(DISTINCT dbo.[RA_GETWORDNUM]([TXT],2,'|')),0)
   FROM #IMPORT_TABLE
   WHERE [TXT] LIKE '%|%' AND       
         ([ORDER] BETWEEN @i AND @k) AND
         dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('***')

   INSERT @tabRD([TXT],
                 [RD])
   SELECT [TXT] = [B].[CODE_STR] + '|000|' +
                  [B].[CODE] + '|' +
                  LTRIM(STR([COL1],20,2)) + '|' +
                  LTRIM(STR([COL2],20,2)) + '|' +
                  LTRIM(STR([COL3],20,2)) + '|' +
                  LTRIM(STR([COL4],20,2)) + '|' +
                  LTRIM(STR([COL5],20,2)) + '|' +
                  LTRIM(STR([COL6],20,2)) + '|',1  
   FROM (
      SELECT [CODE_STR] = MAX([A].[CODE_STR]),
             [A].[CODE],
             [COL1] = SUM([COL1]),
             [COL2] = SUM([COL2]),
             [COL3] = SUM([COL3]),
             [COL4] = SUM([COL4]),
             [COL5] = SUM([COL5]),
             [COL6] = SUM([COL6])          
      FROM 
      (
         SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],1,'|'),
                [CODE] = dbo.[RA_GETWORDNUM]([TXT],3,'|'),
                [COL1] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''),0) AS NUMERIC(20,4)),
                [COL2] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],5,'|'),''),0) AS NUMERIC(20,4)),
                [COL3] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],6,'|'),''),0) AS NUMERIC(20,4)),
                [COL4] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],7,'|'),''),0) AS NUMERIC(20,4)),
                [COL5] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],8,'|'),''),0) AS NUMERIC(20,4)),
                [COL6] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],9,'|'),''),0) AS NUMERIC(20,4))
         FROM #IMPORT_TABLE
         WHERE [TXT] LIKE '%|%' AND 
               ([ORDER] BETWEEN @i AND @k) AND  
               (@iAdmCount <= 1 OR @iAdmCount > 1 AND dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('000','***')) AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],4,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],4,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],5,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],5,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],6,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],6,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],7,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],8,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],8,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],9,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],9,'|') = '')
      ) [A]
      GROUP BY [A].[CODE]
   ) [B]

   DELETE #IMPORT_TABLE
   WHERE [ORDER] BETWEEN @i-3 AND @k+1
END

SET @i = NULL
SELECT @i = [ORDER] + 2
FROM #IMPORT_TABLE
WHERE LEFT([TXT],5) = 'ТБ=02'

SET @k = NULL
SELECT @k = MIN([ORDER]) - 1
FROM #IMPORT_TABLE
WHERE [ORDER] > @i AND
      [TXT] = '#' 

IF @i IS NOT NULL AND
   @k IS NOT NULL
BEGIN
   SET @iAdmCount = 0
   SELECT @iAdmCount = ISNULL(COUNT(DISTINCT dbo.[RA_GETWORDNUM]([TXT],2,'|')),0)
   FROM #IMPORT_TABLE
   WHERE [TXT] LIKE '%|%' AND       
         ([ORDER] BETWEEN @i AND @k) AND
         dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('***')

   INSERT @tabRD([TXT],
                 [RD])
   SELECT [TXT] = [B].[CODE_STR] + '|000|' +
                  [B].[CODE] + '|' +
                  LTRIM(STR([COL1],20,2)) + '|' +
                  LTRIM(STR([COL2],20,2)) + '|' +
                  LTRIM(STR([COL3],20,2)) + '|' +
                  LTRIM(STR([COL4],20,2)) + '|' +
                  LTRIM(STR([COL5],20,2)) + '|' +
                  LTRIM(STR([COL6],20,2)) + '|',2
   FROM (
      SELECT [CODE_STR] = MAX([A].[CODE_STR]),
             [A].[CODE],
             [COL1] = SUM([COL1]),
             [COL2] = SUM([COL2]),
             [COL3] = SUM([COL3]),
             [COL4] = SUM([COL4]),
             [COL5] = SUM([COL5]),
             [COL6] = SUM([COL6]),
             [COL7] = SUM([COL7]),
             [COL8] = SUM([COL8])
      FROM 
      (
         SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],1,'|'),
                [CODE] = dbo.[RA_GETWORDNUM]([TXT],3,'|')+'|'+
                         dbo.[RA_GETWORDNUM]([TXT],4,'|')+'|'+
                         dbo.[RA_GETWORDNUM]([TXT],5,'|')+'|'+
                         dbo.[RA_GETWORDNUM]([TXT],6,'|'),             
                [COL1] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],7,'|'),''),0) AS NUMERIC(20,4)),
                [COL2] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],8,'|'),''),0) AS NUMERIC(20,4)),
                [COL3] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],9,'|'),''),0) AS NUMERIC(20,4)),
                [COL4] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],10,'|'),''),0) AS NUMERIC(20,4)),
                [COL5] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],11,'|'),''),0) AS NUMERIC(20,4)),
                [COL6] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],12,'|'),''),0) AS NUMERIC(20,4)),
                [COL7] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],13,'|'),''),0) AS NUMERIC(20,4)),
                [COL8] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],14,'|'),''),0) AS NUMERIC(20,4))
         FROM #IMPORT_TABLE
         WHERE [TXT] LIKE '%|%' AND 
               ([ORDER] BETWEEN @i AND @k) AND  
               (@iAdmCount <= 1 OR @iAdmCount > 1 AND dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('000','***')) AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],7,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],8,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],8,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],9,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],9,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],10,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],10,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],11,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],11,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],12,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],12,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],13,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],13,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],14,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],14,'|') = '')
      ) [A]
      GROUP BY [A].[CODE]
   ) [B]

   DELETE #IMPORT_TABLE
   WHERE [ORDER] BETWEEN @i-3 AND @k+1
END
 
SET @i = NULL
SELECT @i = [ORDER] + 2
FROM #IMPORT_TABLE
WHERE LEFT([TXT],5) = 'ТБ=03'

SET @k = NULL
SELECT @k = MIN([ORDER]) - 1
FROM #IMPORT_TABLE
WHERE [ORDER] > @i AND
      [TXT] = '#' 

IF @i IS NOT NULL AND
   @k IS NOT NULL
BEGIN
   SET @iAdmCount = 0
   SELECT @iAdmCount = ISNULL(COUNT(DISTINCT dbo.[RA_GETWORDNUM]([TXT],2,'|')),0)
   FROM #IMPORT_TABLE
   WHERE [TXT] LIKE '%|%' AND       
         ([ORDER] BETWEEN @i AND @k) AND
         dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('***')

   INSERT @tabRD([TXT],
                 [RD])
   SELECT [TXT] = [B].[CODE_STR] + '|' + 
                  CASE 
                     WHEN LEFT([CODE_STR],1)='8' THEN '***'
                     ELSE '000'
                  END + '|' +
                  [B].[CODE] + '|' +
                  LTRIM(STR([COL1],20,2)) + '|' +
                  LTRIM(STR([COL2],20,2)) + '|' +
                  LTRIM(STR([COL3],20,2)) + '|' +
                  LTRIM(STR([COL4],20,2)) + '|' +
                  LTRIM(STR([COL5],20,2)) + '|' +
                  LTRIM(STR([COL6],20,2)) + '|',3  
   FROM (
      SELECT [A].[CODE_STR],
             [A].[CODE],
             [COL1] = SUM([COL1]),
             [COL2] = SUM([COL2]),
             [COL3] = SUM([COL3]),
             [COL4] = SUM([COL4]),
             [COL5] = SUM([COL5]),
             [COL6] = SUM([COL6])          
      FROM 
      (
         SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],1,'|'),
                [CODE] = dbo.[RA_GETWORDNUM]([TXT],3,'|'),
                [COL1] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''),0) AS NUMERIC(20,4)),
                [COL2] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],5,'|'),''),0) AS NUMERIC(20,4)),
                [COL3] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],6,'|'),''),0) AS NUMERIC(20,4)),
                [COL4] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],7,'|'),''),0) AS NUMERIC(20,4)),
                [COL5] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],8,'|'),''),0) AS NUMERIC(20,4)),
                [COL6] = CAST(ISNULL(NULLIF(dbo.[RA_GETWORDNUM]([TXT],9,'|'),''),0) AS NUMERIC(20,4))
         FROM #IMPORT_TABLE
         WHERE [TXT] LIKE '%|%' AND 
               ([ORDER] BETWEEN @i AND @k) AND  
               (@iAdmCount <= 1 OR @iAdmCount > 1 AND dbo.[RA_GETWORDNUM]([TXT],2,'|') NOT IN ('000','***')) AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],4,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],4,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],5,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],5,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],6,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],6,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],7,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],8,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],8,'|') = '') AND
               (dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],9,'|'))=1 OR dbo.[RA_GETWORDNUM]([TXT],9,'|') = '')

      ) [A]
      GROUP BY [A].[CODE_STR],[A].[CODE]
   ) [B]
END

IF OBJECT_ID('tempdb..#IMPORT_TABLE') IS NOT NULL
BEGIN
   DROP TABLE #IMPORT_TABLE
END        
                               
CREATE TABLE #IMPORT_TABLE([TXT] VARCHAR(1000), 
                           [ORDER] INT IDENTITY(1,1))     

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM @tabRD
WHERE [RD]=0
ORDER BY [ORDER]

INSERT #IMPORT_TABLE([TXT]) VALUES ('#@')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ТБ=01')
INSERT #IMPORT_TABLE([TXT]) VALUES ('#$')

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM @tabRD
WHERE [RD]=1
ORDER BY [ORDER]
   
INSERT #IMPORT_TABLE([TXT]) VALUES ('#')
INSERT #IMPORT_TABLE([TXT]) VALUES ('#@')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ТБ=02')
INSERT #IMPORT_TABLE([TXT]) VALUES ('#$')

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM @tabRD
WHERE [RD]=2
ORDER BY [ORDER]

INSERT #IMPORT_TABLE([TXT]) VALUES ('#')
INSERT #IMPORT_TABLE([TXT]) VALUES ('#@')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ТБ=03')
INSERT #IMPORT_TABLE([TXT]) VALUES ('#$')

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM @tabRD
WHERE [RD]=3
ORDER BY [ORDER]

INSERT #IMPORT_TABLE([TXT]) VALUES ('#')


EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                               @liRepeatRequest,
                                               @tIsAppend,
                                               @bDinamicRows,
                                               @iLINK_SELF,
                                               @tMode

RETURN @liReturn

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

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest   

LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/

GO




GO

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

GO
CREATE PROCEDURE [dbo].SA_TABEL_FILL_EMPL
	@varKSYear 		int,  
	@varKSMonth 		int, 		
	@varKSLinkTab 	int = 0,
	@DEP_LINK int = null,
	@BufferCode varchar(10) = null 
AS

DECLARE @varKSDateBegin datetime,
		@varKSDateEnd	  datetime

set @DEP_LINK = coalesce(@DEP_LINK,(select DEP_LINK from user_dep))

SET @varKSDateBegin = dbo.ConvertDMY2Date(1,@varKSMonth,@varKSYear) 
SET @varKSDateEnd 	= dbo.DateEndOfMonth(@varKSDateBegin)

CREATE TABLE #empl (link int, num_stake numeric(5,2), DateAccept datetime, DateSack datetime, GRAPH_LINK int, ETS_RAZR tinyint)
CREATE INDEX #EMPL_LINK ON #empl (LINK ASC)

if ltrim(rtrim(coalesce(@BufferCode,''))) = ''
	insert into #empl 
	select e.link, st.num_stake, beg.DATE_BEGIN, dis.DIS_DATE, E.GRAPH_LINK, ISNULL(ST.ETS_RAZR,0)
	from dbo.empl E
		inner join (
		Select distinct IM.empl_link, IM.DATE_BEGIN from dbo.item_move IM where IM.active = 1 AND IM.new_face = 1
		) beg on E.link = beg.empl_link --определить дату приема
		left join (
		Select distinct IDF.empl_link, IDF.DIS_DATE from dbo.item_dis_face IDF where IDF.active=1 AND COALESCE(IDF.dis_date,@varKSDateEnd) < @varKSDateEnd
		) dis on E.link = dis.empl_link --определить дату увольнения
		left join (
		Select distinct IM.empl_link, IM.num_stake, IM.ETS_RAZR from 
			dbo.ORDER_TYPES ot
			INNER JOIN dbo.ORDERS o on ot.code = o.type
			INNER JOIN dbo.ITEM_MOVE im on im.order_link = o.link
			where ot.CODE IN (1,2) AND IM.active = 1 AND @varKSDateEnd BETWEEN IM.date_begin AND COALESCE(IM.date_end,IM.date_begin)
		) ST on E.link = ST.empl_link --определить кол-во ставок
	where DEP_LINK = @DEP_LINK order by e.link	
else
	insert into #empl 
	select B.link, st.num_stake, beg.DATE_BEGIN, dis.DIS_DATE, E.GRAPH_LINK, ISNULL(ST.ETS_RAZR,0)
	from dbo.empl E inner join dbo.Buffer B on E.link = B.link
		inner join (
		Select distinct IM.empl_link, IM.DATE_BEGIN from dbo.item_move IM where IM.active = 1 AND IM.new_face = 1
		) beg on B.link = beg.empl_link --определить дату приема
		left join (
		Select distinct IDF.empl_link, IDF.DIS_DATE from dbo.item_dis_face IDF where IDF.active=1 AND COALESCE(IDF.dis_date,@varKSDateEnd) < @varKSDateEnd
		) dis on B.link = dis.empl_link --определить дату увольнения
		left join (
		Select distinct IM.empl_link, IM.num_stake, IM.ETS_RAZR from 
			dbo.ORDER_TYPES ot
			INNER JOIN dbo.ORDERS o on ot.code = o.type
			INNER JOIN dbo.ITEM_MOVE im on im.order_link = o.link
		where ot.CODE IN (1,2) AND IM.active = 1 AND @varKSDateEnd BETWEEN IM.date_begin AND COALESCE(IM.date_end,IM.date_begin)
		) ST on B.link = ST.empl_link --определить кол-во ставок
	where RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@BufferCode)) order by B.link

CREATE TABLE #varKSS
(
 LINK_EMPL int,
 [TYPE] int,
 [PRIOR] int,
 [HOUR]  numeric(6,2),
 [DATE_1] datetime,
 [DATE_2] datetime,
 [DOC]	int)

CREATE TABLE #ITEM_VACATION(
	[LINK] INT,
	[MOVED] int,
	[EMPL_LINK] int,
	[VAC_LINK] int ,
	[TYPE_LINK] int,
	[PERIOD_BEGIN] datetime ,
	[PERIOD_END] datetime,
	[DATE_BEGIN] datetime,
	[DATE_END] datetime,
	[REASON] varchar(254),
	[ORDER_LINK] int,
	[ACTIVE] tinyint)

INSERT	#ITEM_VACATION
SELECT	* FROM ITEM_VACATION

INSERT	#ITEM_VACATION
SELECT	0,
		IV.MOVED,
		IVB.EMPL_LINK,
		IV.VAC_LINK,
		IV.TYPE_LINK,
		IV.PERIOD_BEGIN,
		IV.PERIOD_END,
		DATEADD(DAY,IVB.BREAK_WORK_DAYS,IVB.DATE_BREAK) AS DATE_BEGIN,
		DATEADD(DAY,IVB.LEN_KAL_DAYS,IV.DATE_END) AS DATE_END,
		'',
		IV.ORDER_LINK,
		IV.ACTIVE
FROM	ITEM_VACATION_BREAK IVB LEFT JOIN ITEM_VACATION IV ON IV.LINK = IVB.VAC_LINK
WHERE	IVB.EMPL_LINK IN (SELECT LINK FROM dbo.Buffer WHERE ID = RTRIM(LTRIM(@BufferCode)))
		AND IVB.ACTIVE = 1
		AND IVB.BREAK_WORK_DAYS > 0


INSERT INTO #varKSS (LINK_EMPL,[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC])
-- БОЛЬНИЧНЫЕ --
SELECT LINK_EMPL,[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC] FROM 
(SELECT 
	SD.LINK_EMPL,
	[TYPE] = N.TYPE_LINK,
	[PRIOR] = (SELECT PRIORITET FROM dbo.TYP_DAYS WHERE LINK = N.TYPE_LINK),
	[HOUR] = (SELECT HOUR FROM dbo.TYP_DAYS WHERE LINK = N.TYPE_LINK),
	[DATE_1] = (CASE WHEN SD.DATE1 < @varKSDateBegin THEN @varKSDateBegin ELSE SD.DATE1 END),
	[DATE_2] = (CASE WHEN SD.DATE2 > @varKSDateEnd  THEN @varKSDateEnd ELSE SD.DATE2 END),
	[DOC]	= 1 
FROM dbo.SDOC S INNER JOIN dbo.SDOC_DIS SD ON  S.LINK = SD.LINK_UP
	INNER JOIN dbo.NETRUD N ON SD.TYPE = N.LINK
	inner join #empl E on E.link = SD.LINK_EMPL
WHERE (SD.DATE1 BETWEEN @varKSDateBegin AND @varKSDateEnd OR SD.DATE2 BETWEEN @varKSDateBegin AND @varKSDateEnd OR
	  ((SD.DATE1 < @varKSDateBegin) AND(SD.DATE2 > @varKSDateEnd)))
UNION
-- ОТПУСКА --
SELECT 	
	V.EMPL_LINK,
	[TYPE] = VV.TYPE_LINK,
	[PRIOR] = (SELECT PRIORITET FROM dbo.TYP_DAYS WHERE LINK = VV.TYPE_LINK),
	[HOUR] 	= (SELECT HOUR FROM dbo.TYP_DAYS WHERE LINK = VV.TYPE_LINK),
	[DATE_1] = (CASE WHEN DATE_BEGIN < @varKSDateBegin THEN @varKSDateBegin ELSE DATE_BEGIN END),
	[DATE_2] = (CASE WHEN ISNULL((SELECT top 1 (CASE
							WHEN IVB.DATE_BREAK - 1 > (ISNULL((SELECT top 1 (CASE
													    WHEN IVD.NEW_DATE_END > V.DATE_END
														THEN IVD.NEW_DATE_END
													    ELSE V.DATE_END
													 END)  
 											   FROM ITEM_VACATION_DIS IVD
									                   WHERE IVD.VAC_LINK = V.LINK
												 AND IVD.ACTIVE = 1
											   ORDER BY IVD.NEW_DATE_END DESC),
											  V.DATE_END))
					                    THEN (ISNULL((SELECT top 1 (CASE
											    WHEN IVD.NEW_DATE_END > V.DATE_END
												THEN IVD.NEW_DATE_END
											    ELSE  V.DATE_END
											END)
					 				  FROM ITEM_VACATION_DIS IVD
									  WHERE IVD.VAC_LINK = V.LINK
										AND IVD.ACTIVE = 1
									  ORDER BY IVD.NEW_DATE_END DESC),
									 V.DATE_END))
							ELSE IVB.DATE_BREAK - 1
						     END) 
					FROM ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = V.LINK
					      AND IVB.ACTIVE = 1
					ORDER BY IVB.DATE_BREAK DESC), 
         			(ISNULL((SELECT top 1 (CASE
								   WHEN IVD.NEW_DATE_END > V.DATE_END
									THEN IVD.NEW_DATE_END
								   ELSE V.DATE_END
							       END)  
 						 FROM ITEM_VACATION_DIS IVD 
						 WHERE IVD.VAC_LINK = V.LINK
					      	       AND IVD.ACTIVE = 1
						 ORDER BY IVD.NEW_DATE_END DESC),
						V.DATE_END))
					) > @varKSDateEnd 
				THEN @varKSDateEnd  
                    	ELSE ISNULL((SELECT top 1 (CASE
						       WHEN IVB.DATE_BREAK - 1 > (ISNULL((SELECT top 1 (CASE
													    WHEN IVD.NEW_DATE_END > V.DATE_END
														THEN IVD.NEW_DATE_END
													    ELSE V.DATE_END
													END)  
 											  FROM ITEM_VACATION_DIS IVD
                    									  WHERE IVD.VAC_LINK = V.LINK
												AND IVD.ACTIVE = 1
											  ORDER BY IVD.NEW_DATE_END DESC),
											 V.DATE_END)) 
                   					    THEN (ISNULL((SELECT top 1 (CASE
											    WHEN IVD.NEW_DATE_END > V.DATE_END
											       THEN IVD.NEW_DATE_END
											    ELSE V.DATE_END
										        END)
	 								  FROM ITEM_VACATION_DIS IVD
									  WHERE IVD.VAC_LINK = V.LINK
									        AND IVD.ACTIVE = 1
									  ORDER BY IVD.NEW_DATE_END DESC),
								         V.DATE_END)) 
							ELSE IVB.DATE_BREAK - 1
						   END)
				     FROM ITEM_VACATION_BREAK IVB
				     WHERE IVB.VAC_LINK = V.LINK
					   AND IVB.ACTIVE = 1
				     ORDER BY IVB.DATE_BREAK DESC),
				    ISNULL((SELECT top 1 (CASE
							      WHEN IVD.NEW_DATE_END > V.DATE_END
								  THEN IVD.NEW_DATE_END
							      ELSE V.DATE_END
							  END)  
 					    FROM ITEM_VACATION_DIS IVD 
					    WHERE IVD.VAC_LINK = V.LINK
						  AND IVD.ACTIVE = 1
					    ORDER BY IVD.NEW_DATE_END DESC),
					   V.DATE_END))
		 END),
	[DOC] = 2
FROM #item_vacation v inner join dbo.VACATION_VID VV
     on V.TYPE_LINK = VV.LINK
	inner join #empl E on E.link = V.EMPL_LINK
WHERE	
	V.ACTIVE = 1 
	AND (V.DATE_BEGIN BETWEEN @varKSDateBegin AND @varKSDateEnd 
		OR V.DATE_END BETWEEN @varKSDateBegin AND @varKSDateEnd 
		OR ((V.DATE_BEGIN<@varKSDateBegin) AND (V.DATE_END>@varKSDateEnd))
		OR V.LINK IN (SELECT VAC_LINK FROM VACATION_DIS WHERE EMPL_LINK = V.EMPL_LINK AND ACTIVE = 1 AND NEW_DATE_END > @varKSDateBegin )
	)
UNION
-- КОМАНДИРОВКИ --
SELECT 
	T.EMPL_LINK,
	[TYPE] 	= KV.TYPE_LINK,
	[PRIOR] = (SELECT PRIORITET FROM dbo.TYP_DAYS WHERE LINK = KV.TYPE_LINK),
	[HOUR] 	= (SELECT HOUR FROM dbo.TYP_DAYS WHERE LINK = KV.TYPE_LINK),
	[DATE_1] = (CASE WHEN [DATE_BEGIN]<@varKSDateBegin THEN @varKSDateBegin ELSE [DATE_BEGIN] END),
	[DATE_2] = (CASE WHEN (ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > T.DATE_END THEN ITL.NEW_DATE_END ELSE T.DATE_END END)
				 FROM ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = T.LINK AND ITL.ACTIVE = 1),T.DATE_END))> @varKSDateEnd 
				 THEN @varKSDateEnd ELSE 
				(ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > T.DATE_END THEN ITL.NEW_DATE_END ELSE T.DATE_END END)
				 FROM ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = T.LINK AND ITL.ACTIVE = 1),T.DATE_END)) END),
	[DOC]= 3
FROM dbo.item_travel T inner join dbo.KOMAND_VID KV on t.type_link = KV.LINK
	inner join #empl E on E.link = T.EMPL_LINK
WHERE T.ACTIVE = 1 
	AND (T.DATE_BEGIN BETWEEN @varKSDateBegin AND @varKSDateEnd OR T.DATE_END BETWEEN @varKSDateBegin AND @varKSDateEnd OR
	((T.DATE_BEGIN<@varKSDateBegin) AND(T.DATE_END>@varKSDateEnd)) )
)  TAB
/*
-- ****************************************************** --
-- ************** ДОБАВЛЕНО 25.11.2008 ****************** --
-- *********** ВАСИЛЬЕВ ДМИТРИЙ ВАДИМОВИЧ *************** --
-- ПРОДЛЕНИЕ ОТПУСКА ПРИ ОТЗЫВЕ ОТПУСКА НА НЕСКОЛЬКО ДНЕЙ --
-- ****************************************************** --
DECLARE	@varKSlinkEmpl INT								-- ССЫЛКА НА СОТРУДНИКА
DECLARE @DATE_BN DATETIME								-- дата начала продления отпуска
DECLARE @DATE_EN DATETIME								-- дата окончания продления отпуска
DECLARE @DATE_BR DATETIME								-- дата отзыва из отпуска на несколько дней
DECLARE @BREAK_WORK_DAYS INT							-- количество календарных дней отзыва
DECLARE @LEN_KAL_DAYS INT								-- количество календарных дней продления отпуска
--
SELECT	LINK
INTO	#EMPL_TEMP
FROM	#EMPL
WHILE EXISTS(SELECT * FROM #EMPL_TEMP) BEGIN
	SELECT	TOP 1 @varKSlinkEmpl = LINK FROM #EMPL_TEMP	
	--
	IF EXISTS(SELECT IVB.*													-- если существует приказ об отзыве
		  FROM   ITEM_VACATION IV LEFT JOIN ITEM_VACATION_BREAK IVB			-- из отпуска НА НЕСКОЛЬКО ДНЕЙ
			 ON IVB.VAC_LINK = IV.LINK
		  WHERE  ISNULL(IVB.BREAK_WORK_DAYS,0) != 0							-- количество дней отзыва > 0
			 AND IVB.EMPL_LINK = @varKSlinkEmpl								-- на определенного сотрудника
			 AND IVB.ACTIVE = 1												-- утвержденный приказ
			 AND IVB.DATE_BREAK BETWEEN @varKSDateBegin AND @varKSDateEnd)	-- входящий в период расстановки табеля
	 BEGIN
		--
		SELECT	TOP 1
			@DATE_BR = DATE_BREAK,
			@BREAK_WORK_DAYS = BREAK_WORK_DAYS,
			@LEN_KAL_DAYS = LEN_KAL_DAYS,
			@DATE_EN = IV.DATE_END
		FROM	ITEM_VACATION_BREAK IVB LEFT JOIN ITEM_VACATION IV ON IV.LINK = IVB.VAC_LINK
		WHERE	ISNULL(IVB.BREAK_WORK_DAYS,0) != 0
			AND IVB.EMPL_LINK = @varKSlinkEmpl	
			AND IVB.ACTIVE = 1
			AND IVB.DATE_BREAK BETWEEN @varKSDateBegin AND @varKSDateEnd
		--

		SET @DATE_BN = @DATE_BR + @BREAK_WORK_DAYS  
		SET @DATE_EN = @DATE_EN + @LEN_KAL_DAYS
		--
	 	INSERT	INTO #varKSS ([LINK_EMPL],[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC])
	  	SELECT	@varKSlinkEmpl,[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC] FROM
	 	(
	  	SELECT	[TYPE]   = VV.TYPE_LINK,
	  			[PRIOR]  = (SELECT PRIORITET FROM dbo.TYP_DAYS WHERE LINK = VV.TYPE_LINK),
	  			[HOUR]   = (SELECT HOUR FROM dbo.TYP_DAYS WHERE LINK = VV.TYPE_LINK),
	  			[DATE_1] = @DATE_BN,
	  			[DATE_2] = @DATE_EN,
	  			[DOC]    = 2
	 	FROM	ITEM_VACATION IV LEFT JOIN ITEM_VACATION_BREAK IVB
	 		ON IVB.VAC_LINK = IV.LINK LEFT JOIN VACATION_VID VV
	 		ON IV.TYPE_LINK = VV.LINK
		WHERE	ISNULL(IVB.BREAK_WORK_DAYS,0) != 0
			AND IVB.EMPL_LINK = @varKSlinkEmpl
			AND IVB.ACTIVE = 1			
			AND IVB.DATE_BREAK BETWEEN @varKSDateBegin AND @varKSDateEnd
		) TAB
	END
	--
	DELETE FROM #EMPL_TEMP WHERE LINK = @varKSlinkEmpl
END
DROP TABLE #EMPL_TEMP
-- ****************************************************** --
-- ****************************************************** --
*/
IF EXISTS(SELECT * FROM #varKSS WHERE [TYPE] IS NULL)
	BEGIN
		DECLARE @varKSMesStr varchar(1000)
		SET @varKSMesStr = 'Формирование прервано! Не заполнен тип дня в одном из справочников: "Виды отпусков","Причины нетрудоспособности", "Виды командировок"!'+CHAR(13)+CHAR(10)+'Заполните справочники и запустите формирование табеля снова!'
		RAISERROR (@varKSMesStr,11,1)
 		RETURN 1005
	END

DECLARE @varKSG TABLE
(
 LINK_EMPL int,
 [DATE1] 	datetime,
 [DAY] 		int,
 [HOUR]  	numeric(6,2),
 [DAY_TIP]	int,
 [LINK_UP]	int,
 [PRIOR]	int,
 [LINK_WORK] int,	
 [LINK_WORK_TYPE] int,
 [DATE_BEG] DATETIME, 
 [DATE_END] DATETIME,
 [GRAPH_LINK] int,
 [num_stake] numeric(5,2)
 )		


DECLARE @LINK_OSN INT
SET @LINK_OSN= (Select TOP 1 LINK from TABEL_nastr2 where code = 'ОСН')

---Основное место
INSERT INTO @varKSG(LINK_EMPL, [DATE1],[DAY],[HOUR],[DAY_TIP],[LINK_UP],[PRIOR],[LINK_WORK], [LINK_WORK_TYPE], [DATE_BEG], [DATE_END], GRAPH_LINK, [num_stake])
SELECT	
		 E.LINK,
		 dbo.ConvertDMY2Date([DAY],@varKSMonth,@varKSYear) AS DATE1,
		 [DAY] = [DAY],
		 [HOUR] = [HOUR],
		 [DAY_TIP] = TD_LINK,
		 [LINK_UP] = 0,
		 [PRIOR] = PRIORITET,
		 [LINK_WORK] = NULL,
		 [LINK_WORK_TYPE] = @LINK_OSN,
		 [DATE_BEG] = DateAccept,
		 [DATE_END] = DateSack,
		 E.GRAPH_LINK,
		 E1.[num_stake]
FROM 
	dbo.KD_GRAPH_TABLE  GT
	inner join dbo.EMPL E on E.GRAPH_LINK = GT.LINK_GR
	inner join #empl E1 on E1.link = E.link
WHERE 
	[MONTH] = @varKSMonth AND [YEAR] = @varKSYear
	AND E.LINK NOT IN (Select link_empl from dbo.STO_TARIF_EMPL TE where TE.link_type = @LINK_OSN)

--Всевозможные совмещения
INSERT INTO @varKSG(LINK_EMPL, [DATE1],[DAY],[HOUR],[DAY_TIP],[LINK_UP],[PRIOR],[LINK_WORK], [LINK_WORK_TYPE], [DATE_BEG], [DATE_END], GRAPH_LINK, [num_stake])
SELECT	
		 E.link_empl,
		 dbo.ConvertDMY2Date([DAY],@varKSMonth,@varKSYear) AS DATE1,
		 [DAY] = [DAY],
		 [HOUR] = [HOUR],
		 [DAY_TIP] = TD_LINK,
		 [LINK_UP] = 0,
		 [PRIOR] = PRIORITET,
		 [LINK_WORK] = E.LINK, --сама работа
		 [LINK_WORK_TYPE] = E.LINK_TYPE, --Вид работы
		 [DATE_BEG] = DATE_BEGIN,
		 [DATE_END] = CASE WHEN ISNULL(E1.DATESACK, @varKSDateEnd) < ISNULL(DATE_END,@varKSDateEnd) THEN ISNULL(E1.DATESACK, @varKSDateEnd) ELSE ISNULL(DATE_END,@varKSDateEnd) END,
		 [GRAPH_LINK] = LINK_GRAPH,
		 E.[num_stake]
FROM 
	dbo.KD_GRAPH_TABLE  GT
	inner join dbo.STO_TARIF_EMPL E on E.LINK_GRAPH = GT.LINK_GR
	inner join #empl E1 on E1.link = E.link_empl
WHERE 
	[MONTH] = @varKSMonth AND [YEAR] = @varKSYear

---
DECLARE @varKSCurs CURSOR,
		@varKSCurType int,
		@varKSCurPrior int,
		@varKSCurHour numeric(6,2),
		@varKSCurDate1 datetime,				
		@varKSCurDate2 datetime,
		@varKSCurDoc	int,	
		@varKSCom int,
		@varKSBol int,
		@varKSOtp int,
		@link_empl int

SELECT @varKSCom = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_COM') AND SID IS NULL
SELECT @varKSBol = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_BOL') AND SID IS NULL
SELECT @varKSOtp = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_OTP') AND SID IS NULL

SET @varKSCom = ISNULL(@varKSCom,0)
SET @varKSBol = ISNULL(@varKSBol,0)
SET @varKSOtp = ISNULL(@varKSOtp,0)

SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT * FROM #varKSS 
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @link_empl, @varKSCurType,@varKSCurPrior,@varKSCurHour,@varKSCurDate1,@varKSCurDate2,@varKSCurDoc
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSCurDoc = 2	
		IF @varKSOtp = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11)
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	IF @varKSCurDoc = 1 
		IF @varKSBol = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11) 
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	IF @varKSCurDoc = 3 
		IF @varKSCom = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11) 
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	FETCH NEXT FROM @varKSCurs INTO @link_empl, @varKSCurType,@varKSCurPrior,@varKSCurHour,@varKSCurDate1,@varKSCurDate2,@varKSCurDoc

END
CLOSE @varKSCurs
DEALLOCATE @varKSCurs

--Проверка, чтобы за один и тот же день не было 2 табеля

SELECT @varKSYear AS Y, @varKSMonth AS M, @varKSLinkTab AS L
INTO #PAR

CREATE TABLE #TABOLD (LINK_EMPL INT, Y INT, M INT, D INT)

DECLARE @I INT, @SQL VARCHAR(8000)
SET @I = 1
WHILE @I <= 31
BEGIN
	SET @SQL = 
 + '
INSERT INTO #TABOLD (LINK_EMPL, Y, M, D)
SELECT DISTINCT T.LINK_EMPL, Y= YEAR(PERIOD), M = MONTH(PERIOD), D = ' + CONVERT(VARCHAR(3),@I) + '
FROM
	DBO.TABELS T INNER JOIN DBO.TABELS_W W ON T.LINK = W.LINK_UP
	INNER JOIN #empl E on E.link = T.LINK_EMPL
	INNER JOIN #PAR P ON 1=1
WHERE
	D' + CONVERT(VARCHAR(3),@I) + ' > 0
	AND
	YEAR(PERIOD) = P.Y AND MONTH(PERIOD) = P.M AND LINK_DOC <> P.L
'
	SET @I = @I + 1

	EXEC (@SQL)

END

DECLARE @END_DATE DATETIME
SET @END_DATE = (SELECT TOP 1 DATE FROM DBO.SDOC WHERE LINK = @varKSLinkTab)

DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

SELECT DISTINCT LINK_EMPL, G.LINK_WORK, G.LINK_WORK_TYPE, G.DATE1, G.[DAY], Convert(NUMERIC(5,2), DBO.MINUTES_TO_NUM(DBO.NUM_TO_MINUTES(G.[HOUR],@ISMINUTES) * COALESCE(G.NUM_STAKE,0) ,@ISMINUTES)) AS HOURS,
		 G.DAY_TIP,G.LINK_UP,D.SYMB AS SYMB,D.NAME AS NAME,
		D.DOP_TAB, G.DATE_BEG, G.DATE_END, G.GRAPH_LINK, E.ETS_RAZR
FROM 
	@varKSG G 
	inner join dbo.KD_TYP_DAYS D on G.DAY_TIP =  D.LINK 
	inner join #empl E on E.link = G.LINK_EMPL
WHERE 
	G.DATE1 BETWEEN DATE_BEG AND COALESCE(DATE_END,@varKSDateEnd)
	AND NOT EXISTS (SELECT LINK_EMPL FROM #TABOLD O WHERE O.LINK_EMPL = G.LINK_EMPL AND O.Y = YEAR(G.DATE1) AND O.M = MONTH(G.DATE1) AND O.D = DAY(G.DATE1))
	AND (G.DATE1 <= @END_DATE OR @END_DATE IS NULL)

ORDER BY 1





GO


GRANT EXECUTE ON dbo.[SA_TABEL_FILL_EMPL] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS OFF
GO
SET LOCK_TIMEOUT -1
GO

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

CREATE procedure [dbo].[RT_GET_KBK_DIFF]
    @CodeDict varchar(250)
AS

if len(isnull(@CodeDict,''))=0 begin
	select 0,0 as [checked],'','','',null as [date_begin],null as [date_end]
	return 1
end

declare @fed_dict_code varchar(250),
		@is_ist tinyint

set @is_ist = case when left(@CodeDict,3)='ИСТ' then 1 else 0 end
set @fed_dict_code = left(ltrim(@CodeDict),len(@CodeDict)-5)


select 
	link,
	1 as [checked],
	[code],
	[cname],
	[name],
	cast([date_begin] as datetime) as [date_begin],
	cast([date_end] as datetime) as [date_end]
from #bks_diction_data as bks
WHERE 
NOT EXISTS(SELECT * FROM dbo.[RO_KBK_HIST_VIEW] k
           WHERE K.code_form IN ( @fed_dict_code, @CodeDict)
               AND K.code = bks.code
               --AND isnull(K.end_date, '30000101') >= isnull(bks.date_end, '30000101')
               AND  (isnull(bks.date_begin, '19000101') <=isnull(k.end_date, '30000101') AND isnull(bks.date_end, '30000101') >=isnull(k.begin_date, '19000101')) 
              -- AND REPLACE(left(ltrim(rtrim(bks.cname)),250), ' ', '') = REPLACE(K.name, ' ', '')
              /* AND REPLACE(bks.name, ' ', '') = REPLACE(K.long_name, ' ', '')*/
)

return 1
GO
grant execute on [dbo].[RT_GET_KBK_DIFF] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO
SET LOCK_TIMEOUT 30000
GO



GO

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

GO

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

CREATE PROCEDURE dbo.RT_CALC_0503125M_ITOG_2011
@Void int,--@table int,
@LSF int
AS

if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#res]')) begin
select 0
return
end

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
@cSource char(1),
@cSinth char(3),
@cAnalit char(2),
@cSGU char(3),
@iLinkAccount int,
@dBeginDate datetime,
@dEndDate datetime,
@iThisDep int,
@iCorrDep int,
@i int,
@j int,
@jj int,
@iLink_col int,
@code_row varchar(50),
@float_val numeric(20,4),
@str_val varchar(250),
@cVidForm varchar(250),
@cVidFormCode int,
@iLink_Table int,
@code_form varchar(50)

declare @table2 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(8), KBK varchar(50), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(9), dnd tinyint, link varchar(254), key_prov
int, tabsource tinyint)

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ

set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
set @cVidFormCode = -1
select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

select @code_form = rtrim(code) from dbo.report_forms where link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF)

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dBeginDate = Begin_Date from dbo.report_saved_forms where link_saved_form = @LSF
-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate - (datepart(dd,@dBeginDate)) end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')
set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

set @j = 0
declare @table tinyint
set @table = 1
while @table !> 3 begin
select @iLink_Table = link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table
if @table in (1,3) begin
insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
substring(coalesce(rd2.Str_Val,''),1,3),
substring(coalesce(rd3.Str_Val,''),1,8),
substring(coalesce(rd4.Str_Val,''),1,2),
case
WHEN  right(rtrim(@cAccount),8) in ('30406000')
THEN '00000000000000000'
when @table = 1 and right(rtrim(@cAccount),8) in ('20551560','20551660')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'0000000000',14)
when @table = 1 and right(rtrim(@cAccount),8) in ('40110180','40110151','40120251','20651560','20651660')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
when @table = 1 and right(rtrim(@cAccount),8) not in ('40110180','40110151','40120251','20551560','20551660','20651560','20651660')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),3)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111000','30131000','30141000','30151000','30121000')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),14)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111810','30131810', '30111710')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
else right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),4)+'00000000000000',14)
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN substring(coalesce(rd9.Str_Val,''),2,1) IN ('1', '2') AND substring(coalesce(rd9.Str_Val,''),2,3) <> '104'
THEN case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
THEN LEFT(@cAccount,6) + '730'
ELSE LEFT(@cAccount,6) + '830' END
ELSE case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END END

ELSE @cAccount
END,
isnull(rd7.Float_Val,0.00),
isnull(rd8.Float_Val,0.00),
substring(coalesce(rd9.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) end,
srows.Code_Row,
null,
@table
from (
select Code_Row from #report_dinamics
where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
group by Code_Row
) as srows
left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10
and Link_Table = @iLink_Table)
end
else begin
insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
substring(coalesce(rd2.Str_Val,''),1,3),
substring(coalesce(rd3.Str_Val,''),1,8),
substring(coalesce(rd4.Str_Val,''),1,2),
--right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) + '0000000000',
right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) +
case
when (  (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151') or
(@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') or
(@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or
(@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or
(@cSinth = '207' and @cAnalit = '31' and @cSGU = '540') or
(@cSinth = '207' and @cAnalit = '21' and @cSGU = '540') or
(@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('710','810')) or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '830'))
then right('0000000'+rtrim(coalesce(rd7.Str_Val,'')),7) + '000'
else '0000000000'
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN substring(coalesce(rd9.Str_Val,''),2,1) IN ('1', '2') AND substring(coalesce(rd9.Str_Val,''),2,3) <> '104'
THEN case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
THEN LEFT(@cAccount,6) + '730'
ELSE LEFT(@cAccount,6) + '830' END
ELSE case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END END

ELSE @cAccount
END,
isnull(rd9.Float_Val,0.00),
isnull(rd10.Float_Val,0.00),
substring(coalesce(rd11.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) end,
srows.Code_Row,
null,
@table
from (
select Code_Row from #report_dinamics
where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
group by Code_Row
) as srows
left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
left join #report_dinamics as rd11 on rd11.link_sf = @LSF and rd11.Code_Row = srows.Code_Row and 11 = (select Orders from dbo.report_coloumns where link_col = rd11.link_col) and rd11.link_col = (select link_col from dbo.report_coloumns where Orders = 11
and Link_Table = @iLink_Table)
left join #report_dinamics as rd12 on rd12.link_sf = @LSF and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12
and Link_Table = @iLink_Table)
end
set @table = @table + 1
end
update @table2 set link = cast(nn as varchar(10)), key_prov = nn -- для уникальности записей собраных с трёх таблиц. Ибо пользователю доверять нельзя!

update @table2  -- устанавливаем признак Денежные/Неденежные рассчёты | неденежные считаем все с СГУ 310,320,330,340 и сотые корреспондирующие счета
set dnd = case
when dnd not in (1,0)
then
(case
when
right(left(korr_acc,6),5) in ('21002','30405') or
right(korr_acc,3) in ('510','610')
then 1 -- денежные рассчёты
else 0 -- не денежные рассчёты
end)
else dnd
end

select @j = count(*) from @table2

if (@j > 0)begin -- если кол-во полученных строк больше нуля, то...
-- формирование итоговых строчек для 304.04 счёта
--select * from @table2
-- 30404000 ####################################################################################################

if (@cSinth = '304' and (@cAnalit = '04' OR @cAnalit = '06') and @cSGU = '000') begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,link)
select KBK,Code_Acc,coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40120241 ####################################################################################################

-- формирование итоговых строчек для счёта 40120241
if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '241'/*@cVidFormCode = 2*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,KBK,Code_Acc,summa_db,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40110180 ####################################################################################################

-- формирование итоговых строчек для счёта 40110180
if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '180' /*and @cVidFormCode = 3*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_db),0)) > 0.0 then -coalesce(SUM(summa_db),0) else coalesce(SUM(summa_kr),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20731540 ####################################################################################################

-- формирование итоговых строчек для счётов 20702540
if (@cSinth = '207' and @cAnalit in ('11','21','31') and @cSGU = '540') begin
-- итоговые. в том числе по номеру (коду) счета
/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc*/
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp, el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40120251 ####################################################################################################

if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') begin
-- итоговые. в том числе по номеру (коду) счета
/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc*/
if @code_form like '425_' begin
insert into @table2 (/*ppp,*/el_bud,okato,Code_Acc,summa_db,link)
select /*ppp,*/el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by /*ppp, */el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
--insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link
from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link
from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20651560(660) ####################################################################################################

if (@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660'))begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp, el_bud,okato,Code_Acc,summa_db,link)
select ppp, el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp, el_bud,okato,Code_Acc
end
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr) ,0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30212830 ####################################################################################################

if (@cSinth = '302' and @cAnalit = '51' and @cSGU = '830')begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)     select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20551000,20651000,20731000 ####################################################################################################

if (
(@cSinth = '205' and @cAnalit = '51' and @cSGU = '000' /*and @cVidFormCode = 9*/)-- or @cVidFormCode = 11)) or
or (@cSinth = '206' and @cAnalit = '51' and @cSGU = '000'/*and @cVidFormCode = 9*/)-- or @cVidFormCode = 5)) or
or (@cSinth = '207' and @cAnalit = '31' and @cSGU = '000'/*and @cVidFormCode = 9*/)
or (@cSinth = '207' and @cAnalit = '21' and @cSGU = '000')
or (@cSinth = '207' and @cAnalit = '11' and @cSGU = '000'))begin-- or @cVidFormCode = 6 or @cVidFormCode = 13)))begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where right(link,2) = 'ИП'
end
end

-- 301X1000 ####################################################################################################
if (@cSinth = '301' and @cAnalit in ('11','21','31','41') and @cSGU = '000') or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '000') begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,KBK,Code_Acc
-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where right(link,2) = 'ИП'
end
end

-- 40110151 ####################################################################################################
-- формирование итоговых строчек для счётов 40101151
if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151' /*and @cVidFormCode = 10*/) begin
--  -- сначала извращаемся над кбк в соответствии с письмом от 19.12.2008
--  update @table2
--  set KBK = case when tabsource = 1 then left(KBK,6)+'00000000000' else KBK end
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end

-- подитоговые для денежных
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20551560(660) ####################################################################################################

if (@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 1     group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20731640,20711640 ####################################################################################################

-- формирование итоговых строчек для счётов 20702640
if ((@cSinth = '207' and @cAnalit = '31' and @cSGU = '640') or
(@cSinth = '207' and @cAnalit = '11' and @cSGU = '640'))begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end


-- 30111810 ####################################################################################################
-- формирование итоговых строчек для счётов 30101710
if (@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('810')) begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30111710 ####################################################################################################
-- формирование итоговых строчек для счётов 30101710
if (@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('710')) begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- формирование итоговых строчек для счётов 021100560, 021200560
if ((@cSinth = '211' or @cSinth = '212') and @cAnalit = '00' and (@cSGU = '560' or @cSGU = '660') /*and @cVidFormCode = 15*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (okato,Code_Acc,summa_db,link)
select okato, Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
group by okato, Code_Acc
-- итоговые по неденежным
insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30800730,30900730,30800830,30900830 ####################################################################################################

-- формирование итоговых строчек для счётов 030800730 и 030900730
if ((@cSinth = '308' or @cSinth = '309') and @cAnalit = '00' and (@cSGU = '730' or @cSGU = '830') /*and @cVidFormCode = 16*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (okato,Code_Acc,summa_kr,link)
select okato, Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
group by okato, Code_Acc
-- итоговые по неденежным
insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end
end

delete from @table2 where right(link,1) like '[0-9]'
----------------------------------------- Делаем кодовое значение более коротким (на базе nn)
select @j = MIN(nn) from @table2

update @table2
set link = rtrim(cast((nn - @j) as varchar)) + right(link,2)
where right(link,2) in ('ИД','ИН')
-----------------------------------------
if not exists(select * from @table2 where right(link,2) = 'ИД')
insert into @table2 (link) values ('ИД')

if not exists(select * from @table2 where right(link,2) = 'ИН')
insert into @table2 (link) values ('ИН')

if not exists(select * from @table2 where rtrim(link) = 'итог_денежные_рассчёты')
insert into @table2 (link) values ('итог_денежные_рассчёты')

if not exists(select * from @table2 where rtrim(link) = 'итог_неденежные_рассчёты')
insert into @table2 (link) values ('итог_неденежные_рассчёты')

select @j = MIN(nn) from @table2
select @jj = MAX(nn) from @table2

delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги
delete from #report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги

while @j <= @jj begin
set @i = 1
while @i < 9 begin
select @iLink_col = link_col from dbo.report_coloumns where Orders = @i and Link_Table = (select link_table from dbo.report_tables where Orders = 4/*итоги*/ and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF))
select
@code_row = rtrim(link),
@float_val =
(case when @i in (1,2,3,4,5,8) then 0.0000
when @i = 6 then coalesce(summa_db,0.0000)
when @i = 7 then coalesce(summa_kr,0.0000)
end),
@str_val =
(case when @i in (6,7) then ''
when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
when @i = 2 then cast(coalesce(ppp,'') as varchar (250))
when @i = 3 then cast(coalesce(okato,'') as varchar (250))
when @i = 4 then cast(coalesce(el_bud,'') as varchar (250))
when @i = 5 then cast(coalesce(KBK,'')+coalesce(Code_acc,'') as varchar (250))
when @i = 8 then cast(coalesce(korr_acc,'') as varchar (250))
end)
from @table2
where nn = @j

if @code_row in ('ИД','ИН','итог_денежные_рассчёты','итог_неденежные_рассчёты') and @float_val = 0.0
insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val) values (@LSF,@iLink_col,@code_row,@float_val,@str_val)

insert into #report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
values (@LSF,@iLink_col,@code_row,@float_val,@str_val)


set @i = @i + 1
end
set @j = @j + 1
end
----------------------------------------------------------------------------
select 0


GO


GRANT EXECUTE ON dbo.[RT_CALC_0503125M_ITOG_2011] TO PUBLIC

GO


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


GO
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_12]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_EXPORT_BR_12]
GO





/*
© Кейсистемс (Keysystems), 2006
Выгрузки Лимитов БО и Ассигнований 
*/




CREATE          PROCEDURE dbo.FB_EXPORT_BR_12
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''
AS
DECLARE @iDepLink	int,
	@iPeriod	tinyint,
	@iPeriodType	tinyint


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


-- Блок FROM
SELECT	budg 	as KOD_BP, 
		name 	as NM_BP, 
		0 as link,
		0 as link_up
FROM DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink

-- Блок TO
SELECT '' as KOD_BP,
		'' as NM_BP,
		0 as link,
		0 as link_up
FROM dbo.DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink
	

if @cObjCode like '%LIMIT%'
	select  @iPeriod = MAX(FIN_LIM_PER) - 1, @iPeriodType = MAX(FIN_LIM_TYPE) from workmode 
else
begin	
	select  @iPeriod = FIN_SMETA_PER - 1 from workmode
	set @iPeriodType = 0
end

-- Блок RL

select 	PERIOD		= case @iPeriod when 2 then 'M' when 1 then 'Q' else 'Y' end,
	TYPE_RL 	= convert(varchar(1),case  when F.F2=1 then 2 else F.CHANGE end),
	VID_RL		= case  when F.SVOD = 1 then '0' else '1' end,
	NUMBER		= F.NUMBER,
	DATE		= F.DATE,
	DATE_EXEC	= F.DATE_PROV,
	KOD_RBS		= F.DEP_CODE,
	NAME_RBS	= F.DEP_NAME,
	ACC_NUM		= F.BUDG_ACC,
	ACC_SEND	= F.ACC_CODE,
	KOD_BP		= case F.SVOD when 0 then F.FDEP_CODE else '' end,
	NAME_BP		= case F.SVOD when 0 then F.FDEP_NAME else '' end,
	ACC_RCP		= case F.SVOD when 0 then F.FACC_CODE else '' end,
	ACC_SEND_KIND = '',
	ACC_RCP_KIND = '',
	IST		= '',
	S.SUM_YEAR01,
	S.SUM_YEAR02,
	S.SUM_YEAR03,
	PRIM		= '',
	VID_IZM		= '',
	NAME_BUD	= D.BUDG_NAME,
	DOP_UKAZ	= '',
	DATE_SIGN	= null,
	LINK		= F.LINK,
	LINK_UP		= F.LINK

from dbo.FINANS_LIMIT_AND_ASSIGN F
left join dbo.BB_DEP_ACC_DOP(null) D on D.ACC_LINK = F.FACC_LINK
inner join (select LINK_UP, SUM_YEAR01 = SUM(P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10 + P11 + P12), SUM_YEAR02 = SUM(Y2),  SUM_YEAR03 = SUM(Y3) from FINANSE GROUP BY LINK_UP) S on S.LINK_UP = F.LINK
where F.link in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())


select 	LINK		= F.LINK,
		LINK_UP		= F.LINK,
		NOM_OSNOV	= O.NUMBER,
		DATE_OSNOV	= O.DATE,
		OSNOV		= O.[TYPE],
		PRIM		= O.COMMENT
from dbo.FINANSE_HEAD F
inner join dbo.BD_OSNOV O on F.LINK_OSNOV = O.LINK
where exists (select * from dbo.BufferGetTableByID(@cBuffId) where LINK = F.link)


-- Блок RLST
select	TYPE_KBK = case KBK.TYPE when 1 then '10'
								 when 2 then '20'
								 when 4 then '31'
								 when 8 then '32'
								 else '' end,
		KBK = left(rtrim(replace(KBK.CODE,'.','')) + EKR.CODE,20),
		KBK_IST_RF = '',
		ADD_KLASS	= DCL.CODE,
		[LOCAL]		= '',
		[SERVICE] = '',
		PURPOSE = '',
		PROGRAM = '',

		SUM1		= case when @iPeriodType = 1 and FH.PER_NUM = 1 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 1 and @iPeriodType = 0 then FT.P1 + FT.P2 + FT.P3
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P1
					else 0 end,
		SUM2		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P4 + FT.P5 + FT.P6
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P2
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 2 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 4 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM3		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P7 + FT.P8 + FT.P9
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P3
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 3 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM4		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P4
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 4 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM5		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P5 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 5 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM6		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P6 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 6 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM7		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P7 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM8		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P8 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 8 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM9		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P9 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 9 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM10		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P10 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM11		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P11
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 11 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM12		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P12 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 12 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM_YEAR01	= case @iPeriod when 0 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12 else 0 end,
		SUM_YEAR02	= FT.Y2,
		SUM_YEAR03	= FT.Y3,
		LINK		= FT.LINK,
		LINK_UP		= FT.LINK_UP
from dbo.FINANSE FT
inner join dbo.FINANSE_HEAD FH on FH.LINK = FT.LINK_UP
left join dbo.BI_DICTION_VKR VKR on VKR.LINK_KBK = FT.VKR 
left join dbo.KL_KBK KBK on KBK.LINK = FT.VKR --and KBK.TYPE <> 1 
left join dbo.DOP_CLASSIF DCL on DCL.LINK = FT.DOP_CL 
left join dbo.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 all on FB_EXPORT_LB to public
GO

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

GO
CREATE PROCEDURE dbo.BK_PUSH_BUF_ACCT_BY_TO
	(@strBUF_NAME	VARCHAR (100),
	@intLINK_TO	INT,
	@intDB_KT	TINYINT = 0,
	@intCLEAR_PREVIUS	INT = 1)
AS
BEGIN
	DECLARE @strBUFER_TEMP VARCHAR (100)

	IF ISNULL (@strBUF_NAME, '') = ''
		RETURN 0
	
	IF ISNULL (@intCLEAR_PREVIUS, 1) = 1
		EXEC dbo.BUFFERCLEAR @strBUF_NAME  
	
	DECLARE @TAB_ACCT TABLE (LINK_ACCT INT)

	EXEC dbo.GetRandSTR 20, @strBUFER_TEMP OUTPUT

	SET @strBUFER_TEMP = @strBUF_NAME + '_' + @strBUFER_TEMP

	INSERT INTO dbo.BUFFER ([ID], LINK)
	SELECT @strBUFER_TEMP,
		GAP.ACCOUNT
	FROM dbo.G_PROV1 G1
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
	INNER JOIN dbo.G_PROV_AP GAP ON (GAP.LINK_UP = G2.LINK
		AND GAP.DB_KR = @intDB_KT)
	WHERE G1.LINK = @intLINK_TO
	GROUP BY GAP.ACCOUNT

	INSERT INTO @TAB_ACCT
	SELECT *
	FROM dbo.AccountsSubtreeByAccounts (@strBUFER_TEMP)
	GROUP BY LINK

	EXEC dbo.BUFFERCLEAR @strBUFER_TEMP

	INSERT INTO dbo.BUFFER ([ID], LINK)
	SELECT @strBUF_NAME,
		LINK_ACCT 
	FROM @TAB_ACCT

/*	SELECT SA.LINK,
		SA.CODE
	FROM dbo.BufferGetTableByID (@strBUF_NAME) B
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = B.LINK
*/
-- EXEC dbo.BK_PUSH_BUF_ACCT_BY_TO 'BV_ACCOUNTS_LINK', 84119, 1

	RETURN 0		
END

GO


GRANT EXECUTE ON dbo.[BK_PUSH_BUF_ACCT_BY_TO] TO PUBLIC

GO


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


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

GO

CREATE   PROCEDURE [dbo].SS_SZV63_EXPORT (
	@YEAR1 INT,				/*Год*/
	@nOption int, /*Тип сведений*/
	@nPach varchar(5),
	/*Фильтры*/
	@nFilterLink INT
	/*,
	@cVal1 char(1), @nOtborLink1 int /* Отбор сотрудников */,
	@cVal2 char(1), @nOtborLink2 int /* Отбор физических лиц */,
	@cVal3 char(1), @nOtborLink3 int /* Отбор подразделений */ 
	*/
) AS


	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_EMPLOYERS'))
	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_FL'))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE='QUERY_OTBOR_CHECK'))
	DECLARE @cVal3 char(1), @nOtborLink3 int	/* Отбор подразделений */
	SELECT @nOtborLink3 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE='OTBOR_QUERY_SQL_SUBDIV'))
	SELECT @cVal3 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink3 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE='QUERY_OTBOR_CHECK'))



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

SET NOCOUNT ON

-- Курсор СЗВ-6-3
CREATE TABLE #SZV63(ID int, NUM_PACH INT, LINK int,	FM varchar(50), IM varchar(50),	OT varchar(50), INSUR_NUM varchar(14),
							 [YEAR] varchar(4), CODE VARCHAR(20),	T_DOGOV	int, REG_NOM_PF VARCHAR(15), INN varchar(12), KPP varchar(9), OKPO varchar(20),	
							 DCOUNT int, PERS_INN VARCHAR(12), [TYPE] int, DEP_NAME varchar(256), DEP_FN varchar(2000), NUM_STR int, 
							 DATE_DOC datetime, s1_1 NUMERIC(18,2), s1_2 NUMERIC(18,2), s1_3 NUMERIC(18,2), s1_4 NUMERIC(18,2), s1_5 NUMERIC(18,2), 
							 s1_6 NUMERIC(18,2), s1_7 NUMERIC(18,2), s1_8 NUMERIC(18,2), s1_9 NUMERIC(18,2), s1_10 NUMERIC(18,2), s1_11 NUMERIC(18,2),
							 s1_12 NUMERIC(18,2), s2_1 NUMERIC(18,2), s2_2 NUMERIC(18,2), s2_3 NUMERIC(18,2), s2_4 NUMERIC(18,2), s2_5 NUMERIC(18,2),
							 s2_6 NUMERIC(18,2), s2_7 NUMERIC(18,2), s2_8 NUMERIC(18,2), s2_9 NUMERIC(18,2), s2_10 NUMERIC(18,2), s2_11 NUMERIC(18,2),
							 s2_12 NUMERIC(18,2))
							 
INSERT INTO #SZV63(	ID, NUM_PACH,LINK,FM,IM,OT,INSUR_NUM,[YEAR],CODE,T_DOGOV,REG_NOM_PF,INN,KPP,
OKPO,DCOUNT,PERS_INN,TYPE,DEP_NAME,DEP_FN,NUM_STR,DATE_DOC,s1_1,s1_2,s1_3,s1_4,s1_5,s1_6,s1_7,
s1_8,s1_9,s1_10,s1_11,s1_12,s2_1,s2_2,s2_3,s2_4,s2_5,s2_6,s2_7,s2_8,s2_9,s2_10,s2_11,s2_12)
exec dbo.SS_PRINT_SZV63 @YEAR1 , @nOption, @nPach, @nFilterLink, @cVal1, @nOtborLink1,	@cVal2, @nOtborLink2, @cVal3, @nOtborLink3, 1

CREATE TABLE #ADV64(NUM_PACH INT, CODE VARCHAR(20),	T_DOGOV	int, [YEAR] varchar(4), REG_NOM_PF VARCHAR(15), INN varchar(12), KPP varchar(9), OKPO varchar(20),	
							 [TYPE] int, DEP_NAME varchar(256), DEP_FN varchar(2000), 
							 DATE_DOC datetime, s1_all NUMERIC(18,2), s2_all NUMERIC(18,2),DCOUNT int, )

INSERT INTO #ADV64(NUM_PACH,CODE,T_DOGOV,[YEAR],REG_NOM_PF,INN,KPP,OKPO,[TYPE],DEP_NAME,DEP_FN,DATE_DOC,s1_all,s2_all,DCOUNT)
exec dbo.SS_PRINT_SZV63 @YEAR1 , @nOption, @nPach, @nFilterLink, @cVal1, @nOtborLink1,	@cVal2, @nOtborLink2, @cVal3, @nOtborLink3, 2

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

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

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

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

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

-- ШАПОЧНАЯ ЧАСТЬ ФАЙЛА
-----

SET @Cur1 = CURSOR FORWARD_ONLY


FOR select NUM_PACH from #ADV64 ORDER BY NUM_PACH

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

	SELECT @lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END) + '-ORG-' + ltrim(rtrim(REG_NOM_PF)) + '-DCK-' + REPLACE(STR(COALESCE(NUM_PACH,1),5),' ','0') + '-DPT-000000-DCK-00000.XML' 
	FROM  #adv64 WHERE NUM_PACH = @NGROUP

	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	 SELECT @lcFNAME, 'OEM' --Имя файла 
			UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>' 
			UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>' 
	 		 UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
			 UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>' 
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>' 
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>' 
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>' 
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> ' 
			 UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>' 
			 
			 UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">' 

	DECLARE @DOCCOUNT INT 
	set @DOCCOUNT = (select count(*) from #SZV63 WHERE NUM_PACH = @NGROUP )
	--- Для трудовых договоров по рабочим 
	 --
	 INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	 SELECT @lcFNAME , 
	  SPACE(2) + '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ>' 
		+ SPACE(3) + '<НомерВпачке>1</НомерВпачке>' 
		+ SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>'
		+ SPACE(3) + '<СоставительПачки>'
			+ SPACE(4) + '<НалоговыйНомер>'
				+ SPACE(5) + '<ИНН>' + RTRIM(LTRIM(COALESCE(INN,''))) + '</ИНН>'
				+ SPACE(5) + '<КПП>' + RTRIM(LTRIM(COALESCE(KPP,''))) + '</КПП>'
			+ SPACE(4) + '</НалоговыйНомер>'
			+ SPACE(4) + '<КодЕГРЮЛ>' + @EGRUL + '</КодЕГРЮЛ>'
			+ SPACE(4) + '<НаименованиеОрганизации>' + UPPER(RTRIM(LTRIM(COALESCE(DEP_FN,'')))) + '</НаименованиеОрганизации>'
			+ SPACE(4) + '<НаименованиеКраткое>' + LEFT(UPPER(RTRIM(LTRIM(COALESCE(DEP_NAME,'')))),50) + '</НаименованиеКраткое>'
			+ SPACE(4) + '<РегистрационныйНомер>' + RTRIM(LTRIM(COALESCE(REG_NOM_PF,''))) + '</РегистрационныйНомер>'
		+ SPACE(3) + '</СоставительПачки>'
		+ SPACE(3) + '<НомерПачки>'
			+ SPACE(4) + '<Основной>' + REPLACE(STR(COALESCE(RTRIM(LTRIM(CONVERT(VARCHAR(5),NUM_PACH))),'1'),5), ' ','0') + '</Основной>'
		+ SPACE(3) + '</НомерПачки>'
		+ SPACE(3) + '<СоставДокументов>'
			+ SPACE(4) + '<Количество>'+RTRIM(LTRIM(CONVERT(VARCHAR(10),1)))+'</Количество>'
			+ SPACE(4) + '<НаличиеДокументов>'
				+ SPACE(5) + '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_ВОЗНАГРАЖДЕНИЙ</ТипДокумента>'
				+ SPACE(5) + '<Количество>'+ RTRIM(LTRIM(CONVERT(VARCHAR(10),@DOCCOUNT))) +'</Количество>'
			+ SPACE(4) + '</НаличиеДокументов>'
		+ SPACE(3) + '</СоставДокументов>'
		+ SPACE(3) + '<ДатаСоставления>' + CONVERT(VARCHAR(10),DATE_DOC,104) + '</ДатаСоставления>'
		+ SPACE(3) + '<ТипСведений>' + (CASE [TYPE] WHEN 1 THEN 'ИСХОДНАЯ' WHEN 2 THEN 'КОРРЕКТИРУЮЩАЯ' WHEN 3 THEN 'ОТМЕНЯЮЩАЯ' ELSE '' end) + '</ТипСведений>'
		+ SPACE(3) + '<КодКатегории>' + CODE + '</КодКатегории>'
		+ SPACE(3) + '<ТипДоговора>' + (CASE T_DOGOV WHEN 1 THEN 'ТРУДОВОЙ' ELSE 'ГРАЖДАНСКО-ПРАВОВОЙ' end) + '</ТипДоговора>'
		+ SPACE(3) + '<ОтчетныйГод>' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = '0' THEN '2010' ELSE [YEAR] END) + '</ОтчетныйГод>'
		+ SPACE(3) + '<СуммаВыплатИвознаграждений>'
			+ SPACE(4) + '<ТипСтроки>ИТОГО ПО ПАЧКЕ</ТипСтроки>'
			+ SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_all],0),18,2))) +'</СуммаВыплатВсего>'
			+ SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+  RTRIM(LTRIM(STR(COALESCE([s2_all],0),18,2)))  +'</СуммаВыплатНачисленыСтраховыеВзносы>'
		+ SPACE(3) + '</СуммаВыплатИвознаграждений>'
	 + SPACE(2) + '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ>'
	 FROM
		#ADV64 
	 WHERE 
		NUM_PACH = @NGROUP		
				 
	---
	-- ПЕРЕЧИСЛЕНИЕ ДОКУМЕНТОВ
	---

	SET @Cur2 = CURSOR FORWARD_ONLY
	FOR select ID from #SZV63 WHERE NUM_PACH = @NGROUP
	
	OPEN @Cur2
	FETCH NEXT FROM @Cur2 INTO @ID

	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, 
				SPACE(2) + '<СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_ВОЗНАГРАЖДЕНИЙ>' + CHAR(10)
				  + SPACE(3) + '<НомерВпачке>'+ CONVERT(VARCHAR(20),NUM_STR+1) +'</НомерВпачке>' + CHAR(10)
				  + SPACE(3) + '<ТипСведений>'+ (CASE [TYPE] WHEN 1 THEN 'ИСХОДНАЯ' WHEN 2 THEN 'КОРРЕКТИРУЮЩАЯ' WHEN 3 THEN 'ОТМЕНЯЮЩАЯ' ELSE '' end) +'</ТипСведений>' + CHAR(10)
				  + SPACE(3) + '<СтраховойНомер>'+ INSUR_NUM +'</СтраховойНомер>' + CHAR(10)
				  + SPACE(3) + '<ФИО>' + CHAR(10)
					+ SPACE(4) + '<Фамилия>' + LEFT(UPPER(ltrim(rtrim(FM))),40) + '</Фамилия>' + CHAR(10) 
					+ SPACE(4) + '<Имя>' + LEFT(UPPER(ltrim(rtrim(IM))),40) + '</Имя>' + CHAR(10)
				    + SPACE(4) + '<Отчество>' + LEFT(UPPER(ltrim(rtrim(OT))),40) + '</Отчество>' + CHAR(10)
				  + SPACE(3) + '</ФИО>'
				  
				  + SPACE(3) + '<РегистрационныйНомер>'+ RTRIM(LTRIM(COALESCE(REG_NOM_PF,''))) +'</РегистрационныйНомер>'
				  + SPACE(3) + '<НаименованиеКраткое>'+ LEFT(UPPER(RTRIM(LTRIM(COALESCE(DEP_NAME,'')))),50) +'</НаименованиеКраткое>'
				  + SPACE(3) + '<НалоговыйНомер>'
					+ SPACE(4) + '<ИНН>' + RTRIM(LTRIM(COALESCE(INN,''))) + '</ИНН>'
					+ SPACE(4) + '<КПП>' + RTRIM(LTRIM(COALESCE(KPP,''))) + '</КПП>'
				  + SPACE(3) + '</НалоговыйНомер>'
			
				  + SPACE(3) + '<КодКатегории>'+ CODE +'</КодКатегории>'
				  + SPACE(3) + '<ТипДоговора>' + (CASE T_DOGOV WHEN 1 THEN 'ТРУДОВОЙ' ELSE 'ГРАЖДАНСКО-ПРАВОВОЙ' end) + '</ТипДоговора>'
				  + SPACE(3) + '<ОтчетныйГод>' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = '0' THEN '2010' ELSE [YEAR] END) + '</ОтчетныйГод>'
				  + SPACE(3) + '<ДатаЗаполнения>' + CONVERT(VARCHAR(10),DATE_DOC,104) + '</ДатаЗаполнения>'
				  
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
					 + SPACE(4) + '<Месяц>1</Месяц>'
					 + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_1],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_1],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
					 + SPACE(4) + '<Месяц>2</Месяц>'
					 + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_2],0),15,2))) +'</СуммаВыплатВсего>'
					 + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_2],0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
					 + SPACE(4) + '<Месяц>3</Месяц>'
					 + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_3],0),15,2))) +'</СуммаВыплатВсего>'
					 + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_3],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
					 + SPACE(4) + '<Месяц>4</Месяц>'
					 + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_4],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_4],0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>5</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_5],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_5],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>6</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_6],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_6],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>7</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_7],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_7],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>8</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_8],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_8],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>9</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_9],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_9],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>10</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_10],0),15,2)))+'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_10],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>11</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_11],0),15,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_11],0),15,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>МЕСЯЦ</ТипСтроки>'
				     + SPACE(4) + '<Месяц>12</Месяц>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(COALESCE([s1_12],0),15,2)))+'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(COALESCE([s2_12],0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				  + SPACE(3) + '<СуммаВыплатИвознаграждений>'
					 + SPACE(4) + '<ТипСтроки>ИТОГО</ТипСтроки>'
				     + SPACE(4) + '<СуммаВыплатВсего>'+ RTRIM(LTRIM(STR(ISNULL(s1_1,0)+ISNULL(s1_2,0)+ISNULL(s1_3,0)+ISNULL(s1_4,0)+ISNULL(s1_5,0)+ISNULL(s1_6,0)+ISNULL(s1_7,0)+ISNULL(s1_8,0)+ISNULL(s1_9,0)+ISNULL(s1_10,0)+ISNULL(s1_11,0)+ISNULL(s1_12,0),18,2))) +'</СуммаВыплатВсего>'
				     + SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносы>'+ RTRIM(LTRIM(STR(ISNULL(s2_1,0)+ISNULL(s2_2,0)+ISNULL(s2_3,0)+ISNULL(s2_4,0)+ISNULL(s2_5,0)+ISNULL(s2_6,0)+ISNULL(s2_7,0)+ISNULL(s2_8,0)+ISNULL(s2_9,0)+ISNULL(s2_10,0)+ISNULL(s2_11,0)+ISNULL(s2_12,0),18,2))) +'</СуммаВыплатНачисленыСтраховыеВзносы>'
				  + SPACE(3) + '</СуммаВыплатИвознаграждений>'
				 + SPACE(2) + '</СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_ВОЗНАГРАЖДЕНИЙ>'
				 FROM
					#SZV63
				WHERE 
					ID = @ID 

		END


		FETCH NEXT FROM @Cur2 INTO @ID
	END

	CLOSE @Cur2
	DEALLOCATE @Cur2

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'	
		+ '</ФайлПФР>'
	END
	
	FETCH NEXT FROM @Cur1 INTO @NGROUP

END 

CLOSE @Cur1
DEALLOCATE @Cur1

SET NOCOUNT OFF

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




GO


GRANT EXECUTE ON dbo.[SS_SZV63_EXPORT] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE]
END
GO

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

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

*******************************************************************************/
-- Повторный запрос на сохранение нескольких форм.
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn     INT,
        @liLSF        INT


DECLARE curLSF CURSOR FOR
   SELECT MAX([B].[LINK_SAVED_FORM]) AS [LINK_SAVED_FORM]
   FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
   JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[KBP] = [B].[KBP] AND 
                                               [A].[VB] = [B].[VB] AND 
                                               [A].[LINK_FORM] = [B].[LINK_FORM] AND 
                                               [A].[DT] = [B].[DT] AND 
                                               [A].[PRD] = [B].[PRD] AND 
                                               [A].[VF0] = [B].[VF0] AND 
                                               [A].[IMPORT_DATE] >= [B].[IMPORT_DATE]
   WHERE [A].[LINK_SAVED_FORM] = @liRepeatRequest
   GROUP BY [B].[CODE_FORM], [B].[KBP], [B].[VB], [B].[DT], [B].[PRD], [B].[VF0], [B].[ATRIBUTS], [B].[LINK_FORM], [B].[SOFT] 
   UNION 
   SELECT [B].[LINK_SAVED_FORM]
   FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
   JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[LINK_FORM] = [B].[LINK_FORM] AND 
                                               [A].[DT] = [B].[DT] AND 
                                               [A].[PRD] = [B].[PRD] AND 
                                               [A].[VF0] = [B].[VF0] AND 
                                               [A].[ATRIBUTS] = [B].[ATRIBUTS]
   JOIN dbo.REPORT_FORMS C ON A.LINK_FORM = C.LINK_FORM AND CODE = '0531467'
   WHERE [A].[LINK_SAVED_FORM] = @liRepeatRequest  --заглушка для импорта 0531467
OPEN curLSF

FETCH NEXT 
FROM curLSF
INTO @liLSF

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liLSF,
                                                  @tIsAppend,
	                                               @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   FETCH NEXT 
   FROM curLSF
   INTO @liLSF
END
   
CLOSE curLSF
DEALLOCATE curLSF

RETURN @liReturn

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE] 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.[BK_UPDATE_TYPE_OPER_NDS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_UPDATE_TYPE_OPER_NDS]

GO
CREATE PROCEDURE dbo.BK_UPDATE_TYPE_OPER_NDS
	@intLINK	INT OUTPUT,
	@strCODE	VARCHAR (2),
	@strSHORT_NAME	VARCHAR (254),
	@strFULL_NAME	VARCHAR (2000),
	@intISUSED	TINYINT = 0
AS
BEGIN
	Declare
		@intERROR	int,
		@intRowCount	int,
		@intTrancount	int,
		@intObj	INT,
		@strEventText	VARCHAR (254)

	SET @strCODE = LTRIM (ISNULL (@strCODE, ''))
	SET @strSHORT_NAME = LTRIM (ISNULL (@strSHORT_NAME, ''))
	SET @strFULL_NAME =  LTRIM (ISNULL (@strFULL_NAME, ''))
	SET @intISUSED = ISNULL (@intISUSED, 0)

	IF @strCODE = '' OR @strSHORT_NAME = ''
		RETURN 5

	SET @strFULL_NAME = CASE 
					WHEN @strFULL_NAME = '' THEN @strSHORT_NAME
					ELSE @strFULL_NAME
				END

	IF EXISTS (SELECT * FROM dbo.TYPE_OPER_NDS WITH (NOLOCK) WHERE CODE = @strCODE AND LINK <> @intLINK)
		RETURN 4

	SET @intTrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	UPDATE dbo.TYPE_OPER_NDS
	SET CODE = @strCODE,
		SHORT_NAME	= @strSHORT_NAME,
		FULL_NAME	= @strFULL_NAME,
		ISUSED	= @intISUSED
	WHERE LINK = @intLINK

	SELECT @intERROR = @@ERROR, @intRowCount = @@ROWCOUNT
	IF @intERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	IF @intRowCount = 0
	BEGIN
		INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
		VALUES (@strCODE, @strSHORT_NAME, @strFULL_NAME, @intISUSED)

		SELECT @intERROR = @@ERROR, @intLINK = @@IDENTITY
		IF @intERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF @@TRANCOUNT > @intTrancount
	BEGIN
		SELECT @intObj = LINK
		FROM dbo.S_OBJECTS
		WHERE CODE = 'DICTIONARY_TYPE_OPER_NDS'

		SET @strEventText = 'Виды операций по НДС ' + RTRIM (@strCODE) + '-' + @strSHORT_NAME

		EXECUTE dbo.WF_GENERATEEVENT
			'Сохранение строки справочника',
			@strEventText,
			@intObj,
			'TYPE_OPER_NDS',
			@intLINK

		COMMIT TRAN
	END

	RETURN 0
END

GO


GRANT EXECUTE ON dbo.[BK_UPDATE_TYPE_OPER_NDS] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE dbo.BK_PRINTDOC_INVOICE_COR
	@intLINK_DOC	INT
AS
BEGIN
	DECLARE @DOC_HEADER TABLE
		(LINK		INT,
		DOC_NUM		VARCHAR (30),
		DOC_DATE	VARCHAR (10),
		COR_NUM		VARCHAR (30),
		COR_DATE	VARCHAR (10),

		OSN_NUM		VARCHAR (30),
		OSN_DATE	VARCHAR (10),
		OSN_NUM_C	VARCHAR (30),
		OSN_DATE_C	VARCHAR (10),
		
		SEL_NAME	VARCHAR (254),
		SEL_ADR		VARCHAR (254),
		SEL_INN		VARCHAR (20),
		SEL_KPP		VARCHAR (20),

		BUY_NAME	VARCHAR (254),
		BUY_ADR		VARCHAR (254),
		BUY_INN		VARCHAR (20),
		BUY_KPP		VARCHAR (20),

		PRN_OTV		TINYINT
		)

	--- Шапка документа ---
	INSERT INTO @DOC_HEADER
	SELECT G.LINK,
		G.NUMBER,
		CONVERT (VARCHAR (10), G.[DATE], 104),
		
		CASE
			WHEN ISNULL (GPIC.COR_NUM, '') = '' THEN '-'
			ELSE GPIC.COR_NUM
		END, 
		CASE
			WHEN GPIC.COR_DATE IS NULL THEN '-'
			ELSE CONVERT (VARCHAR (10), GPIC.COR_DATE, 104)
		END,
		G0.NUMBER,
		CONVERT (VARCHAR (10), G0.[DATE], 104),
		
		CASE
			WHEN ISNULL (GPI.COR_NUM,  '') = '' THEN '-'
			ELSE GPI.COR_NUM  
		END,
		CASE
			WHEN GPI.COR_DATE IS NULL THEN '-' 
			ELSE CONVERT (VARCHAR (10), GPI.COR_DATE, 104)
		END,

		-- Продавец --
		dbo.BK_GET_PRINT_DEP_NAME (SEL.LINK),
		CONVERT (VARCHAR (254), dbo.GetAddressByKladr (SEL.KLADR_LINK) +
			ISNULL (', ' + SEL.HOUSE, '')),
		SEL.INN,
		SEL.KPP,
		-- Покупатель --
		dbo.BK_GET_PRINT_DEP_NAME (BUY.LINK),
		CONVERT (VARCHAR (254), dbo.GetAddressByKladr (BUY.KLADR_LINK) +
			ISNULL (', ' + BUY.HOUSE, '')),
		BUY.INN,
		BUY.KPP,

		1
	FROM dbo.G_PROV G
	LEFT JOIN dbo.G_PROV_INVOICE_COR GPIC ON (GPIC.DOC_LINK = G.LINK)
	LEFT JOIN dbo.OSNOV OSN ON (OSN.LINK = GPIC.OSNOV)
	LEFT JOIN dbo.G_PROV G0 ON (G0.LINK = OSN.LINK_G_PROV)
	LEFT JOIN dbo.G_PROV_INVOICE GPI ON (GPI.DOC_LINK = G0.LINK)

	LEFT JOIN dbo.DEPARTMENTS SEL ON (SEL.LINK = GPI.SELLER)
	LEFT JOIN dbo.DEPARTMENTS BUY ON (BUY.LINK = GPI.BUYER)

	WHERE G.LINK = @intLINK_DOC 
/*
	IF EXISTS (SELECT *
			FROM dbo.G_PROV G
			INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = G.OBJECT
				AND SO.CODE = 'DOCUMENTS_INVOICE_СOR_IN')
			WHERE G.LINK = @intLINK_DOC)

		INSERT INTO @DOC_HEADER
		SELECT G.LINK,
			G.NUMBER,
			CONVERT (VARCHAR (10), G.[DATE], 104),
			G.OSNOV_NUM,
			CONVERT (VARCHAR (10), G.OSNOV_DATE, 104),

			dbo.BK_GET_PRINT_DEP_NAME (G.SEL_LINK),
			CONVERT (VARCHAR (254), dbo.GetAddressByKladr (SEL.KLADR_LINK) +
				ISNULL (', ' + SEL.HOUSE, '')),
			SEL.INN,
			SEL.KPP,
			
			dbo.BK_GET_PRINT_DEP_NAME (G.DEP_LINK),
			CONVERT (VARCHAR (254), dbo.GetAddressByKladr (BUY.KLADR_LINK) +
				ISNULL (', ' + BUY.HOUSE, '')),
			BUY.INN,
			BUY.KPP,
			1
		
		FROM dbo.DOCUMENTS_INVOICE_СOR_IN G
		INNER JOIN dbo.DEPARTMENTS BUY ON (BUY.LINK = G.DEP_LINK)
		LEFT JOIN dbo.DEPARTMENTS SEL ON (SEL.LINK = G.SEL_LINK)
		WHERE G.LINK = @intLINK_DOC

	INSERT INTO 
*/	

	-- Табличная часть документа --
	DECLARE @DOC_TAB TABLE
		(DOC_LINK	INT,
		ORDERS		INT,
		INV_CODE	VARCHAR (20)	DEFAULT (''),
		INV_NAME	VARCHAR (254)	DEFAULT (''),
		UM_CODE		VARCHAR (20)	DEFAULT (''),
		UM_NAME		VARCHAR (254)	DEFAULT (''),

		QTY_OLD		NUMERIC (18, 4)	DEFAULT (0),
		QTY_NEW		NUMERIC (18, 4)	DEFAULT (0),

		PRICE_OLD	NUMERIC (18, 2)	DEFAULT (0),
		PRICE_NEW	NUMERIC (18, 2)	DEFAULT (0),

		SUM_OLD		NUMERIC (18, 2)	DEFAULT (0),
		SUM_NEW		NUMERIC (18, 2)	DEFAULT (0),
		SUM_DIF1	NUMERIC (18, 2)	DEFAULT (0),
		SUM_DIF2	NUMERIC (18, 2)	DEFAULT (0),

		AKC_OLD		NUMERIC (18, 2)	DEFAULT (0),
		AKC_NEW		NUMERIC (18, 2)	DEFAULT (0),
		AKC_DIF1	NUMERIC (18, 2)	DEFAULT (0),
		AKC_DIF2	NUMERIC (18, 2)	DEFAULT (0),

		STAVKA_NDS	NUMERIC (5, 2)	DEFAULT (0),
		ST_NDS_NEW	NUMERIC (5, 2)	DEFAULT (0),
		
		NO_NDS_OLD	TINYINT,
		NO_NDS_NEW	TINYINT,

		S_NDS_OLD	NUMERIC (18, 2)	DEFAULT (0), 
		S_NDS_NEW	NUMERIC (18, 2)	DEFAULT (0),
		S_NDS_DIF1	NUMERIC (18, 2)	DEFAULT (0), 
		S_NDS_DIF2	NUMERIC (18, 2)	DEFAULT (0),

		S_ALL_OLD	NUMERIC (18, 2)	DEFAULT (0),
		S_ALL_NEW	NUMERIC (18, 2)	DEFAULT (0),
		S_ALL_DIF1	NUMERIC (18, 2)	DEFAULT (0),
		S_ALL_DIF2	NUMERIC (18, 2)	DEFAULT (0)
		)

	INSERT INTO @DOC_TAB
	SELECT T1.LINK_UP,
		T1.ORDERS,
	
		T1.INV_CODE,
		T1.INV_NAME,
		ISNULL (T1.UM_CODE, '-'),
		ISNULL (T1.UM_NAME, '-'),

		T1.QTY,
		T1.QTY_NEW,

		T1.PRICE,
		T1.PRICE_NEW,

		T1.SUMMA,
		T1.SUM_NEW,
		CASE
			WHEN T1.SUMMA > T1.SUM_NEW THEN T1.SUMMA - T1.SUM_NEW
			ELSE 0
		END,
		CASE
			WHEN T1.SUM_NEW > T1.SUMMA THEN T1.SUM_NEW - T1.SUMMA
			ELSE 0
		END,

		T1.AKCIZ,
		T1.AKC_NEW,
		CASE
			WHEN T1.AKCIZ > T1.AKC_NEW THEN T1.AKCIZ - T1.AKC_NEW
			ELSE 0
		END,
		CASE
			WHEN T1.AKC_NEW > T1.AKCIZ THEN T1.AKC_NEW - T1.AKCIZ
			ELSE 0
		END,

		T1.STAVKA_NDS,
		T1.ST_NDS_NEW,

		T1.NO_NDS,
		T1.NO_NDS_NEW,

		T1.SUMMA_NDS,
		T1.S_NDS_NEW,
		CASE
			WHEN T1.SUMMA_NDS > T1.S_NDS_NEW THEN T1.SUMMA_NDS - T1.S_NDS_NEW
			ELSE 0
		END,
		CASE
			WHEN T1.S_NDS_NEW > T1.SUMMA_NDS THEN T1.S_NDS_NEW - T1.SUMMA_NDS
			ELSE 0
		END,

		T1.SUMMA_ALL,
		T1.S_ALL_NEW,
		CASE
			WHEN T1.SUMMA_ALL > T1.S_ALL_NEW THEN T1.SUMMA_ALL - T1.S_ALL_NEW
			ELSE 0
		END,
		CASE
			WHEN T1.S_ALL_NEW > T1.SUMMA_ALL THEN T1.S_ALL_NEW - T1.SUMMA_ALL
			ELSE 0
		END

	FROM dbo.BK_DOC_TAB_INVOICE_COR_FN (@intLINK_DOC) T1

	IF @@ROWCOUNT = 0
		INSERT INTO @DOC_TAB (DOC_LINK, ORDERS)
		SELECT @intLINK_DOC, 0

	-- Результат --
	SELECT *
	FROM @DOC_HEADER H1
	LEFT JOIN @DOC_TAB T1 ON (T1.DOC_LINK = H1.LINK)
	ORDER BY T1.ORDERS

--	SELECT * FROM @DOC_HEADER H1
END




GO


GRANT EXECUTE ON dbo.[BK_PRINTDOC_INVOICE_COR] TO PUBLIC

GO


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


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

GO

CREATE  PROCEDURE dbo.X_ADMIN_SALDO_RECALC
AS
BEGIN
Declare @varKSDateB datetime,
	@varKSDateE datetime,
	@varKSRESULT int

Select @varKSDateB = BEGINDATE,
	@varKSDateE = ENDDATE
FROM dbo.ADMIN_INFO

EXECUTE @varKSRESULT = dbo.X_SALDO_ChangeDate
		@varKSDateB,
		@varKSDateE

RETURN @varKSRESULT
END


GO


GRANT EXECUTE ON dbo.[X_ADMIN_SALDO_RECALC] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

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

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

CREATE PROCEDURE dbo.[RO_PRINT_769]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
   DECLARE @vcVidFO VARCHAR(50)
	create table #all (COL1 varchar(8000), COL2 NUMERIC(20,2), COL3 NUMERIC(20,2), COL4 VARCHAR(50), COL5 VARCHAR(2000), COL6 varchar(8000), COL7 VARCHAR(10), CODE varchar(50), DEL bit, ITOG int, orders int IDENTITY(1,1))
	DECLARE @table varchar(100), @RunStr varchar(8000)
   
   set @vcVidFO = dbo.RN_GET_ATR_VALUE(@LSF, 'REPORTS_ATR_VID')

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, ''0'', CODE, 0 as DEL, 1 from ' + @table
	insert #all execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, ''1'', CODE, 0 as DEL, 1 from ' + @table + ' where COL1 <> ''88888888''' 
	insert #all execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, ''2'', CODE, 0 as DEL, 1 from ' + @table + ' where COL1 <> ''88888888''' 
	insert #all execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, ''1'', CODE, 0 as DEL, 1 from ' + @table 
	insert #all execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, ''2'', CODE, 0 as DEL, 1 from ' + @table 
	insert #all execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)
   
   INSERT #all (COL1, COL2, COL3, COL4, COL5, COL6, COL7, CODE, DEL)
   SELECT COL1, 0, 0, COL4, '', '', '1', CODE, DEL
   FROM #all A
   WHERE COL7 = '0' AND SUBSTRING(CODE,4,5) IN ('00000', '88888') AND COL4 = ''
         AND NOT EXISTS(SELECT * FROM #all  A1 WHERE A.COL1 = A1.COL1 AND COL7 = '1') 

   INSERT #all (COL1, COL2, COL3, COL4, COL5, COL6, COL7, CODE, DEL)
   SELECT COL1, 0, 0, COL4, '', '', '2', CODE, DEL
   FROM #all A
   WHERE COL7 = '0' AND SUBSTRING(CODE,4,5)  IN ('00000', '88888') AND COL4 = ''
         AND NOT EXISTS(SELECT * FROM #all A1 WHERE A.COL1 = A1.COL1 AND COL7 = '2') 
   
	select COL1,
          COL2,
          COL3,
          RTRIM(COL4) AS COL4,
          COL5,
          COL6,
          COL7,
          RTRIM(CODE) + COL7 AS CODE,
          DEL,
          ITOG,
          orders 
   from #all ORDER BY LEFT(COL1,3), CASE when SUBSTRING(COL1,4,2) = '00' then 'xx' else  SUBSTRING(COL1,4,2) end , COL7, orders
	drop table #all
GO
GRANT ALL ON dbo.[RO_PRINT_769] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


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

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

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = CONVERT (VARCHAR (254), 'Виды операций по НДС ' + ' ' + CODE + ' ' + SHORT_NAME)
	FROM dbo.TYPE_OPER_NDS WITH (UPDLOCK)
	WHERE LINK = @varKSintLINK

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.TYPE_OPER_NDS WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK
		FROM dbo.S_OBJECTS
		WHERE CODE = 'DICTIONARY_TYPE_OPER_NDS'

		EXECUTE dbo.WF_GENERATEEVENT
			'Удаление из справочника',
			@varKSEventText,
			@varKSObjectLink,
			'TYPE_OPER_NDS',
			@varKSintLINK

		COMMIT TRAN
	END
RETURN 0




GO


GRANT EXECUTE ON dbo.[BK_DELETE_TYPE_OPER_NDS] 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_CHECK_DICT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_CHECK_DICT]
GO

/*******************************************************************************
	c Кейсистемс (Keysystems), 2006
    проверка на правильный ввод данных 
*******************************************************************************/
CREATE       procedure dbo.RN_CHECK_DICT
	@LSF int, -- линк сохраненного отчета
	@OrderTable TINYINT, -- порядковый номер таблицы
   @check_property TINYINT = 2
AS

declare @LF int, @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), @prop int,@DictWhere VARCHAR(1000),
	@ExecStr varchar(8000), @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @option_import_report int,@nameTable varchar(100),@link_col int,@code_form varchar(20),
   @org VARCHAR (50), @budg VARCHAR(50), @link_org INT, @link_budg int,@AddWhere VARCHAR(1000), @vcDate VARCHAR(10)


select @LF = Link_Form,
         @link_org = [Link_Organization],
         @link_budg = ISNULL([Link_Type_Svod],0),
         @vcDate = CONVERT(VARCHAR(10), begin_date, 112) 
from report_saved_forms (nolock) 
where Link_Saved_Form = @LSF

SELECT @org = code FROM dbo.[DEPARTMENTS] d WHERE d.[LINK] = @link_org
SELECT @budg = code FROM dbo.[KL_BUDG_TYPE] kbt WHERE kbt.[Link] = @link_budg

select @code_form=code from dbo.report_forms where link_form=@LF


if @LF is NULL
begin
	return -1
end

select @LC = Link_Code_Col, @LT = Link_Table,@nameTable='№'+LTRIM(STR(orders))+' '+Name from report_tables (nolock) where orders = @OrderTable and Link_Form = @LF
if @LC is NULL
begin
	return -2
end
create table #no_check (code_row varchar(50))
insert #no_check
select '00079000000000000000'
union
select '00096000000000000000'
union
select '00097000000000000251'
union
select '00097000000000000540'
union
select '00097000000000000640'
union
select '00097000000000000000'
union
select '00097000000000000231'
union 
select '79000000000000000'
union
select '96000000000000000'
union
select '888'
union
select '8888888'
union
select '88888888888888888'


/*
IF (@code_form like '%0503127%' or @code_form like '%0503117%' or @code_form like '%0503137%' and @code_form like '%0503117%') and @OrderTable=2
    RETURN */

create table #col_dict (link_col int)
insert #col_dict
select link_col from report_coloumns where rtrim(isnull(dictionary,''))<>'' and isnull(property,0)&@check_property = @check_property --and isnull(property,0)&1= case when @code_form='(72н)0503317M' then isnull(property,0)&1 else 0 end
     and link_table=@lt
create table #tmpDict (orders int,ord varchar(250),res varchar(1000),cKod varchar(250),cTable varchar(250),cCol varchar(250))

-- если указано, что нужно проверять по кодовому стролбцу, то берется только этот справочник
if exists(select * from #col_dict where link_col = @LC)
	delete #col_dict where link_col <> @LC

while exists(select * from #col_dict)
begin
	select top 1 @link_col=link_col from #col_dict

	select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List), @DictWhere  = [Dictionary_Where], @prop=property
	  from report_coloumns (nolock) where Link_Col = @Link_col

	IF isnull(@prop,0)&@check_property<>@check_property 
	begin
		delete #col_dict where link_col=@link_col
		continue  -- не контролируем колонку
	end

	if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
	begin
		delete #col_dict where link_col=@link_col
		continue  -- нет подключенных справочников
	end

	set @Cols = ''
	set @Field =''
	set @Fields = ''
	set @Col = ''
	while @DictField <> '' and @DictCol <> ''
	begin
		exec dbo.RO_FORMULA_FUNCTIONS 1, @DictField output, @Field output, ','
		exec dbo.RO_FORMULA_FUNCTIONS 1, @DictCol output, @Col output, ','
		set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
		if @i = @OrderCol
		begin
			set @CodeCol = @Col -- ключевой столбец
			set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
		end
		else begin
			set @Fields = @Fields + @Field + ','
			set @Cols = @Cols + @Col + ','
		end
	end

	if @Fields <> '' AND @Cols <> ''
	begin
		--return 0 -- нет полей, кроме ключевого столбца
	--    delete #col_dict where link_col=@link_col
	--    continue
		set @Fields = LEFT(@Fields, LEN(@Fields) - 1)
		set @Cols =  LEFT(@Cols, LEN(@Cols) - 1)
	end



	declare @nameCol varchar(100)
	declare @cWhere varchar(1000)
   DECLARE @cWhere1 varchar(1000)

   SET @AddWhere =  case when isnull(@DictWhere, '') <> '' THEN ' and ' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DictWhere,'%link_org%',LTRIM(STR(@link_org))),'%link_budg%',LTRIM(STR(@link_budg))),'%org%','''' + LTRIM(@org) + ''''),'%budg%','''' + LTRIM(isnull(@budg,'')) + ''''), '%date%', '''' + @vcDate + '''')  ELSE '' end
	set @cWhere=case when @LC=@link_col then 'A.code_row =D.'+@FieldCol + @AddWhere +' ' 
	  else 'A.str_val =D.'+@FieldCol + @AddWhere  END
   SET @cWhere1 = case when @LC=@link_col then '' 
	  else ' and A.link_col ='+str(@link_col) END
	
	set @i = isnull((select max(orders) from #Res),0) + 1
	select @nameCol='№'+LTRIM(STR(orders))+' '+Name  from report_coloumns where Link_Col = @Link_col
	--проверка на существование кода строка
		set @ExecStr = 'insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select DISTINCT top 1  -2,'+case when @LC=@link_col then 'A.code_row' else 'A.str_val'  end +','''','''','''','''' 
		from #report_dinamics  A join report_coloumns B (nolock) on B.link_col = A.link_col and  B.link_table='+str(@lt)+'
      left join ' + @DICT+' D on '+@cWhere +'  
		where  link_sf='+str(@LSF)+' and not exists(select * from #no_check C where C.code_row=A.code_row) and D.'+@FieldCol + ' is NULL ' + @cWhere1 + '
		and not exists(select * from #no_check C where C.code_row=A.str_val)'

	-- print  @ExecStr
	   execute(@ExecStr)
		set @ExecStr = 'insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct -1,'+case when @LC=@link_col then 'A.code_row' else 'A.str_val' end +',''Строка отсутствует в справочнике:''+case when '+case when @LC=@link_col then 'A.code_row' else 'A.str_val' end +'='''' then '' (пустой код) '' else '+case when @LC=@link_col then 'A.code_row' else 'A.str_val' end +' end ,'''','''+@nameTable+''','''+@nameCol+''' 
		from #report_dinamics  A  join report_coloumns B (nolock) on B.link_col = A.link_col and  B.link_table='+str(@lt)+'
      left join ' + @DICT+' D on '+@cWhere +'      
		where  link_sf='+str(@LSF)+' and not exists(select * from #no_check C where C.code_row=A.code_row) and D.'+@FieldCol + ' is NULL ' + @cWhere1 + '  
		and not exists(select * from #no_check C where C.code_row=A.str_val)'
	-- print  @ExecStr
		execute(@ExecStr)
		insert #Res (res,orders,cdoc,ckod,cTable,cCol,cvalue)
		select 'Проверка справочной информации',@i,left(res,254),ckod,ctable,ccol,'' from #tmpDict order by ord,orders
		delete from #tmpDict


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

	while @Fields <> '' and @Cols <> '' --and @code_form<>'(72н)0503317M'
	begin
		exec dbo.RO_FORMULA_FUNCTIONS 1, @Cols output, @Col output, ','
		exec dbo.RO_FORMULA_FUNCTIONS 1, @Fields output, @Field output, ','
		select @LinkCol = Link_Col,@nameCol='№'+LTRIM(STR(orders))+' '+Name  from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@Col, 'COL', ''))
	--    -- print @Col
	--    -- print @Field
	--    -- print @link_col
	--    -- print @LC

		select @prop=property from report_coloumns (nolock) where Link_Col = @LinkCol
		IF isnull(@prop,0)&@check_property<>@check_property
			begin
				continue  -- не контролируем колонку
			end

	IF @link_col=@LC
	begin
		set @ExecStr = 'insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 0,D.'+@FieldCol+','''','''','''','''' 
		from ' + @Dict + ' D 
		where exists(select * from #report_dinamics where link_sf='+str(@LSF)+' and Code_Row =D.'+@FieldCol+' and LEFT(LTRIM(str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) and link_col='+STR(@LinkCol)+') '
           + @AddWhere   
		+ ' group by D.'+@FieldCol
	-- print  @ExecStr
	  execute(@ExecStr)
		set @ExecStr = 'insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 1,D.'+@FieldCol+',''Неверно заполненная строка:''+D.'+@FieldCol+','''','''+@nameTable+''','''+@nameCol+''' 
		from ' + @Dict + ' D 
		where exists(select * from #report_dinamics where link_sf='+str(@LSF)+' and Code_Row =D.'+@FieldCol+' and LEFT(LTRIM(str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) and link_col='+STR(@LinkCol)+') '
           + @AddWhere   
		+' group by D.'+@FieldCol
	-- print  @ExecStr
		execute(@ExecStr)
		set @ExecStr = 'insert #tmpDict (orders,ord,RES, cKod,cTable,cCol) '+
		'select distinct 2,D.'+@FieldCol+',''В отчете: ''+(select top 1 str_val from #report_dinamics where Code_Row =D.'+@FieldCol+' and link_col='+STR(@LinkCol)+'),'''','''+@nameTable+''','''+@nameCol+''' 
		from ' + @Dict + ' D 
		where exists(select * from #report_dinamics where  link_sf='+str(@LSF)+' and Code_Row =D.'+@FieldCol+' and LEFT(LTRIM(str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) and link_col='+STR(@LinkCol)+') '
           + @AddWhere   
		+' group by D.'+@FieldCol
	-- print  @ExecStr
		execute(@ExecStr)
		set @ExecStr = 'insert #tmpDict (orders,ord,RES, cKod,cTable,cCol) '+
		'select distinct 3,D.'+@FieldCol+',''В справочнике: ''+D.'+@Field+','''','''+@nameTable+''','''+@nameCol+''' 
		from ' + @Dict + ' D 
		where exists(select * from #report_dinamics where  link_sf='+str(@LSF)+' and Code_Row =D.'+@FieldCol+' and LEFT(LTRIM(str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) and link_col='+STR(@LinkCol)+') '
           + @AddWhere   
		execute(@ExecStr)
	end
	else
	begin
		set @ExecStr = '
		select distinct isnull(A.str_val,'''') as code_row ,isnull(B.str_val,'''') as str_val into #tmp_coderow from #report_dinamics A left join #report_dinamics B ON A.code_row=B.code_row and B.link_col='+str(@LinkCol )+'
		where not exists (select * from #no_check C where C.code_row=A.code_row) and A.link_col='+str(@link_col)

		set @ExecStr = @ExecStr+ '  
		 insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 0,D.'+@FieldCol+','''','''','''','''' 
		from ' + @Dict + ' D 
		where exists(select * from #tmp_codeRow B where B.Code_Row =D.'+@FieldCol+' and RTRIM(D.'+ @Field+')<>'''' and LEFT(LTRIM(B.str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) 
			  and not exists(select * from ' + @Dict + ' C where B.Code_Row =C.'+@FieldCol+' and  LEFT(LTRIM(B.str_val),95)=LEFT(LTRIM(C.'+ @Field+'),95))) '
           + @AddWhere   
		+ ' group by D.'+@FieldCol

		set @ExecStr = @ExecStr+ '
		 insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 1,D.'+@FieldCol+',''Неверно заполненная строка:''+D.'+@FieldCol+','''','''+@nameTable+''','''+@nameCol+'''  
		from ' + @Dict + ' D 
		where exists(select * from #tmp_codeRow B where B.Code_Row =D.'+@FieldCol+' and RTRIM(D.'+ @Field+')<>'''' and LEFT(LTRIM(B.str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) 
			  and not exists(select * from ' + @Dict + ' C where B.Code_Row =C.'+@FieldCol+' and  LEFT(LTRIM(B.str_val),95)=LEFT(LTRIM(C.'+ @Field+'),95))) '
           + @AddWhere   
		+ ' group by D.'+@FieldCol


		set @ExecStr = @ExecStr+ '
		 insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 2,D.'+@FieldCol+',''В отчете: ''+(select top 1 STR_VAL from #tmp_codeRow A where A.Code_Row =D.'+@FieldCol+'  and LEFT(LTRIM(A.str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) and not exists(select * from '+@Dict+' B where B.'+@FieldCol+' =A.code_row and  LEFT(LTRIM(A.str_val),95)=LEFT(LTRIM(B.'+ @Field+'),95))  ),'''','''+@nameTable+''','''+@nameCol+''' 
		from ' + @Dict + ' D 
		where exists(select * from #tmp_codeRow B where B.Code_Row =D.'+@FieldCol+' and RTRIM(D.'+ @Field+')<>'''' and LEFT(LTRIM(B.str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) 
			  and not exists(select * from ' + @Dict + ' C where B.Code_Row =C.'+@FieldCol+' and  LEFT(LTRIM(B.str_val),95)=LEFT(LTRIM(C.'+ @Field+'),95))) '
           + @AddWhere   
		+ ' group by D.'+@FieldCol+',D.'+ @Field

		set @ExecStr = @ExecStr+ '
		 insert #tmpDict (orders,ord, RES, cKod,cTable,cCol) '+
		'select distinct 3,D.'+@FieldCol+',''В справочнике: ''+D.'+@Field+','''','''+@nameTable+''','''+@nameCol+''' 
		from ' + @Dict + ' D 
		where exists(select * from #tmp_codeRow B where B.Code_Row =D.'+@FieldCol+' and RTRIM(D.'+ @Field+')<>'''' and LEFT(LTRIM(B.str_val),95)<>LEFT(LTRIM(D.'+ @Field+'),95) 
			  and not exists(select * from ' + @Dict + ' C where B.Code_Row =C.'+@FieldCol+' and  LEFT(LTRIM(B.str_val),95)=LEFT(LTRIM(C.'+ @Field+'),95)))    '
           + @AddWhere   
		-- print  @ExecStr
		execute(@ExecStr)
	   
	end

		insert #Res (res,orders,cdoc,ckod,cTable,cCol,cvalue)
		select 'Проверка справочной информации',@i,left(res,254),ckod,ctable,ccol,'' from #tmpDict order by ord,orders
		delete from #tmpDict
	end

	delete #col_dict where link_col=@link_col
end --end while
GO
GRANT ALL ON dbo.[RN_CHECK_DICT] 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.[X_SALDO_ChangeDate]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_SALDO_ChangeDate]

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.X_SALDO_ChangeDate
	@varKSBeginDate	DATETIME,
	@varKSEndDate	DATETIME,
	@varKSlogicRecursive	bit = 0
AS
Declare
	@varKSCurrentDateValue	datetime,
	@varKSOldDateValue	datetime,
	@varKSBeginOfYear	datetime,
	@varKSDayBeforeBegin datetime,
	@varKSStartDate	datetime

Select @varKSStartDate = dbo.RestGetStartDate()

SET @varKSBeginOfYear = dbo.DateBeginOfYear(@varKSBeginDate)

IF @varKSlogicRecursive = 0
BEGIN
	
	DELETE FROM dbo.SALDO_CHANGES
	
	DELETE FROM dbo.SALDO WHERE ([DATE] > @varKSBeginDate OR [DATE] < @varKSStartDate) AND ISOBOROT = 0 OR ISOBOROT = 1
	
	IF @varKSBeginDate = @varKSBeginOfYear
		SET @varKSCurrentDateValue = Dateadd(year, -1, @varKSBeginOfYear)
	ELSE
		SET @varKSCurrentDateValue = @varKSBeginOfYear

	IF @varKSCurrentDateValue < @varKSStartDate
		Select @varKSCurrentDateValue = dbo.DateBeginOfMonth(dateadd(month, 1, @varKSStartDate)) 

	
	IF NOT EXISTS(Select * from dbo.SALDO Where [DATE] = @varKSStartDate AND ISOBOROT = 0)
	BEGIN
		
		INSERT INTO dbo.SALDO([DATE], ACCOUNT, ISOBOROT, D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
				KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, SGU, INDATE, AP1, AP2, AP3, DEP_LINK, PRICE)
		SELECT @varKSStartDate, ACCOUNT, convert(tinyint, 0), D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
				KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, SGU, INDATE, AP1, AP2, AP3, DEP_LINK, PRICE
		FROM dbo.SALDO
		WHERE [DATE] = (@varKSStartDate - 1) AND ISOBOROT = 2
	END
	
	SET @varKSOldDateValue = @varKSCurrentDateValue
	SET @varKSCurrentDateValue = dateadd(month, 1, @varKSCurrentDateValue) 
	WHILE @varKSCurrentDateValue < @varKSBeginDate
	BEGIN
		
		DELETE FROM dbo.SALDO WHERE [DATE] BETWEEN @varKSOldDateValue + 1 AND @varKSCurrentDateValue - 1 AND ISOBOROT = 0
		
		IF NOT(EXISTS(Select * from dbo.saldo where [date] = @varKSCurrentDateValue and isoborot = 0))
			EXECUTE dbo.X_SALDO_CHANGEDATE @varKSCurrentDateValue, @varKSCurrentDateValue, 1
		SET @varKSOldDateValue = @varKSCurrentDateValue
		SET @varKSCurrentDateValue = dateadd(month, 1, @varKSCurrentDateValue) 
	END
END

IF NOT EXISTS(Select * from dbo.SALDO Where [DATE] = @varKSBeginDate AND ISOBOROT = 0) AND @varKSBeginDate > @varKSStartDate
BEGIN
  SET @varKSDayBeforeBegin = @varKSBeginDate-1
   INSERT INTO dbo.SALDO([DATE], ACCOUNT, ISOBOROT, D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, SGU, INDATE, AP1, AP2, AP3,DEP_LINK, PRICE)
   SELECT @varKSBeginDate, ACCOUNT, convert(tinyint, 0),
		D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, SGU, INDATE, AP1, AP2, AP3,DEP_LINK, PRICE
	FROM dbo.ARestFullCalc (@varKSBeginDate, DEFAULT)
END
IF @varKSlogicRecursive = 0
BEGIN
	INSERT INTO dbo.SALDO([DATE], ACCOUNT, ISOBOROT, D_SUMMA, K_SUMMA, R_SUMMA, D_QUANTITY, K_QUANTITY,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC, SGU, INDATE, AP1, AP2, AP3, DEP_LINK, PRICE)
	SELECT DATE_PROV,
		ACCOUNT,
		convert(tinyint, 1),
		SUM(D_SUMMA),
		SUM(K_SUMMA),
		SUM(R_SUMMA),
		SUM(D_QUANTITY),
		0,
		KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC,
		CASE WHEN SA.p_Kassa = 1 THEN O.SGU ELSE NULL END,
		INDATE, AP1, AP2, AP3,DEP_LINK,
		PRICE
	FROM dbo.ARestPackedOborotByPeriod(@varKSBeginDate, @varKSEndDate, default) O
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = O.ACCOUNT
	GROUP BY DATE_PROV, ACCOUNT, KBK, EKR, DEP, SUB, EMP, NOMEN, INV, KAU, DEP_ACC, TMC,
	CASE WHEN SA.p_Kassa = 1 THEN O.SGU ELSE NULL END,
	INDATE, AP1, AP2, AP3,DEP_LINK, PRICE
END

GO


GRANT EXECUTE ON dbo.[X_SALDO_ChangeDate] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RN_IMPORT_FORM_155]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RN_IMPORT_FORM_155]
END
GO

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RN_IMPORT_FORM_155]   
   @lvcKODF         VARCHAR(10),
   @lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
   @liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
   @bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0     -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn     INT,
        @ltImportType TINYINT,
        @liLSF        INT,
        @lvcAdm       VARCHAR(3),                
        @lvcTXT   VARCHAR(8000),
        @lvcWord1 VARCHAR(8000),
        @lvcWord2 VARCHAR(8000),
        @lvcKBP   VARCHAR(50),
        @lvcVB    VARCHAR(50),
        @liORDER  INT,
        @i        INT,
		@vcUK		varchar(100),
        @bBreak_To_Grbs BIT ,
        @iLinkOrg  INT ,
        @iLinkBudg  INT,
        @lvcTypeOrg VARCHAR(20) 

SET @bBreak_To_Grbs = 0
SET @ltImportType = 2

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   DECLARE curLSF CURSOR FOR
      SELECT [B].[LINK_SAVED_FORM]
      FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
      JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[KBP] = [B].[KBP] AND 
                                                  [A].[VB] = [B].[VB] AND 
                                                  [A].[LINK_FORM] = [B].[LINK_FORM] AND 
                                                  [A].[DT] = [B].[DT] AND 
                                                  [A].[PRD] = [B].[PRD] AND 
                                                  [A].[VF0] = [B].[VF0] AND 
                                                  [A].[IMPORT_DATE] >= [B].[IMPORT_DATE]
      WHERE [A].[LINK_SAVED_FORM] = @liRepeatRequest 
   
   OPEN curLSF
   
   FETCH NEXT 
   FROM curLSF
   INTO @liLSF
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
        
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liLSF,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode

      FETCH NEXT 
      FROM curLSF
      INTO @liLSF
   END
      
   CLOSE curLSF
   DEALLOCATE curLSF
   
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

SELECT @lvcKBP = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
      LEFT([TXT],3) IN ('KБ=')

SELECT @lvcVB = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

 SELECT top 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
 FROM #IMPORT_TABLE
 WHERE LEFT([TXT],3) IN ('TO|')

 SELECT top 1 @lvcAdm = dbo.[RA_GETWORDNUM]([TXT], 6, '|')
 FROM #IMPORT_TABLE
 WHERE LEFT([TXT],3) IN ('OS|')

 SELECT top 1 @lvcTypeOrg = CASE dbo.[RA_GETWORDNUM]([TXT], 4, '|')
   WHEN '0' THEN 'Казенный'
   WHEN '1' THEN 'Бюджетный'   
   WHEN '2' THEN 'Автономный'   
   ELSE '' END
 FROM #IMPORT_TABLE
 WHERE LEFT([TXT],  3) IN ('OS|')


 IF @lvcKBP IS NULL
 BEGIN
    SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],''), @bBreak_To_Grbs = Break_To_Grbs      
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
    SELECT @iLinkOrg = link FROM dbo.departments WHERE budg =  REPLACE(@lvcKBP, 'КБП=', '') 
 END

 IF @lvcVB IS NULL 
 BEGIN
    SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
    
    SELECT @iLinkBudg = link FROM dbo.kl_budg_type WHERE outcode = REPLACE(@lvcVB, 'ВИД=', '') 
 END


IF @lvcKBP IS NULL
BEGIN
   SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_KBP_151'
END

IF @lvcVB IS NULL 
BEGIN
   SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_VB_151'
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE LEFT([TXT],3) = 'FK|')
BEGIN
   DELETE #IMPORT_TABLE 
   WHERE [ORDER] IN (1,2)

   SET IDENTITY_INSERT #IMPORT_TABLE ON  
   
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ='+@lvcKODF,-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'КБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   IF @lvcKODF = '0503155G'
   BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=5',2)
   END
   ELSE BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)
   END
   
   SET IDENTITY_INSERT #IMPORT_TABLE OFF

   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

DECLARE @tabIMPORT_HEAD TABLE ([TXT] VARCHAR(8000),
                               [ORDER] INT IDENTITY(1,1))


DECLARE @tabIMPORT TABLE ([TXT] VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))
   
DECLARE @tabRD TABLE ([TXT] VARCHAR(8000),
                      [RD]  TINYINT,
                      [ADM] VARCHAR(3))

INSERT @tabIMPORT_HEAD([TXT]) VALUES ('КОДФ='+@lvcKODF)


IF EXISTS (SELECT * 
           FROM #IMPORT_TABLE
           WHERE LEFT([TXT],3)='OS|')
BEGIN       
   INSERT @tabIMPORT_HEAD([TXT]) 
   SELECT 'ДТ=' + RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3)='OS|'
END

INSERT @tabIMPORT_HEAD([TXT]) VALUES (ISNULL( @lvcKBP,'КБП='))
INSERT @tabIMPORT_HEAD([TXT]) VALUES (ISNULL(@lvcVB,'ВИД='))

IF @lvcKODF = '0503155G'
BEGIN
   INSERT @tabIMPORT_HEAD([TXT]) VALUES ('ПРД=5')
END
ELSE BEGIN
   INSERT @tabIMPORT_HEAD([TXT]) VALUES ('ПРД=3')
END
--select * from @tabIMPORT

INSERT @tabRD([ADM],
              [RD],
              [TXT])
SELECT [ADM] = '',
       [RD] = 1,
       [TXT] = SUBSTRING([TXT],8,8000)        
FROM #IMPORT_TABLE
WHERE LEFT([TXT],6) IN ('OS_DOH')  

UPDATE @tabRD 
SET [txt] = '010|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='010||' AND RD = 1

INSERT @tabRD([ADM],
              [RD],
              [TXT])
SELECT [ADM] = '',
       [RD] = 2,
       [TXT] = SUBSTRING([TXT],8,8000)        
FROM #IMPORT_TABLE
WHERE LEFT([TXT],6) IN ('OS_RAS')  

UPDATE @tabRD 
SET [txt] = '200|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='200||' AND RD = 2

UPDATE @tabRD 
SET [txt] = '450|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='450||' AND RD = 2

INSERT @tabRD([ADM],
              [RD],
              [TXT])
SELECT [ADM] = '',
       [RD] = 3,
       [TXT] = SUBSTRING([TXT],8,8000)        
FROM #IMPORT_TABLE
WHERE LEFT([TXT],6) IN ('OS_IST')  

UPDATE @tabRD 
SET [txt] = '500|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='500||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '520|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='520||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '620|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='620||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '700|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='700||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '710|500|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='710||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '720|500|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='720||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '800|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='800||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '825|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='825||' AND RD = 3

UPDATE @tabRD 
SET [txt] = '826|000|'+SUBSTRING([txt],6,7000)
WHERE LEFT(txt,5)='826||' AND RD = 3

-- составной ключ
UPDATE @tabRD 
SET [txt] = RTRIM([txt])+'|'+SUBSTRING([txt],1,3)+SUBSTRING([txt],5,3)
WHERE RD=2

    INSERT #IMPORT_TABLE([TXT])
    SELECT CASE WHEN [TXT] LIKE 'КБП=%' THEN '' + ISNULL(@lvcKBP, '') WHEN [TXT] LIKE 'ВИД=%'THEN '' + isnull(@lvcVB, '') ELSE [TXT] END 
    FROM @tabIMPORT_HEAD
    ORDER BY [ORDER]                     


   INSERT #IMPORT_TABLE ([TXT]) VALUES ('РА=0')
   INSERT #IMPORT_TABLE ([TXT]) VALUES ('REPORTS_ATR_ADM=' + @lvcAdm)
   INSERT #IMPORT_TABLE ([TXT]) VALUES ('REPORTS_ATR_TYPE_ORG=' + @lvcTypeOrg)


   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=1')
   
   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabRD
   WHERE  [RD] = 1
      
   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=2')
   
   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabRD
   WHERE [RD] = 2

   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=3')
   
   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabRD
   WHERE [RD] = 2
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode




RETURN @liReturn

GO
GRANT ALL ON dbo.[RN_IMPORT_FORM_155] 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.[SS_REP_CARD_NDFL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SS_REP_CARD_NDFL]

GO

CREATE PROCEDURE dbo.SS_REP_CARD_NDFL
	@cYear varchar(4),
	@nMonth varchar (2) ,			
	@nFirstNum varchar (10) = '',
	@LINK_EMPL int = NULL,  
	@LINK_PERS int = NULL 					
AS BEGIN

SET NOCOUNT ON
 
	Set @nMonth = (case when len(@nMonth)<2 then '0'+@nMonth  else @nMonth  end)

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@cYear AS INT)

	DECLARE @BEGIN_YEAR DATETIME
	SET @BEGIN_YEAR = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	---------------------------------
	--определим последний день в месяце
	declare @eDay varchar (2)
	set @eDay = (select day(max(d.date1))  from dbo.days_month(@nMonth,@cYear)d)
/*	print @eDay*/
	
	
	DECLARE @PRES_DATE DATETIME,
			@PRESENT_DATE varchar (10) 			
	SET @PRES_DATE = dbo.ConvertDMY2Date(@eDay,@nMonth,@varKSnYear)
	SET @PRESENT_DATE = (@cYear + @nMonth + @eDay )

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SELECT * INTO #DICT_TYP_INCOMS FROM dbo.DICTIONARY_TYP_INCOMS
	SELECT * INTO #Salary_deductions FROM dbo.Salary_deductions(@PRESENT_DATE)	

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

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

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

	if isnull(@LINK_EMPL,0) = 0
		set @LINK_EMPL =  (SELECT TOP 1 LINK FROM dbo.SD_EMPL WHERE PERS_LINK = @LINK_PERS AND STATUS_EMPL IN (1,3) AND ISNULL(DATE_END,@BEGIN_YEAR) >= @BEGIN_YEAR AND DEP_LINK = @DEP_LINK )

	if isnull(@LINK_PERS,0)= 0
		set @LINK_PERS =  (SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @LINK_EMPL)


	declare @Status int
	Select @Status= [STATUS] from dbo.ITEM_MOVE where ACTIVE = 1 and EMPL_LINK = @LINK_EMPL	-->>NEW

	--Все сотрудники в данной организации с заданным @LINK_PERS
	CREATE TABLE #EMPLS (LINK INT, LINK_PERS INT)

	INSERT INTO #EMPLS(LINK, LINK_PERS)
	SELECT distinct LINK, @LINK_PERS FROM dbo.empl WHERE PERS_LINK = @LINK_PERS AND DEP_LINK = @DEP_LINK

	-----------------------------
	delete from dbo.SAL_DED_MONTH
	where 
	YEAR(DATE_DED) = @varKSnYear
	AND
	Month(DATE_DED) <= @nMonth
	AND
	LINK_EMPL IN (Select EM.LINK from #EMPLS EM)
	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 '#EMPLS', 'REP2NDFL', 'LINK_PERS'

	/*Временная таблица*/
	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, code_inc varchar(4), period_begin datetime, period_END 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,code_inc, period_begin, period_end, 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,
		CODE_INC = CONVERT(VARCHAR(5), (SELECT DA.VALUE FROM DICTION_APP DA WHERE DA.LINK_UP = P.LINK_INC AND 
							        da.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_CODE_T_INC'))),
		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.period_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 = @LINK_PERS
			or
			JC.PERS_LINK = @LINK_PERS
			)	
		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,
			CODE_INC = CONVERT(VARCHAR(5), (SELECT DA.VALUE FROM DICTION_APP DA WHERE DA.LINK_UP = sjc.LINK_INC AND 
							        da.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_CODE_T_INC'))),
			 period_begin, period_end, date1, link_dep
	from dbo.S_J_C_SHORT SJC 
		LEFT JOIN #DICT_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC 
	where 
		SJC.LINK_DEP = @DEP_LINK
		and
		(
			SJC.LINK_FACE = @LINK_PERS
			or
			SJC.PERS_LINK = @LINK_PERS
		)
		and YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		and TYP_OPER = 2

--select * from SDOC where link = SJC.link_doc
-----------------------------------------------------------
--Для обособленных подразделений
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_KPP VARCHAR(9))
INSERT INTO #S_OBOSOB (SUBDIV_LINK, O_OKATO, O_KPP)
SELECT SUBDIV_LINK, O_OKATO, O_KPP 
FROM [dbo].SUBDIVISION(@DATE) 
WHERE OBOSOB = 1

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

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

	SELECT 	distinct 
		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),
		[NMD] = (SELECT TOP 1 NAME FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
		[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 = '',
		isnull(PO.O_OKATO, ''),
		isnull(PO.O_KPP, '')
	FROM 
		dbo.PERSON P
		LEFT OUTER JOIN dbo.NDFL_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
		LEFT JOIN #P_OBOSOB PO ON 1=1
	WHERE
		P.LINK = @LINK_PERS		
		
	ORDER BY 
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT)
		
		
	UPDATE #PERSON SET NOM_SPR = @nFirstNum 

	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


	---->>

	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
		
	

	-- выборка заявленных вычетов по сотрудникам 
	---------------------------------
	CREATE  TABLE  #RES_VICHET (LINK INT, LINK_EMPL INT, LINK_PERS int, LINK_DED INT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), SUMMA NUMERIC(10,2), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE1 DATETIME, DATE2 DATETIME,M_BEG INT, M_END INT, NUM_ROW int identity(1,1), FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
	INSERT INTO #RES_VICHET
	SELECT ed.LINK, 
		   ed.EMPL_LINK AS LINK_EMPL,
		   @LINK_PERS as  LINK_PERS,
		   ed.DED_LINK AS LINK_DED,
           sd.CODE AS CODE_DED,
           sd.NAME AS NAME_DED,
           sd.SUMMA AS SUMMA,
           /*(SELECT CODE
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS CODE_DED,
           (SELECT NAME
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS NAME_DED, 
           (SELECT SUMMA
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS SUMMA, 
            */sd.predel,
            sd.type,
            ed.DATE1, 
            ed.DATE2,
			0,
            0,
            '',
            '',
            0
	FROM dbo.EMPL_DED AS ED 
			INNER JOIN #EMPLS R  ON  ED.empl_link = R.LINK
			inner join  #Salary_deductions sd on sd.ref_pay = ed.ded_link and sd.type = '1'

	where 
		ed.date1 <= @PRES_DATE 
				AND (ed.date2 IS NULL OR YEAR(ed.date2) = '1900' OR year(ed.date2) >=@varKSnYear)
				and @nMonth >= month(ed.date1) 
				and @varKSnYear = year(ed.date1)
				
	update #RES_VICHET
		set M_BEG =  case when year(DATE1)< @cYear then 1
					      when year(DATE1)= @cYear then Month(DATE1) 
						  end,
			M_END = case when DATE2 is null then null
					      when DATE2 is not null and month(DATE2) <= @nMonth then Month(DATE2)
					      when DATE2 is not null and month(DATE2) > @nMonth then null
						  end 
	from #RES_VICHET


	if exists(select CODE_DED from #RES_VICHET where NAME_DED like ('%ребенка%'))
	begin

		create table #CHILDS (ROW_ID int identity(1,1),FIO varchar (60) , BIRTHDAY DATETIME, AGE INT )
		insert into #CHILDS  ( FIO, BIRTHDAY, AGE )
		SELECT 	
			distinct
			[FIO] = CONVERT(VARCHAR(60),RTRIM(FM) +' '+RTRIM(IM) + ' '+ RTRIM(OT)),
			[BIRTHDAY] = BIRTHDATE,
			[AGE] = DATEDIFF(year,BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod())) 
		FROM 
			dbo.KU_PERS_FAMILY  
		WHERE 
			PERS_LINK = @LINK_PERS
			AND
			FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
			and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@cYear)) <18

	
		create table #CHILDS_res (LINK INT, LINK_EMPL INT, LINK_PERS int, LINK_DED INT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), SUMMA NUMERIC(10,2), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE1 DATETIME, DATE2 DATETIME,M_BEG INT, M_END INT, NUM_ROW int, N_ROW_C int identity(1,1), FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
		insert into #CHILDS_res 
		select  r.*
		from #RES_VICHET r where r.NAME_DED like ('%ребенка%')

		update #CHILDS_res
		Set	[FIO] = c.FIO,
			[BIRTHDAY] = c.BIRTHDAY,
			[AGE] = c.AGE
		FROM 
			#CHILDS_res v ,#CHILDS c 
		WHERE 
			v.N_ROW_C = c.ROW_ID

		update #RES_VICHET
		Set	[FIO] = v.FIO,
			[BIRTHDAY] = v.BIRTHDAY,
			[AGE] = v.AGE
		FROM 
			#RES_VICHET r , #CHILDS_res v 
		WHERE 
			r.link = v.link
			
		drop table #CHILDS_res
		drop table  #CHILDS
	end	
	else 
	begin
		


		insert into #RES_VICHET 
		select distinct	
		   0, 
		   0, 
		   0,
		   0,
           '',
           '', 
           0, 
           0,
           0,
           '',
           '',
           0, 
           0,
		   CONVERT(VARCHAR(60),RTRIM(F.FM) +' '+RTRIM(F.IM) + ' '+ RTRIM(F.OT)),
		   isnull(F.BIRTHDATE,''),
		   DATEDIFF(year,F.BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod()))
		FROM 
			dbo.KU_PERS_FAMILY F
		WHERE 
			F.PERS_LINK = @LINK_PERS
			AND
			F.FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
			--and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@cYear)) <18
	end 	


	--- если в таблице нет кода с вычетом 103, то добавляем пустую строку и код 103 - для вывода в excel
	if not exists(select * from #RES_VICHET where code_ded = '103')
	begin
		insert into #RES_VICHET 
		select distinct	
		   null, 
		   null, 
		   null,
		   null,
           '103',
           ' ', 
           null, 
           null,
           null,
           null,
           null,
           null, 
           null,
           null,
		   null,
		   null
	end
	
	if not exists(select * from #RES_VICHET where code_ded <> '103' and name_ded not like '%на налогоплательщика%')
		begin
		insert into #RES_VICHET 
		select distinct	
		   0, 
		   0, 
		   0,
		   0,
           ' ',
		   '', 
           0, 
           0,
           0,
           '',
           '',
           0, 
           0,
           null,
		   null,
		   null
	   
	end
	--- 

	--- выборка детей работников 
		CREATE  TABLE  #RES_CHILD_VICHET(PERS_LINK INT, FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
		INSERT INTO #RES_CHILD_VICHET
		SELECT F.PERS_LINK,
			[FIO] = CONVERT(VARCHAR(60),RTRIM(F.FM) +' '+RTRIM(F.IM) + ' '+ RTRIM(F.OT)),
			[BIRTHDAY] = F.BIRTHDATE,
			[AGE] = DATEDIFF(year,F.BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod()))
		FROM 
			dbo.KU_PERS_FAMILY F
		WHERE 
			F.PERS_LINK = @LINK_PERS
			AND
			F.FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
		

	DECLARE @varKSStatus VARCHAR(1)
	Set @varKSStatus = COALESCE((SELECT TOP 1 STATUS FROM #PERSON),1) /*резидент, не резидент*/	
	--- выборка имущественных вычетов	
	CREATE  TABLE  #RES_IM_VICHET (LINK INT, LINK_EMPL INT, LINK_DED INT, YEAR INT, MONTH1 TINYINT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), F_NAME VARCHAR(254), 
		SUM_DED NUMERIC(10,2),NUM_REF VARCHAR(15), IFNS_CODE VARCHAR(20), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE_ref DATETIME)
	INSERT INTO #RES_IM_VICHET
	SELECT distinct TD.LINK, 
		   TD.LINK_PERSON AS LINK_EMPL, 
		   TD.LINK_DICTION AS LINK_DED,
		   TD.YEAR,
		   TD.MONTH1,
		   CODE_DED = SPR.CODE,
           NAME_DED = SPR.NAME,
           F_NAME = case when SPR.CODE = '311' or SPR.CODE = '313' then 'Прямые расходы на  новое строительство и (или) приобретение'
						 when SPR.CODE = '312' then 'Погашение процентов по кредитам'
						 when SPR.CODE = '318' then 'Погашение процентов по кредитам на рефинансирование ипотечных займов'
						 else  SPR.NAME end ,
            TD.SUM_DED,
            TD.NUM_REF,
            TD.IFNS_CODE, 
            PREDEL = ISNULL(sd.SUMMA,SPR.SUMMA),
            sd.type,
            TD.DATE_REF
	FROM dbo.TAX_DEDUCTIONS AS TD 
			INNER JOIN #EMPLS R  ON  TD.link_person = R.LINK_PERS
			INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = td.LINK_DICTION AND SPR.NUMBER = 4
			LEFT JOIN #Salary_deductions sd on sd.ref_pay = td.LINK_DICTION and sd.type = '4'
	where 
		YEAR(td.date_ref) = @cYear 
		AND
		TD.LINK_DEP = @DEP_LINK
	group by td.LINK, TD.LINK_PERSON, TD.LINK_DICTION, SPR.CODE, SPR.NAME,	TD.YEAR,TD.MONTH1,  TD.SUM_DED, TD.NUM_REF, TD.IFNS_CODE, sd.SUMMA,SPR.SUMMA, sd.type, TD.DATE_REF

	---------	 Необлагаемые доходы	
	CREATE  TABLE  #RES_NE_VICHET (CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), PREDEL NUMERIC(10,2), CODE_INC varchar(5), NAME_INC VARCHAR(254),  
				SUMMA_M1 NUMERIC(10,2),SUMMA_M2 NUMERIC(10,2),SUMMA_M3 NUMERIC(10,2),SUMMA_M4 NUMERIC(10,2),
				SUMMA_M5 NUMERIC(10,2),SUMMA_M6 NUMERIC(10,2),SUMMA_M7 NUMERIC(10,2),SUMMA_M8 NUMERIC(10,2),
				SUMMA_M9 NUMERIC(10,2),SUMMA_M10 NUMERIC(10,2),SUMMA_M11 NUMERIC(10,2),SUMMA_M12 NUMERIC(10,2))

	INSERT INTO #RES_NE_VICHET
	SELECT DISTINCT
		   CODE_DED = isnull(SPR.CODE,' '),
           NAME_DED = SPR.NAME,
           PREDEL = ISNULL(sd.SUMMA,SPR.SUMMA),
           CODE_INC = DT.SNAME,
           NAME_INC = DT.NAME,
           SUMMA_M1 = 0,
           SUMMA_M2 = 0,
           SUMMA_M3 = 0,
           SUMMA_M4 = 0,
           SUMMA_M5 = 0,
           SUMMA_M6 = 0,
           SUMMA_M7 = 0,
           SUMMA_M8 = 0,
           SUMMA_M9 = 0,
           SUMMA_M10 = 0,
           SUMMA_M11 = 0,
           SUMMA_M12 = 0
	FROM
		dbo.SAL_DED_MONTH AS SDM
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
		INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
		inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
		LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
	where 
		YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth


	update #RES_NE_VICHET	
	set    
		   SUMMA_M1 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 1 ),0) ,
           SUMMA_M2 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 2 ),0),
           SUMMA_M3 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 3 ),0),           
           SUMMA_M4 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 4 ),0),           
           SUMMA_M5 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 5 ),0),           
           SUMMA_M6 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 6 ),0),          
           SUMMA_M7 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 7 ),0),           
          SUMMA_M8 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 8 ),0),           
           SUMMA_M9 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 9 ),0),           
           SUMMA_M10 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 10 ),0),           
           SUMMA_M11 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 11 ),0),           
           SUMMA_M12 = isnull((select SDM.SUMMA 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 12 ),0)

	FROM #RES_NE_VICHET		
	
------*************************


	--CREATE  TABLE  #RES_NonNDFL_VICHET (LINK_EMPL INT,LINK INT, link_vkr INT, link_ekr INT, TYP_PER varchar (8), object varchar (8), SUMMA NUMERIC(10,2), period_begin datetime , period_end datetime,DATE_BEGIN datetime , DATE_END datetime, CODE_DED VARCHAR(3), Ref_ded varchar (8), CODE_INC varchar(5), link_inc int, NAME_DED VARCHAR(254) ,PREDEL NUMERIC(10,2), TYPE_ded NUMERIC(3,0))
	--INSERT INTO #RES_NonNdfl_VICHET
	--Select 
	--	JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, jc.summa, 
	--	period_begin =  JC.period_begin ,
	--	period_end = JC.period_end,
	--	JC.DATE_BEGIN,
	--	JC.DATE_END,
	--	dt.cod_ded, 
	--	dt.ref_deduct, 
	--	dt.sname  ,
	--	dt.link , 
	--	dt.name as name_ded,
	--	sd.summa as summa_neoblag,
	--	sd.type 
	
	--from 
	--	dbo.CALCULATE_JURNAL JC 
	--	INNER JOIN #EMPLS R  ON  JC.link_empl = R.LINK_PERS
	--	/*INNER JOIN dbo.EMPL E ON C.LINK_EMPL = E.LINK  /*and e.link = 17114*/*/
	--	INNER JOIN dbo.PAYS P ON   JC.LINK_PAYS = P.LINK 
	--	inner join DICTIONARY_TYP_INCOMS DT on dt.link = p.link_inc and dt.ref_deduct is not null
	--	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
	--	inner join  dbo.Salary_deductions(@cYear + @nMonth + @eDay ) sd on sd.ref_pay = dt.ref_deduct and sd.type = '6'
	--where
	--	P.OBJECT = 1
	--	AND P.LINK in (Select LINK_PAYS from  dbo.NDFL_GroupTax() )   /*  dbo.NDFL_GroupTax() */ 
	--	AND  month(JC.PERIOD_BEGIN) <=@nMonth and  year(JC.PERIOD_BEGIN) = @cYear
	--	/*AND (	@Status <> 1 AND JC.LINK_EMPL = @LINK_EMPL /*Если не основной сотрудник, то доход по своему табельному номеру*/
	--			or
	--	@Status = 1     and  R.PERS_LINK = 17024*/ /*Если основной сотрудник, то доход по всем табельным номерам
	--	)*/	
	--AND JC.LINK_DEP = @DEP_LINK 
	
	----------------------------------
	-- 5. Налоговые ставки 
	----------------------------------
	-- таблица 5.1 Статус налогоплательщика
	declare @varKSSumDed numeric(15,2), @varKSRange  numeric(15,2), @varKSResid int, @varKSStrCom varchar(1000)

	declare @FACE int

	if @link_empl is null
		begin 
			set  @FACE = @link_PERS
		end 
	else
		begin 
			set	@FACE = @link_PERS	
		end


	CREATE  TABLE  #RES_EMP_STATUS (DATE_begin DATETIME,DATE_END DATETIME, NDFL_Range numeric (3), resident int, KSTR VARCHAR(3), month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, perc_stav varchar(2) )
	INSERT INTO #RES_EMP_STATUS
	SELECT 
		   cast( (@cYear + '01' + '01') as datetime) ,
		   cast( (@cYear + @nMonth + @eDay) as datetime) ,
		   dbo.SalaryGetNDFLRange (@FACE,(@cYear + @nMonth + @eDay) ) as NDFL_Range ,
		   (case when dbo.GetEmplResident(@FACE) = 0 then 1
				 when dbo.GetEmplResident(@FACE) = 1 then 2
				 else 3 end) as resident, 
		   (case when (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = (select CITIZ_LINK from person where link = @LINK_PERS)) = '1' then '643' else '' END) as KSTR,
		   null,
		   '',
		   null,
		   null,
		   '',
		   '', 
		   null,
		   ''
	--Таблица 5.2 Виды доходов (доходы не по ставке 13%)
	--по сотрудникам

	CREATE  TABLE  #vid_dohod_not13 (month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, perc_stav varchar(2) )
	insert into #vid_dohod_not13	
	select DISTINCT
		   month(s.period_end),
		   year(s.period_end),
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   perc_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from 
		#EMPLS E
		INNER JOIN #S_J_C_SHORT  S ON S.link_empl = E.LINK
		INNER JOIN #DICT_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 and	
		  Month(s.date1)<= @nMonth 
		 AND S.LINK_DEP = @DEP_LINK 
		 and S.link_inc is not null

	--по договорникам
	insert into #vid_dohod_not13	
	select DISTINCT
		   month(s.period_end),
		   year(s.period_end),
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   perc_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from 
		#S_J_C_SHORT  S
		INNER JOIN #DICT_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 and	
		  Month(s.date1)<= @nMonth 
		  AND S.PERS_LINK = @LINK_PERS
		 AND S.LINK_DEP = @DEP_LINK 
		 and S.link_inc is not null
	-----------------------------------------------------
	
	DECLARE @varKSCNT INT

	SELECT @varKSCNT  = COUNT(*) FROM #PERSON

	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(FULL_NAME, '') AS FULL_NAME,
		ISNULL((SELECT TOP 1 dbo.GetAddressByKladr(DD.REF_LINK_A)), '') AS ADDRES,
		ISNULL(DOTF.PHONE, '') AS PHONE,
		ISNULL(RTRIM(FM), '') + ' ' + ISNULL(RTRIM(IM), '') + ' ' + ISNULL(RTRIM(OT), '') AS GLBUH,
		ISNULL(RTRIM(FM), '') AS FM,
		ISNULL(RTRIM(IM), '') AS IM, 
		ISNULL(RTRIM(OT), '') AS OT,
		ISNULL(RTRIM(DOTF.NAME), '') AS Dolzh
	INTO #DEP
	FROM DICTIONARY_DEPARTMENT DD 
	LEFT OUTER JOIN DICTIONARY_OTV_FACE DOTF ON 
		(DOTF.DEP_LINK = DD.LINK
		AND DOTF.NAME = 'Главный бухгалтер')
	LEFT OUTER JOIN KU_EMPL_PLACING EP ON DOTF.FACE_LINK = EP.LINK
	WHERE DD.link = @DEP_LINK


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

	SELECT 
		@varKScInn = INN, @varKScKPP = KPP,
		@varKSFULL_NAME = FULL_NAME, 
		@varKSNALOG = NALOG, @varKSOKATO = Replace(OKATO,' ',''), 
		@varKSPHONE = PHONE, 
		@varKSGLBUH  = GLBUH
	FROM #DEP
	------------------------------------
	--- 6.  Сведения о вычетах, предоставленных по предыдущему мету работы 
	------------------------------------
	
		---Сумма доходов, облагаемых по ставке 13%
	SELECT  * 
	INTO #Prev_dohod
	FROM SD_EMPL_PREV_DOHOD 
	WHERE LINK_EMPL =  @LINK_EMPL ORDER BY COD_TYP_INCOMS 


	--- Сумма доходов не облагаемых по ставке 13%
	SELECT  SD.LINK_EMPL,
			SD.REF_TYP_INCOMS ,
			SD.COD_TYP_INCOMS AS COD_INC,
			SD.NAME_TYP_INCOMS AS NAME_INC,
			(CASE WHEN SD.SUMMA_TYP_INCOMS > DT.SUMMA_DED THEN DT.SUMMA_DED 
				  WHEN SD.SUMMA_TYP_INCOMS <= DT.SUMMA_DED THEN SD.SUMMA_TYP_INCOMS END )AS SUMM_INC,
			@cYear as PER_YEAR	  				 
	INTO #Prev_dohod_NO
	FROM SD_EMPL_PREV_DOHOD sd
	inner join dbo.#DICT_TYP_INCOMS DT ON DT.LINK = SD.REF_TYP_INCOMS AND DT.NUMBER_DED = 6
	WHERE LINK_EMPL =  @LINK_EMPL ORDER BY COD_TYP_INCOMS

	declare @SUM_doh13  numeric(10,2),
			@sum_doh_no13 numeric(10,2)
		
	set @SUM_doh13 = isnull((select sum(SUMMA_TYP_INCOMS) from #Prev_dohod),0) 
	set @sum_doh_no13 = isnull((select sum(SUMM_INC) from #Prev_dohod_NO),0) 

	
	
	CREATE  TABLE  #DEP_Prev (link_dep int,NALOG varchar(10), INN varchar(12), KPP varchar(9), OKATO varchar(14), FULL_NAME  varchar (254), ADDRES  varchar (254), SUMMA_13 NUMERIC(10,2))
	insert into #DEP_Prev
	SELECT 
		null AS link_dep,
		' ' AS NALOG,
		' ' AS INN,
		' ' AS KPP,
		' ' AS OKATO, 
		/*
		ISNULL(dd.link,null) AS link_dep,
		ISNULL(dd.IMNS, ' ') AS NALOG,
		ISNULL(dd.INN, ' ') AS INN,
		ISNULL(dd.KPP, ' ') AS KPP,
		ISNULL(dd.OKATO, ' ')AS OKATO,
		*/
		ISNULL(A.DEP, ' ') AS FULL_NAME,
		ISNULL(A.place, ' ') AS ADDRES,
		ISNULL((@SUM_doh13 - @sum_doh_no13),0) AS SUMMA_13
	FROM /*DICTIONARY_DEPARTMENT DD 
	inner join */KU_EMPL_OLDWORK A /*on  (dd.full_name = a.dep or dd.name = a.dep)*/
	inner join KJ_EMPL_OLDWORK_GROUP b  on a.EMPL_LINK = b.EMPL_LINK 
									and b.EMPL_LINK =  @LINK_EMPL
									and b.link > -1 
									and  year(b.date_end) = @cYear 
									and month(b.date_end) <=  @nMonth 
									and b.date_end = (select max(date_end) 
													  from KJ_EMPL_OLDWORK_GROUP   
													  WHERE EMPL_LINK = @LINK_EMPL 
															and  year(date_end) = @cYear  
															and month(date_end) <= @nMonth 
													  ) 

	where a.date_end = (select max(date_end)  from KJ_EMPL_OLDWORK_GROUP   
											  WHERE EMPL_LINK = @LINK_EMPL 
											and  year(date_end) = @cYear  
													and month(date_end) <= @nMonth 
													 ) 
	---- налоговые вычеты с предыдущего места работы по типам

	SELECT  dd.link_empl,dd.link_ded,dd.code_ded,dd.name_ded,dd.summa_ded as summ_ded, sd.type,  @cYear as PER_YEAR
	INTO #Prev_ded
	FROM SD_EMPL_PREV_DED dd
	inner join #Salary_deductions sd on sd.code = dd.code_ded  
	WHERE dd.LINK_EMPL =  @LINK_EMPL ORDER BY dd.CODE_DED
	
	------------------------------------------------
	-- 7. Доходы облагаемые по ставке 13%

	select 
		SJC.link_empl, 
		SJC.pers_link, 
		   d.name  , 
		   D.sname, 
		   SJC.period_begin, 
		   SJC.period_end, 
		   sum(SJC.summa) as summa , 
		   SJC.link_inc
		   
	into #Dohod_13	   		
	from   #S_J_C_SHORT SJC 
			--inner join pays  p on  p.link = SJC.link_pays and  p.link_inc is not null 
			inner join #DICT_TYP_INCOMS d on d.link = SJC.link_inc 
	WHERE
		(
			SJC.LINK_FACE = @FACE
			or
			SJC.PERS_LINK = @FACE
		)
		AND YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @cYear
		AND MONTH(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND SJC.CODE_INC IS NOT NULL
		AND SJC.CODE_INC <> '0000'
		AND SJC.link_dep  = @DEP_LINK  
	group by SJC.pers_link, SJC.link_empl, D.sname ,d.name  , SJC.period_begin, SJC.period_end, SJC.link_inc

	
	create TABLE #Dohod_13_1 (link_empl int, name varchar(256),  sname varchar(4) ,link_inc int,  p_b1 datetime, p_e1 datetime, s1 numeric (10,2),  
						 p_b2 datetime, p_e2 datetime, s2 numeric (10,2),p_b3 datetime, p_e3 datetime, s3 numeric (10,2), 
						 p_b4 datetime, p_e4 datetime, s4 numeric (10,2),p_b5 datetime, p_e5 datetime, s5 numeric (10,2), 
						 p_b6 datetime, p_e6 datetime, s6 numeric (10,2),p_b7 datetime, p_e7 datetime, s7 numeric (10,2), 
						 p_b8 datetime, p_e8 datetime, s8 numeric (10,2),p_b9 datetime, p_e9 datetime, s9 numeric (10,2),
						 p_b10 datetime, p_e10 datetime, s10 numeric (10,2),p_b11 datetime, p_e11 datetime, s11 numeric (10,2),
						 p_b12 datetime, p_e12 datetime, s12 numeric (10,2))
	INSERT INTO #Dohod_13_1
	SELECT distinct
		D.link_empl ,
		D.name , 
		D.sname , 
 		D.link_inc,
		[p_b1] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '01' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e1] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s1] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b2] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '02' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e2] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s2] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b3] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '03' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e3] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s3] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b4] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '04' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e4] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s4] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b5] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '05' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e5] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s5] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b6] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '06' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e6] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s6] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b7] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '07' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e7] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s7] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b8] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '08' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e8] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s8] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b9] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '09' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e9] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s9] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b10] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '10' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e10] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s10] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b11] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '11' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e11] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s11] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl),
		[p_b12] =(SELECT period_begin FROM #Dohod_13 WHERE month(period_begin) = '12' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[p_e12] =(SELECT period_end FROM #Dohod_13 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl), 
		[s12] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC and link_empl = d.link_empl)
	FROM #Dohod_13 D
	GROUP BY D.link_empl ,D.name , D.sname ,D.link_inc

	--- всего за месяц 
	CREATE  TABLE #Dohod_13_i (MODE int, S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	INSERT INTO #Dohod_13_i
	SELECT
		MODE = 1,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0
		 
	UPDATE #Dohod_13_i
	SET	S_JAN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '01' ),
		S_FEB = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '02' ),
		S_MART= (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '03' ),
		S_APR = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '04' ), 
		S_MAY = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '05' ),
		S_JUN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '06' ),
		S_JUL = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '07' ),
		S_AUG = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '08' ),
		S_SEN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '09' ),
		S_OKT = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '10' ),
		S_NOV = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '11' ),
		S_DEC = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '12' ) 
	FROM #Dohod_13_i where MODE = 1	
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO  #Dohod_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0),
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0),
		S_MART= isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) ,
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0),
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_13_i 
		 where MODE = 1	
	
		 

	------------------------------------------------
	--8. Необлагаемые суммы доходов
	
	Select distinct 
			code_ded, 
			code_inc, 
			name_ded, 
			predel,
			SUMMA_M1,
            SUMMA_M2,          
            SUMMA_M3,         
            SUMMA_M4,        
            SUMMA_M5,          
            SUMMA_M6,          
            SUMMA_M7,        
            SUMMA_M8,      
            SUMMA_M9,         
            SUMMA_M10,         
            SUMMA_M11,          
            SUMMA_M12
				 
	into #Dohod_13_predel
	from #RES_NE_VICHET R

	--- всего за месяц 

	CREATE  TABLE #Dohod_13_predel_i (MODE int null, S_JAN NUMERIC(10,2) , S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	
	INSERT INTO #Dohod_13_predel_i
	
	SELECT
		MODE = 1,
		S_JAN = 0, 
		S_FEB = 0, 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0
	 
	UPDATE #Dohod_13_predel_i
	SET MODE = 1,
		S_JAN = (SELECT isnull(SUMMA_M1,0) FROM #Dohod_13_predel),
		S_FEB = (SELECT isnull(SUMMA_M2,0) FROM #Dohod_13_predel),
		S_MART =(SELECT isnull(SUMMA_M3,0) FROM #Dohod_13_predel),
		S_APR = (SELECT isnull(SUMMA_M4,0) FROM #Dohod_13_predel),	
		S_MAY = (SELECT isnull(SUMMA_M5,0) FROM #Dohod_13_predel),
		S_JUN = (SELECT isnull(SUMMA_M6,0) FROM #Dohod_13_predel),	
		S_JUL = (SELECT isnull(SUMMA_M7,0) FROM #Dohod_13_predel),
		S_AUG = (SELECT isnull(SUMMA_M8,0) FROM #Dohod_13_predel),	
		S_SEN = (SELECT isnull(SUMMA_M9,0) FROM #Dohod_13_predel),
		S_OKT = (SELECT isnull(SUMMA_M10,0) FROM #Dohod_13_predel),	
		S_NOV = (SELECT isnull(SUMMA_M11,0) FROM #Dohod_13_predel),
		S_DEC = (SELECT isnull(SUMMA_M12,0) FROM #Dohod_13_predel) 
	FROM #Dohod_13_predel_i	 where mode = 1 
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #Dohod_13_predel_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
	    S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_13_predel_i where mode = 1 
		
	------------------------------------------------
	--- 9. Сумма облагаемых доходов
	------------------------------------------------
	
	--- всего за месяц 

	CREATE  TABLE #Obl_Dohod_i (MODE INT , S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	
	INSERT INTO #Obl_Dohod_i
	SELECT  mode = 1 ,S_JAN = 0 ,S_FEB = 0 ,S_MART = 0,	S_APR = 0,S_MAY = 0,S_JUN = 0,S_JUL = 0,S_AUG = 0,S_SEN = 0,S_OKT = 0,S_NOV = 0,S_DEC = 0
	
	UPDATE #Obl_Dohod_i
	SET S_JAN = (SELECT isnull(d.S_JAN,0) - isnull(dp.S_JAN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_FEB = (SELECT isnull(d.S_FEB,0) - isnull(dp.S_FEB,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_MART =(SELECT isnull(d.S_MART,0) - isnull(dp.S_MART,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_APR = (SELECT isnull(d.S_APR,0) - isnull(dp.S_APR,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_MAY = (SELECT isnull(d.S_MAY,0) - isnull(dp.S_MAY,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_JUN = (SELECT isnull(d.S_JUN,0) - isnull(dp.S_JUN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_JUL = (SELECT isnull(d.S_JUL,0) - isnull(dp.S_JUL,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_AUG = (SELECT isnull(d.S_AUG,0) - isnull(dp.S_AUG,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_SEN = (SELECT isnull(d.S_SEN,0) - isnull(dp.S_SEN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_OKT = (SELECT isnull(d.S_OKT,0) - isnull(dp.S_OKT,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_NOV = (SELECT isnull(d.S_NOV,0) - isnull(dp.S_NOV,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_DEC = (SELECT isnull(d.S_DEC,0) - isnull(dp.S_DEC,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1) 
	FROM #Obl_Dohod_i where mode = 1 
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #Obl_Dohod_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0), 
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Obl_Dohod_i where mode = 1 
	
	-----------------------------------------------
	--- 10. Вычеты фактически предоставленные , стандартные, имущестевнные, проффессиональные
	-----------------------------------------------
	CREATE  TABLE #DED_FACT( /* LINK_VKR int, NAME_VKR varchar(20) ,*/ LINK_EMPL int , name_ded varchar(254) , code_ded varchar(6),ref_ded int,
							type tinyint,type_ded tinyint, type_name varchar(100),NUM1 int,summa_1 NUMERIC(10,2), countd1 int,NUM2 int, summa_2 NUMERIC(10,2), countd2 int,
							NUM3 int,summa_3 NUMERIC(10,2), countd3 int,NUM4 int, summa_4 NUMERIC(10,2), countd4 int,NUM5 int, summa_5 NUMERIC(10,2), countd5 int,
							NUM6 int,summa_6 NUMERIC(10,2), countd6 int,NUM7 int, summa_7 NUMERIC(10,2), countd7 int,NUM8 int, summa_8 NUMERIC(10,2), countd8 int,
							NUM9 int,summa_9 NUMERIC(10,2), countd9 int,NUM10 int, summa_10 NUMERIC(10,2), countd10 int,NUM11 int, summa_11 NUMERIC(10,2), countd11 int,
							NUM12 int,summa_12 NUMERIC(10,2), countd12 int)
	INSERT INTO #DED_FACT

	SELECT 	
	--LINK_VKR,
	--[NAME_VKR]= FIN.CODE,
	LINK_EMPL, 
	[name_ded] = T.[name],
	[code_ded] =T.[CODE],
	[ref_ded] = REF_DED,
	[type] = type,
	[type_ded] = t.number,
	[type_name] =(case when type=1 and t.number <> 4 and t.code not in (101,102,106,107,108,109,110,111,112,113)  then 'стандартный налоговый вычет'
					   when type=1 and t.number <> 4 and t.code in (101,102,106,107,108,109,110,111,112,113)  then 'Стандартный налоговый вычет на обеспечение ребенка'
					   when type=1 and  t.number = 10 then 'Социальный налоговый вычет в части расходов по уплате взносов на ДПС (НГПС)' 
					   when type=1 and t.number = 4  then 'Имущественный налоговый вычет'
						 else 'освобождаемые от налогообложения' 
					end),
	[NUM1] = 1,
	[summa_1] = 0,
	countd1 = 0,
	[num2] = 2,
	[summa_2] = 0,
	[countd2] = 0  ,
	[num3] = 3,
	[summa_3] = 0 ,
	[countd3] = 0 ,
	[num4] = 4,
	[summa_4] = 0 ,
	[countd4] = 0 ,	
	[num5]= 5,
	[summa_5] = 0 ,
	[countd5] = 0 ,
	[num6]= 6,
	[summa_6] = 0 ,
	[countd6] = 0 ,
	[num7]= 7,
	[summa_7]  = 0,
	[countd7] = 0 ,
	[num8]= 8,
	[summa_8]  = 0,
	[countd8]  = 0,		
	[num9]= 9,
	[summa_9] = 0 ,
	[countd9] = 0 ,
	[num10]= 10,
	[summa_10] = 0 ,
	[countd10] = 0 ,
	[num11]= 11,
	[summa_11] = 0 ,
	[countd11] = 0 ,
	[num12]= 12,
	[summa_12] = 0 ,
	[countd12] = 0 
	from 
		sal_ded_month D inner join months m on m.num =  month(DATE_DED)
		left join dbo.SAL_SFIN FIN ON FIN.LINK = D.LINK_VKR
		left join DICTIONARY_TYP_DEDUCTION  T on T.link = D.REF_DED
	where  
		month(DATE_DED)<=@nMonth and YEAR(DATE_DED)=@cYear and link_empl = @LINK_EMPL and (TYPE=1 /*or TYPE=2*/)

	group by /*m.num,*/ LINK_EMPL, REF_DED, T.[code],T.[name],  type , /*LINK_VKR, FIN.CODE ,*/ t.number
	order by 1,3
	
	update #DED_FACT
	set 	[summa_1] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= d.NUM1 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd1 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= d.NUM1  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT 
	set 	[summa_2] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM2  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd2 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM2  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_3] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM3 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd3 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM3 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d


	update #DED_FACT
	set 	[summa_4] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM4 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd4 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM4 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_5] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM5 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd5 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM5 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_6] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM6 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd6 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM6 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
			
	update #DED_FACT
	set 	[summa_7] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM7 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd7 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM7 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
	
	update #DED_FACT
	set 	[summa_8] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM8 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd8 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM8 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_9] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM9 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd9 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM9 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_10] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM10 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd10 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM10 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_11] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM11 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd11 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM11 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_12] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM12 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd12 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM12 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	--- всего за месяц 

	CREATE  TABLE #NDFL_13_i ( MODE int, S_JAN NUMERIC(10,2), d1 datetime, S_FEB NUMERIC(10,2), d2 datetime, S_MART NUMERIC(10,2), d3 datetime, S_APR NUMERIC(10,2), d4 datetime, 
							   S_MAY NUMERIC(10,2), d5 datetime, S_JUN NUMERIC(10,2),d6 datetime,S_JUL NUMERIC(10,2), d7 datetime,S_AUG NUMERIC(10,2), d8 datetime, 
							   S_SEN NUMERIC(10,2), d9 datetime, S_OKT NUMERIC(10,2),d10 datetime, S_NOV NUMERIC(10,2), d11 datetime, S_DEC NUMERIC(10,2), d12 datetime)
	
	INSERT INTO #NDFL_13_i
	
	SELECT 
		MODE = 1,
		S_JAN = 0 , 
		null,
		S_FEB = 0 , 
		null,
		S_MART = 0, 
		null,
		S_APR = 0, 
		null,
		S_MAY = 0, 
		null,
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0, 
		null,
		S_SEN = 0,
		null,
		S_OKT = 0, 
		null,
		S_NOV = 0, 
		null,
		S_DEC = 0,
		null
	UPDATE #NDFL_13_i
	SET S_JAN = (SELECT sum(isnull(summa_1,0)) FROM #DED_FACT ),
		S_FEB = (SELECT sum(isnull(summa_2,0)) FROM #DED_FACT ),
		S_MART =(SELECT sum(isnull(summa_3,0)) FROM #DED_FACT ),
		S_APR = (SELECT sum(isnull(summa_4,0)) FROM #DED_FACT ),	
		S_MAY = (SELECT sum(isnull(summa_5,0)) FROM #DED_FACT ),
		S_JUN = (SELECT sum(isnull(summa_6,0)) FROM #DED_FACT ),	
		S_JUL = (SELECT sum(isnull(summa_7,0)) FROM #DED_FACT ),
		S_AUG = (SELECT sum(isnull(summa_8,0)) FROM #DED_FACT ),	
		S_SEN = (SELECT sum(isnull(summa_9,0)) FROM #DED_FACT ),
		S_OKT = (SELECT sum(isnull(summa_10,0)) FROM #DED_FACT ),	
		S_NOV = (SELECT sum(isnull(summa_11,0)) FROM #DED_FACT ),
		S_DEC = (SELECT sum(isnull(summa_12,0)) FROM #DED_FACT ) 
	FROM #NDFL_13_i where mode = 1

	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT 
		MODE = 2,
		S_JAN = isnull(S_JAN,0), 
		null,
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		null,
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		null,
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		null,
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		null,
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		null,
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		null,
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) ,
		null,
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) , 
		null,
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		null,
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		null,
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0),
		null 
	FROM #NDFL_13_i where mode = 1
	---------------------------------------------
	---- 11. Облагаемая база ставка 13% 
	---------------------------------------------
	--- всего за месяц 

	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	
	SELECT
		MODE = 3,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 ,
		null, 
		S_MART = 0,
		null, 
		S_APR = 0, 
		null,
		S_MAY = 0,
		null, 
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0,
		null, 
		S_SEN = 0,
		null,
		S_OKT = 0,
		null, 
		S_NOV = 0,
		null, 
		S_DEC = 0,
		null
	 
	UPDATE #NDFL_13_i
	SET S_JAN = (SELECT isnull(O.S_JAN,0) - isnull(D.S_JAN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_FEB = (SELECT isnull(O.S_FEB,0) - isnull(D.S_FEB,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_MART =(SELECT isnull(O.S_MART,0) - isnull(D.S_MART,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_APR = (SELECT isnull(O.S_APR,0) - isnull(D.S_APR,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_MAY = (SELECT isnull(O.S_MAY,0) - isnull(D.S_MAY,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_JUN = (SELECT isnull(O.S_JUN,0) - isnull(D.S_JUN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_JUL = (SELECT isnull(O.S_JUL,0) - isnull(D.S_JUL,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_AUG = (SELECT isnull(O.S_AUG,0) - isnull(D.S_AUG,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_SEN = (SELECT isnull(O.S_SEN,0) - isnull(D.S_SEN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_OKT = (SELECT isnull(O.S_OKT,0) - isnull(D.S_OKT,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_NOV = (SELECT isnull(O.S_NOV,0) - isnull(D.S_NOV,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_DEC = (SELECT isnull(O.S_DEC,0) - isnull(D.S_DEC,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1) 
	FROM #NDFL_13_i where mode = 3

	--- всего с нарастающим итогом с начала года за месяц

	
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT 
		MODE = 4,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 ,
		null, 
		S_MART = 0,
		null, 
		S_APR = 0, 
		null,
		S_MAY = 0,
		null, 
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0,
		null, 
		S_SEN = 0,
		null,
		S_OKT = 0,
		null, 
		S_NOV = 0,
		null, 
		S_DEC = 0,
		null
		
	UPDATE #NDFL_13_i
	set   
		S_JAN = (SELECT isnull(o.S_JAN,0) - isnull(D.S_JAN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_FEB = (SELECT isnull(o.S_FEB,0) - isnull(D.S_FEB,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_MART =(SELECT isnull(o.S_MART,0) - isnull(D.S_MART,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_APR = (SELECT isnull(o.S_APR,0) - isnull(D.S_APR,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_MAY = (SELECT isnull(o.S_MAY,0) - isnull(D.S_MAY,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_JUN = (SELECT isnull(o.S_JUN,0) - isnull(D.S_JUN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_JUL = (SELECT isnull(o.S_JUL,0) - isnull(D.S_JUL,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_AUG = (SELECT isnull(o.S_AUG,0) - isnull(D.S_AUG,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_SEN = (SELECT isnull(o.S_SEN,0) - isnull(D.S_SEN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_OKT = (SELECT isnull(o.S_OKT,0) - isnull(D.S_OKT,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_NOV = (SELECT isnull(o.S_NOV,0) - isnull(D.S_NOV,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_DEC = (SELECT isnull(o.S_DEC,0) - isnull(D.S_DEC,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2)
	FROM #NDFL_13_i where mode = 4
	
	------------------------------------------------
	--- 12. НДФЛ по ставке 13%
	------------------------------------------------ 
	--сумма начисленного налого С НАЧАЛА ГОДА
	INSERT INTO #NDFL_13_i  (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 5,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 , 
		null, 
		S_MART = 0, 
		null, 
		S_APR = 0, 
		null,
		S_MAY = 0, 
		null, 
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0, 
		null,
		S_SEN = 0,
		null,
		S_OKT = 0, 
		null,
		S_NOV = 0, 
		null,
		S_DEC = 0,
		null

	DECLARE @varKSCOEFF NUMERIC(20,2)
	SELECT @varKSCOEFF = CASE WHEN @varKSStatus = 1 THEN 0.13 ELSE 0.30 END

 
	UPDATE #NDFL_13_i 
	SET S_JAN = round((SELECT isnull(S_JAN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_FEB = round((SELECT isnull(S_FEB,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_MART =round((SELECT isnull(S_MART,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_APR = round((SELECT isnull(S_APR,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_MAY = round((SELECT isnull(S_MAY,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_JUN = round((SELECT isnull(S_JUN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_JUL = round((SELECT isnull(S_JUL,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_AUG = round((SELECT isnull(S_AUG,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_SEN = round((SELECT isnull(S_SEN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_OKT = round((SELECT isnull(S_OKT,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_NOV = round((SELECT isnull(S_NOV,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_DEC = round((SELECT isnull(S_DEC,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0)
	FROM #NDFL_13_i where mode =5
	

	
	
	--сумма начисленного налога за месяц 
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 6,
		S_JAN = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '1'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '1') AS C ) 
						  - (round(isnull(S_JAN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JAN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JAN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JAN,0)* @varKSCOEFF,0) end,
		d1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1) from dbo.days_month(1,@cYear)d) else null end,
		
		
		S_FEB =  case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '2'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '2') AS C ) 
						  - (round(isnull(S_FEB,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_FEB,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_FEB,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_FEB,0)* @varKSCOEFF,0) end, 
		d2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1) from dbo.days_month(2,@cYear)d) else null end,
		S_MART = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '3'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '3') AS C ) 
						  - (round(isnull(S_MART,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_MART,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_MART,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_MART,0)* @varKSCOEFF,0) end, 
		d3 = case when isnull(S_MART,0) <>0 then (select max(d.date1) from dbo.days_month(3,@cYear)d) else null end,
		S_APR = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '4'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '4') AS C ) 
						  - (round(isnull(S_APR,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_APR,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_APR,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_APR,0)* @varKSCOEFF,0) end,
		d4 = case when isnull(S_APR,0) <>0 then (select max(d.date1) from dbo.days_month(4,@cYear)d) else null end,
		S_MAY = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '5'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '5') AS C ) 
						  - (round(isnull(S_MAY,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_MAY,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_MAY,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_MAY,0)* @varKSCOEFF,0) end,
		d5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1) from dbo.days_month(5,@cYear)d) else null end,
		S_JUN = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '6'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '6') AS C ) 
						  - (round(isnull(S_JUN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JUN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JUN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JUN,0)* @varKSCOEFF,0) end,
		d6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1) from dbo.days_month(6,@cYear)d) else null end,
		S_JUL = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '7'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '7') AS C ) 
						  - (round(isnull(S_JUL,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JUL,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JUL,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JUL,0)* @varKSCOEFF,0) end,
		d7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1) from dbo.days_month(7,@cYear)d) else null end,
		S_AUG = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '8'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '8') AS C ) 
						  - (round(isnull(S_AUG,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_AUG,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_AUG,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_AUG,0)* @varKSCOEFF,0) end,
		d8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1) from dbo.days_month(8,@cYear)d) else null end,
		S_SEN = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '9'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '9') AS C ) 
						  - (round(isnull(S_SEN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_SEN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_SEN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_SEN,0)* @varKSCOEFF,0) end, 
		d9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1) from dbo.days_month(9,@cYear)d) else null end,
		S_OKT = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '10'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '10') AS C ) 
						  - (round(isnull(S_OKT,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_OKT,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_OKT,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_OKT,0)* @varKSCOEFF,0) end, 
		d10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1) from dbo.days_month(10,@cYear)d) else null end,
		S_NOV = case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '11'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '11') AS C ) 
						  - (round(isnull(S_NOV,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_NOV,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_NOV,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_NOV,0)* @varKSCOEFF,0) end, 
		d11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1) from dbo.days_month(11,@cYear)d) else null end,
		S_DEC =	case ((SELECT SUM(C.SUMMA) FROM(select summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '12'	
					     union all
					     select summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '12') AS C ) 
						  - (round(isnull(S_DEC,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_DEC,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_DEC,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_DEC,0)* @varKSCOEFF,0) end, 
		d12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1) from dbo.days_month(12,@cYear)d) else null end
	FROM #NDFL_13_i  where mode = 3

	
	--сумма удержанного налого С НАЧАЛА ГОДА
	CREATE TABLE #MONTHES ([MONTH] INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	INSERT INTO #MONTHES
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear
 		and 
		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND 
		E.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)
	UNION ALL
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
 		and
 		MONTH(DATE1)<= @nMonth 
 		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND
		SJC.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)	

	--сумма удержанного налога за месяц 
	INSERT INTO #NDFL_13_i (MODE,  S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6,S_JUL, D7,S_AUG, D8, S_SEN, D9,S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 
		MODE = 8,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null
	update	#NDFL_13_i	
	set 
		S_JAN = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 1 ),0),0), 
		S_FEB = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 2 ),0),0), 
		S_MART =round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 3 ),0),0),
		S_APR = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 4 ),0),0),
		S_MAY = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 5 ),0),0),
		S_JUN = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 6 ),0),0),
		S_JUL = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 7 ),0),0),
		S_AUG = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 8 ),0),0),
		S_SEN = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 9 ),0),0), 
		S_OKT = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 10 ),0),0),
		S_NOV = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 11 ),0),0), 
		S_DEC = round(isnull((SELECT isnull(summa,0) FROM #MONTHES where [month]= 12 ),0),0)
	FROM #NDFL_13_i where mode = 8
	
	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1)  from dbo.days_month(1,@cYear)d) else null end,
		d2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1)  from dbo.days_month(2,@cYear)d) else null end,
		d3 = case when isnull(S_MART,0) <>0 then (select max(d.date1)  from dbo.days_month(3,@cYear)d) else null end,
		d4 = case when isnull(S_APR,0) <>0 then (select max(d.date1)  from dbo.days_month(4,@cYear)d) else null end,
		d5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1)  from dbo.days_month(5,@cYear)d) else null end,
		d6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1)  from dbo.days_month(6,@cYear)d) else null end,
		d7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1)  from dbo.days_month(7,@cYear)d) else null end,
		d8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1)  from dbo.days_month(8,@cYear)d) else null end,
		d9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1)  from dbo.days_month(9,@cYear)d) else null end,
		d10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1)  from dbo.days_month(10,@cYear)d) else null end,
		d11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1)  from dbo.days_month(11,@cYear)d) else null end,
		d12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1)  from dbo.days_month(12,@cYear)d) else null end
	FROM #NDFL_13_i where mode = 8	
	
 	
	INSERT INTO #NDFL_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 7,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #NDFL_13_i where mode = 8
 	
	-- перечисления	НДФЛ по ставке 13%
	INSERT INTO #NDFL_13_i (MODE,  S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6,S_JUL, D7,S_AUG, D8, S_SEN, D9,S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 
		MODE = 10,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null



	DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
	DECLARE @SUMMA_NACH_ALL NUMERIC(18,2)


	update	#NDFL_13_i	
	set 
		d1 = (select max(d.date1)  from dbo.days_month(1,@cYear)d),
		d2 = (select max(d.date1)  from dbo.days_month(2,@cYear)d),
		d3 = (select max(d.date1)  from dbo.days_month(3,@cYear)d),
		d4 = (select max(d.date1)  from dbo.days_month(4,@cYear)d),
		d5 = (select max(d.date1)  from dbo.days_month(5,@cYear)d),
		d6 = (select max(d.date1)  from dbo.days_month(6,@cYear)d),
		d7 = (select max(d.date1)  from dbo.days_month(7,@cYear)d),
		d8 = (select max(d.date1)  from dbo.days_month(8,@cYear)d),
		d9 = (select max(d.date1)  from dbo.days_month(9,@cYear)d),
		d10 =(select max(d.date1)  from dbo.days_month(10,@cYear)d),
		d11 =(select max(d.date1)  from dbo.days_month(11,@cYear)d),
		d12 =(select max(d.date1)  from dbo.days_month(12,@cYear)d)
	FROM #NDFL_13_i where mode = 10	
	
	declare @db datetime ,
		@de datetime, 
		@SUMMA_PLAT_ALL1 NUMERIC(18,2),
		@SUMMA_NACH_ALL1 NUMERIC(18,2),
		@SUMMA_PLAT_ALL2 NUMERIC(18,2),
		@SUMMA_NACH_ALL2 NUMERIC(18,2),
		@SUMMA_PLAT_ALL3 NUMERIC(18,2),
		@SUMMA_NACH_ALL3 NUMERIC(18,2),
		@SUMMA_PLAT_ALL4 NUMERIC(18,2),
		@SUMMA_NACH_ALL4 NUMERIC(18,2),
		@SUMMA_PLAT_ALL5 NUMERIC(18,2),
		@SUMMA_NACH_ALL5 NUMERIC(18,2),
		@SUMMA_PLAT_ALL6 NUMERIC(18,2),
		@SUMMA_NACH_ALL6 NUMERIC(18,2),
		@SUMMA_PLAT_ALL7 NUMERIC(18,2),
		@SUMMA_NACH_ALL7 NUMERIC(18,2),
		@SUMMA_PLAT_ALL8 NUMERIC(18,2),
		@SUMMA_NACH_ALL8 NUMERIC(18,2),
		@SUMMA_PLAT_ALL9 NUMERIC(18,2),
		@SUMMA_NACH_ALL9 NUMERIC(18,2),
		@SUMMA_PLAT_ALL10 NUMERIC(18,2),
		@SUMMA_NACH_ALL10 NUMERIC(18,2),
		@SUMMA_PLAT_ALL11 NUMERIC(18,2),
		@SUMMA_NACH_ALL11 NUMERIC(18,2),
		@SUMMA_PLAT_ALL12 NUMERIC(18,2),
		@SUMMA_NACH_ALL12 NUMERIC(18,2)				
		
	set @db = @BEGIN_YEAR
	set @de = (select d1  FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL1 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL1 OUT

	set @de = (select d2  FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL2 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL2 OUT

	set @de = (select d3  FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL3 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL3 OUT

	set @de = (select d4 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL4 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL4 OUT

	set @de = (select d5 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL5 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL5 OUT

	set @de = (select d6 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL6 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL6 OUT

	set @de = (select d7 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL7 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL7 OUT

	set @de = (select d8 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL8 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL8 OUT

	set @de = (select d9 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL9 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL9 OUT

	set @de = (select d10 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL10 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL10 OUT

	set @de = (select d11 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL11 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL11 OUT

	set @de = (select d12 FROM #NDFL_13_i where mode = 10)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL12 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL12 OUT
	
	--- расчет перечисленных сумм расчитывается в зависимости от удержанных сум, 
	---  если получившаяся перечисленная сумма больше начисленной , то перечисленную сумму обрезаем до начисленной
	UPDATE #NDFL_13_i
	 SET S_JAN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select S_JAN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL1) ELSE 0 END), 0)),													
		 S_FEB = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL2 * (CASE WHEN @SUMMA_NACH_ALL2 > 0 THEN ((select S_FEB from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL2) ELSE 0 END), 0)),
		 S_MART= CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL3 * (CASE WHEN @SUMMA_NACH_ALL3 > 0 THEN ((select S_MART from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL3) ELSE 0 END), 0)), 
		 S_APR = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL4 * (CASE WHEN @SUMMA_NACH_ALL4 > 0 THEN ((select S_APR from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL4) ELSE 0 END), 0)),
		 S_MAY = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL5 * (CASE WHEN @SUMMA_NACH_ALL5 > 0 THEN ((select S_MAY from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL5) ELSE 0 END), 0)),
		 S_JUN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL6 * (CASE WHEN @SUMMA_NACH_ALL6 > 0 THEN ((select S_JUN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL6) ELSE 0 END), 0)),
		 S_JUL = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL7 * (CASE WHEN @SUMMA_NACH_ALL7 > 0 THEN ((select S_JUL from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL7) ELSE 0 END), 0)),
		 S_AUG = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL8 * (CASE WHEN @SUMMA_NACH_ALL8 > 0 THEN ((select S_AUG from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL8) ELSE 0 END), 0)),
		 S_SEN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL9 * (CASE WHEN @SUMMA_NACH_ALL9 > 0 THEN ((select S_SEN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL9) ELSE 0 END), 0)),
		 S_OKT = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL10 * (CASE WHEN @SUMMA_NACH_ALL10 > 0 THEN ((select S_OKT from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL10) ELSE 0 END), 0)),
		 S_NOV = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL11 * (CASE WHEN @SUMMA_NACH_ALL11 > 0 THEN ((select S_NOV from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL11) ELSE 0 END), 0)),
		 S_DEC = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL12 * (CASE WHEN @SUMMA_NACH_ALL12 > 0 THEN ((select S_DEC from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL12) ELSE 0 END), 0))
	from #NDFL_13_i where mode = 10

			
	UPDATE #NDFL_13_i
	 SET S_JAN = CASE WHEN S_JAN > ISNULL((select S_JAN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_JAN from #NDFL_13_i where mode = 5),0))
					  ELSE S_JAN END,													
		
		 S_FEB = CASE WHEN S_FEB > ISNULL((select S_FEB from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_FEB from #NDFL_13_i where mode = 5),0))
					  ELSE S_FEB END,
		
		 S_MART= CASE WHEN S_MART > ISNULL((select S_MART from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_MART from #NDFL_13_i where mode = 5),0))
					  ELSE S_MART END, 
		
		 S_APR = CASE WHEN S_APR > ISNULL((select S_APR from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_APR from #NDFL_13_i where mode = 5),0))
					  ELSE S_APR END,
		
		 S_MAY = CASE WHEN S_MAY > ISNULL((select S_MAY from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_MAY from #NDFL_13_i where mode = 5),0))
					  ELSE S_MAY END,
		
		 S_JUN = CASE WHEN S_JUN > ISNULL((select S_JUN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_JUN from #NDFL_13_i where mode = 5),0))
					  ELSE S_JUN END,
		
		 S_JUL = CASE WHEN S_JUL> ISNULL((select S_JUL from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_JUL from #NDFL_13_i where mode = 5),0))
					  ELSE S_JUL END,
		
		 S_AUG = CASE WHEN S_AUG > ISNULL((select S_AUG from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_AUG from #NDFL_13_i where mode = 5),0))
					  ELSE S_AUG END,
		
		 S_SEN = CASE WHEN S_SEN > ISNULL((select S_SEN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_SEN from #NDFL_13_i where mode = 5),0))
					  ELSE S_SEN END,
		
		 S_OKT = CASE WHEN S_OKT > ISNULL((select S_OKT from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_OKT from #NDFL_13_i where mode = 5),0))
					  ELSE S_OKT END,
		
		 S_NOV = CASE WHEN S_NOV > ISNULL((select S_NOV from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_NOV from #NDFL_13_i where mode = 5),0))
					  ELSE S_NOV END,
		
		 S_DEC = CASE WHEN S_DEC > ISNULL((select S_DEC from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_DEC from #NDFL_13_i where mode = 5),0))
					  ELSE S_DEC END
	from #NDFL_13_i where mode = 10		



	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then d1 else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then d2 else null end,
		d3 = case when isnull(S_MART,0) <> 0 then d3 else null end,
		d4 = case when isnull(S_APR,0) <> 0 then d4 else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then d5 else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then d6 else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then d7 else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then d8 else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then d9 else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then d10 else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then d11 else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then d12 else null end
	FROM #NDFL_13_i where mode = 10	


--	--Перечисленная сумма по всем за период
----	EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
--	EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
--	--Начисленная сумма по всем за период
--	EXEC dbo.SA_NDFL_NACHISL @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_NACH_ALL OUT
--	--select @BEGIN_YEAR, @DATE, @DEP_LINK,	@SUMMA_PLAT_ALL, @SUMMA_NACH_ALL
--	--Перечисленная за сотрудника	
--	--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))
	INSERT INTO #NDFL_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 9,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_FEB,0) - isnull(S_JAN,0) , 
		S_MART =isnull(S_MART,0) - isnull(S_FEB,0) ,
		S_APR = isnull(S_APR,0) - isnull(S_MART,0),
		S_MAY = isnull(S_MAY,0) - isnull(S_APR,0),
		S_JUN = isnull(S_JUN,0) - isnull(S_MAY,0),
		S_JUL = isnull(S_JUL,0) - isnull(S_JUN,0),
		S_AUG = isnull(S_AUG,0) - isnull(S_JUL,0),
		S_SEN = isnull(S_SEN,0) - isnull(S_AUG,0), 
		S_OKT = isnull(S_OKT,0) - isnull(S_SEN,0),
		S_NOV = isnull(S_NOV,0) - isnull(S_OKT,0), 
		S_DEC = isnull(S_DEC,0) - isnull(S_NOV,0)
	FROM #NDFL_13_i where mode = 10	
	
	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then (select d1 from #NDFL_13_i where mode = 10) else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then (select d2 from #NDFL_13_i where mode = 10) else null end,
		d3 = case when isnull(S_MART,0) <> 0 then (select d3 from #NDFL_13_i where mode = 10) else null end,
		d4 = case when isnull(S_APR,0) <> 0 then (select d4 from #NDFL_13_i where mode = 10)  else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then (select d5 from #NDFL_13_i where mode = 10) else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then (select d6 from #NDFL_13_i where mode = 10) else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then (select d7 from #NDFL_13_i where mode = 10) else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then (select d8 from #NDFL_13_i where mode = 10) else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then (select d9 from #NDFL_13_i where mode = 10) else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then (select d10 from #NDFL_13_i where mode = 10) else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then (select d11 from #NDFL_13_i where mode = 10) else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then (select d12 from #NDFL_13_i where mode = 10) else null end
	FROM #NDFL_13_i where mode = 9		
	
	------------------------------------------------
	--- 15.Доходы , облагаемая база  - ставка 35%
	-------------------------------------------------
	/*	CREATE  TABLE  #vid_dohod_not13 (LINK_empl INT, LINK_face INT, month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, percent_stav varchar(2) )
	insert into #vid_dohod_not13	
	select s.link_empl, 
		   s.link_face,
		   s.month_end,
		   s.year_end,
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   percent_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from S_J_C_SHORT  S
		INNER JOIN DICTIONARY_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 AND S.LINK_DEP = @DEP_LINK 
		 AND S.link_empl = @LINK_EMPL 
		 and S.link_inc is not null
	group by s.link_empl, s.link_face , s.month_end, s.year_end,s.link_inc,s.link_dep, d.sname, d.name, d.flag
	*/

	select j.link_empl,  
		   d.name  , 
		   d.sname , 
		   j.period_begin, 
		   j.period_end, 
		   sum(j.summa) as summa , 
		   p.link_inc

	into #Dohod_35  	
	from   CALCULATE_JURNAL j
		INNER JOIN #EMPLS R  ON  J.link_empl = R.LINK
		inner join pays  p on  p.link = j.link_pays and  p.link_inc is not null 
		inner join #DICT_TYP_INCOMS d on d.link = p.link_inc  and  D.FLAG = 4  	
	where 
 		P.OBJECT = 1
		AND P.LINK in (Select LINK_PAYS from  dbo.NDFL_GroupTax() )   /*  dbo.NDFL_GroupTax() */ 
		AND  month(J.PERIOD_BEGIN) <=@nMonth and  year(J.PERIOD_BEGIN) = @cYear
		/*AND (	@Status <> 1 AND J.LINK_EMPL = @LINK_EMPL /*Если не основной сотрудник, то доход по своему табельному номеру*/
				or
		@Status = 1     and  R.LINK_FACE = @LINK_PERS /*Если основной сотрудник, то доход по всем табельным номерам*/
		)*/
		AND J.LINK_DEP = @DEP_LINK 
	group by j.link_empl, d.sname ,d.name  , j.period_begin, j.period_end, p.link_inc  

	--- Суммы доходов сгруппированнные по коду дохода по месяцам
	CREATE  TABLE #Dohod_35_m( LINK_EMPL int, name varchar(254), sname varchar(3),link_inc int, NUM1 int,summa_1 NUMERIC(10,2), d1 datetime,NUM2 int, summa_2 NUMERIC(10,2), d2 datetime,
							NUM3 int,summa_3 NUMERIC(10,2), d3 datetime,NUM4 int, summa_4 NUMERIC(10,2), d4 datetime,NUM5 int, summa_5 NUMERIC(10,2), d5 datetime,
							NUM6 int,summa_6 NUMERIC(10,2), d6 datetime,NUM7 int, summa_7 NUMERIC(10,2), d7 datetime,NUM8 int, summa_8 NUMERIC(10,2), d8 datetime,
							NUM9 int,summa_9 NUMERIC(10,2), d9 datetime,NUM10 int, summa_10 NUMERIC(10,2), d10 datetime,NUM11 int, summa_11 NUMERIC(10,2), d11 datetime,
							NUM12 int,summa_12 NUMERIC(10,2), d12 datetime)
	INSERT INTO #Dohod_35_m	

	select  d.link_empl,  
		    d.name  , 
		    d.sname , 
		    d.link_inc,
		    [NUM1] = 1,
			[summa_1] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC),
			[d1] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC),
			[num2] = 2,
			[summa_2] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC),
			[d2] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC),  
			[num3] = 3,
			[summa_3] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC) ,
			[d3] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC), 
			[num4] = 4,
			[summa_4] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC) ,
			[d4] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC),	
			[num5]= 5,
			[summa_5] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC) ,
			[d5] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC),
			[num6]= 6,
			[summa_6] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC) ,
			[d6] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC),
			[num7]= 7,
			[summa_7]  = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC),
			[d7] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC),
			[num8]= 8,
			[summa_8] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC),
			[d8]  = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC),		
			[num9]= 9,
			[summa_9] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC) ,
			[d9] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC), 
			[num10]= 10,
			[summa_10] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC) ,
			[d10] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC),
			[num11]= 11,
			[summa_11] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC) ,
			[d11] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC),
			[num12]= 12,
			[summa_12] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC) ,
			[d12] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC)  

	from #Dohod_35 d 
	group by d.link_empl, d.sname ,d.name,  d.link_inc	
	

	--- всего за месяц 
	CREATE  TABLE #Dohod_35_i (MODE INT, S_JAN NUMERIC(10,2), d1 datetime, S_FEB NUMERIC(10,2), d2 datetime,  S_MART NUMERIC(10,2), d3 datetime,  S_APR NUMERIC(10,2), d4 datetime,
							  S_MAY NUMERIC(10,2), d5 datetime,  S_JUN NUMERIC(10,2), d6 datetime, S_JUL NUMERIC(10,2), d7 datetime, S_AUG NUMERIC(10,2), d8 datetime,
							  S_SEN NUMERIC(10,2), d9 datetime, S_OKT NUMERIC(10,2), d10 datetime,  S_NOV NUMERIC(10,2), d11 datetime, S_DEC NUMERIC(10,2), d12 datetime)
	INSERT INTO #Dohod_35_i
	SELECT
		MODE = 1,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 , 
		null,
		S_MART = 0, 
		null,
		S_APR = 0, 
		null,
		S_MAY = 0, 
		null,
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0, 
		null,
		S_SEN = 0,
		null,
		S_OKT = 0, 
		null,
		S_NOV = 0, 
		null,
		S_DEC = 0,
		null
		 
	UPDATE #Dohod_35_i
	SET	S_JAN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '01' ),0),
		D1 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '01'), 
		S_FEB = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '02' ),0),
		D2 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '02'), 
		S_MART= round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '03' ),0),
		D3 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '03'), 
		S_APR = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '04' ),0), 
		D4 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '04'), 
		S_MAY = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '05' ),0),
		D5 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '05'), 
		S_JUN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '06' ),0),
		D6 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '06'), 
		S_JUL = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '07' ),0),
		D7 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '07'), 
		S_AUG = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '08' ),0),
		D8 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '08'), 
		S_SEN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '09' ),0),
		D9 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '09'), 
		S_OKT = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '10' ),0),
		D10 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '10'), 
		S_NOV = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '11' ),0),
		D11 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '11'), 
		S_DEC = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '12' ),0), 
		D12 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '12') 
	FROM #Dohod_35_i where mode = 1	
	
	--- всего с нарастающим итогом с начала года 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0),
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0),
		S_MART= isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0),
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_35_i where mode = 1
		

	------------------------------------------------
	--- 16. НДФЛ по ставке 35%
	------------------------------------------------
	--сумма начисленного налога С НАЧАЛА ГОДА
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 3,
		S_JAN = round(isnull(S_JAN,0)*0.35,0),
		S_FEB = round(isnull(S_FEB,0)*0.35,0), 
		S_MART = round(isnull(S_MART,0)*0.35,0),
		S_APR = round(isnull(S_APR,0)*0.35,0),
		S_MAY = round(isnull(S_MAY,0)*0.35,0),
		S_JUN = round(isnull(S_JUN,0)*0.35,0),
		S_JUL = round(isnull(S_JUL,0)*0.35,0),
		S_AUG = round(isnull(S_AUG,0)*0.35,0),
		S_SEN = round(isnull(S_SEN,0)*0.35,0), 
		S_OKT = round(isnull(S_OKT,0)*0.35,0),
		S_NOV = round(isnull(S_NOV,0)*0.35,0), 
		S_DEC = round(isnull(S_DEC,0)*0.35,0)
	FROM #Dohod_35_i where mode = 2
	


	--сумма начисленного налога за месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6,S_JUL, D7,S_AUG, D8, S_SEN, D9,S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 4,
		S_JAN = round(isnull(S_JAN,0)*0.35,0),
		D1,  
		S_FEB = round(isnull(S_FEB,0)*0.35,0), 
		D2,
		S_MART =round(isnull(S_MART,0)*0.35,0),
		D3,
		S_APR = round(isnull(S_APR,0)*0.35,0),
		D4,
		S_MAY = round(isnull(S_MAY,0)*0.35,0),
		D5,
		S_JUN = round(isnull(S_JUN,0)*0.35,0),
		D6,
		S_JUL = round(isnull(S_JUL,0)*0.35,0),
		D7,
		S_AUG = round(isnull(S_AUG,0)*0.35,0),
		D8,
		S_SEN = round(isnull(S_SEN,0)*0.35,0), 
		D9,
		S_OKT = round(isnull(S_OKT,0)*0.35,0),
		D10,
		S_NOV = round(isnull(S_NOV,0)*0.35,0), 
		D11,
		S_DEC = round(isnull(S_DEC,0)*0.35,0),
		D12
	FROM #Dohod_35_i  where mode = 1
	
	--сумма удержанного налого С НАЧАЛА ГОДА
	delete from #MONTHES
	
	--CREATE TABLE #MONTHES ([MONTH] INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	INSERT INTO #MONTHES
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 5)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
 		and
 		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND 
		E.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)
	UNION ALL
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 5)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
		and 
		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND
		SJC.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)		
	
	--сумма удержанного налога за месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 5, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL
	
	UPDATE 	#Dohod_35_i
	Set
		MODE = 5,
		S_JAN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 1 ),0),0), 
		D1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1)  from dbo.days_month(1,@cYear)d) else null end,
		S_FEB = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 2 ),0),0), 
		D2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1)  from dbo.days_month(2,@cYear)d) else null end,
		S_MART =isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 3 ),0),0),
		D3 = case when isnull(S_MART,0) <>0 then (select max(d.date1)  from dbo.days_month(3,@cYear)d) else null end,
		S_APR = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 4 ),0),0),
		D4 = case when isnull(S_APR,0) <>0 then (select max(d.date1)  from dbo.days_month(4,@cYear)d) else null end,
		S_MAY = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 5 ),0),0),
		D5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1)  from dbo.days_month(5,@cYear)d) else null end,
		S_JUN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 6 ),0),0),
		D6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1)  from dbo.days_month(6,@cYear)d) else null end,
		S_JUL = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 7 ),0),0),
		D7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1)  from dbo.days_month(7,@cYear)d) else null end,
		S_AUG = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 8 ),0),0),
		D8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1)  from dbo.days_month(8,@cYear)d) else null end,
		S_SEN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 9 ),0),0), 
		D9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1)  from dbo.days_month(9,@cYear)d) else null end,
		S_OKT = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 10 ),0),0),
		D10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1)  from dbo.days_month(10,@cYear)d) else null end,
		S_NOV = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 11 ),0),0), 
		D11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1)  from dbo.days_month(11,@cYear)d) else null end,
		S_DEC = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 12 ),0),0),
		D12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1)  from dbo.days_month(12,@cYear)d) else null end
	FROM #Dohod_35_i  where mode = 5
	
	
	--сумма удержанного за год по месяцам
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 6,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_35_i  where mode = 5 
	

	------------------------------------------------
	-- 17. Перечисление НДФЛ по ставке 35%
	------------------------------------------------
	--месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 8, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL
	update	#Dohod_35_i	
	set 
		d1 = (select max(d.date1)  from dbo.days_month(1,@cYear)d),
		d2 = (select max(d.date1)  from dbo.days_month(2,@cYear)d),
		d3 = (select max(d.date1)  from dbo.days_month(3,@cYear)d),
		d4 = (select max(d.date1)  from dbo.days_month(4,@cYear)d),
		d5 = (select max(d.date1)  from dbo.days_month(5,@cYear)d),
		d6 = (select max(d.date1)  from dbo.days_month(6,@cYear)d),
		d7 = (select max(d.date1)  from dbo.days_month(7,@cYear)d),
		d8 = (select max(d.date1)  from dbo.days_month(8,@cYear)d),
		d9 = (select max(d.date1)  from dbo.days_month(9,@cYear)d),
		d10 =(select max(d.date1)  from dbo.days_month(10,@cYear)d),
		d11 =(select max(d.date1)  from dbo.days_month(11,@cYear)d),
		d12 =(select max(d.date1)  from dbo.days_month(12,@cYear)d)
	FROM #Dohod_35_i where mode = 8	
	
	set @db = @BEGIN_YEAR
	set @de = (select d1  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL1 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL1 OUT

	set @de = (select d2  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL2 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL2 OUT

	set @de = (select d3  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL3 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL3 OUT

	set @de = (select d4 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL4 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL4 OUT

	set @de = (select d5 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL5 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL5 OUT

	set @de = (select d6 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL6 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL6 OUT

	set @de = (select d7 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL7 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL7 OUT

	set @de = (select d8 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL8 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL8 OUT

	set @de = (select d9 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL9 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL9 OUT

	set @de = (select d10 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL10 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL10 OUT

	set @de = (select d11 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL11 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL11 OUT

	set @de = (select d12 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL12 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL12 OUT

	--- расчет перечисленных сумм расчитывается в зависимости от удержанных сум, 
	---  если получившаяся перечисленная сумма больше начисленной , то перечисленную сумму обрезаем до начисленной
	UPDATE #Dohod_35_i
	 SET S_JAN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select S_JAN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL1) ELSE 0 END), 0)),													
		 S_FEB = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL2 * (CASE WHEN @SUMMA_NACH_ALL2 > 0 THEN ((select S_FEB from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL2) ELSE 0 END), 0)),
		 S_MART= CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL3 * (CASE WHEN @SUMMA_NACH_ALL3 > 0 THEN ((select S_MART from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL3) ELSE 0 END), 0)), 
		 S_APR = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL4 * (CASE WHEN @SUMMA_NACH_ALL4 > 0 THEN ((select S_APR from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL4) ELSE 0 END), 0)),
		 S_MAY = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL5 * (CASE WHEN @SUMMA_NACH_ALL5 > 0 THEN ((select S_MAY from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL5) ELSE 0 END), 0)),
		 S_JUN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL6 * (CASE WHEN @SUMMA_NACH_ALL6 > 0 THEN ((select S_JUN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL6) ELSE 0 END), 0)),
		 S_JUL = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL7 * (CASE WHEN @SUMMA_NACH_ALL7 > 0 THEN ((select S_JUL from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL7) ELSE 0 END), 0)),
		 S_AUG = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL8 * (CASE WHEN @SUMMA_NACH_ALL8 > 0 THEN ((select S_AUG from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL8) ELSE 0 END), 0)),
		 S_SEN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL9 * (CASE WHEN @SUMMA_NACH_ALL9 > 0 THEN ((select S_SEN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL9) ELSE 0 END), 0)),
		 S_OKT = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL10 * (CASE WHEN @SUMMA_NACH_ALL10 > 0 THEN ((select S_OKT from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL10) ELSE 0 END), 0)),
		 S_NOV = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL11 * (CASE WHEN @SUMMA_NACH_ALL11 > 0 THEN ((select S_NOV from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL11) ELSE 0 END), 0)),
		 S_DEC = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL12 * (CASE WHEN @SUMMA_NACH_ALL12 > 0 THEN ((select S_DEC from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL12) ELSE 0 END), 0))
	from #Dohod_35_i where mode = 8
			
	UPDATE #Dohod_35_i
	 SET S_JAN = CASE WHEN S_JAN > ISNULL((select S_JAN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_JAN from #Dohod_35_i where mode = 3),0))
					  ELSE S_JAN END,													
		
		 S_FEB = CASE WHEN S_FEB > ISNULL((select S_FEB from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_FEB from #Dohod_35_i where mode = 3),0))
					  ELSE S_FEB END,
		
		 S_MART= CASE WHEN S_MART > ISNULL((select S_MART from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_MART from #Dohod_35_i where mode = 3),0))
					  ELSE S_MART END, 
		
		 S_APR = CASE WHEN S_APR > ISNULL((select S_APR from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_APR from #Dohod_35_i where mode = 3),0))
					  ELSE S_APR END,
		
		 S_MAY = CASE WHEN S_MAY > ISNULL((select S_MAY from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_MAY from #Dohod_35_i where mode = 3),0))
					  ELSE S_MAY END,
		
		 S_JUN = CASE WHEN S_JUN > ISNULL((select S_JUN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_JUN from #Dohod_35_i where mode = 3),0))
					  ELSE S_JUN END,
		
		 S_JUL = CASE WHEN S_JUL> ISNULL((select S_JUL from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_JUL from #Dohod_35_i where mode = 3),0))
					  ELSE S_JUL END,
		
		 S_AUG = CASE WHEN S_AUG > ISNULL((select S_AUG from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_AUG from #Dohod_35_i where mode = 3),0))
					  ELSE S_AUG END,
		
		 S_SEN = CASE WHEN S_SEN > ISNULL((select S_SEN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_SEN from #Dohod_35_i where mode = 3),0))
					  ELSE S_SEN END,
		
		 S_OKT = CASE WHEN S_OKT > ISNULL((select S_OKT from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_OKT from #Dohod_35_i where mode = 3),0))
					  ELSE S_OKT END,
		
		 S_NOV = CASE WHEN S_NOV > ISNULL((select S_NOV from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_NOV from #Dohod_35_i where mode = 3),0))
					  ELSE S_NOV END,
		
		 S_DEC = CASE WHEN S_DEC > ISNULL((select S_DEC from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select S_DEC from #Dohod_35_i where mode = 3),0))
					  ELSE S_DEC END
	from #Dohod_35_i where mode = 8	
---CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select S_JAN from #Dohod_35_i where mode = 5)/ @SUMMA_NACH_ALL1) ELSE 0 END),0)),
	
	update	#Dohod_35_i 
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then d1 else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then d2 else null end,
		d3 = case when isnull(S_MART,0) <> 0 then d3 else null end,
		d4 = case when isnull(S_APR,0) <> 0 then d4 else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then d5 else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then d6 else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then d7 else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then d8 else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then d9 else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then d10 else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then d11 else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then d12 else null end
	FROM #Dohod_35_i  where mode = 8	
	

	--год
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 7,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_FEB,0) - isnull(S_JAN,0) , 
		S_MART =isnull(S_MART,0) - isnull(S_FEB,0) ,
		S_APR = isnull(S_APR,0) - isnull(S_MART,0),
		S_MAY = isnull(S_MAY,0) - isnull(S_APR,0),
		S_JUN = isnull(S_JUN,0) - isnull(S_MAY,0),
		S_JUL = isnull(S_JUL,0) - isnull(S_JUN,0),
		S_AUG = isnull(S_AUG,0) - isnull(S_JUL,0),
		S_SEN = isnull(S_SEN,0) - isnull(S_AUG,0), 
		S_OKT = isnull(S_OKT,0) - isnull(S_SEN,0),
		S_NOV = isnull(S_NOV,0) - isnull(S_OKT,0), 
		S_DEC = isnull(S_DEC,0) - isnull(S_NOV,0)
	FROM #Dohod_35_i where mode = 8	
	
	------------------------------------------------
	-- 14. Расчет сумм материальной выгоды на дату погашения
	------------------------------------------------
	
	------------------------------------------------
	-- 18.Взыскание/Возврат НДФЛ
	------------------------------------------------
	
	------------------------------------------------
	-- 19. Расчеты по налогу
	------------------------------------------------
	
	-- задолженность по ндфл на начало месяца
	--------
	
	CREATE  TABLE #NALOG_RASH (Mode int, S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2),SNN NUMERIC(10,2), SNU NUMERIC(10,2), DOLG_NAEND NUMERIC(10,2), DOLG_NPEND NUMERIC(10,2))
	insert into #NALOG_RASH
	SELECT		
		MODE = 1,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0,
		snn = 0,
		snu = 0,
		DOLG_NAEND  = 0,
		DOLG_NPEND = 0

	
	-- за налогоплательщиком долг если в плюсе
	-- если в минусе то за налоговым агентом
		
	UPDATE #NALOG_RASH 
	set S_JAN = round(isnull(((n1.s_jan + n2.s_jan) - (U1.s_jan + U2.s_jan)  ),0),0) ,
		S_FEB = round(isnull(((n1.S_FEB + n2.S_FEB) - (U1.S_FEB + U2.S_FEB) ),0),0),
		S_MART= round(isnull(((n1.S_MART + n2.S_MART) - (U1.S_MART + U2.S_MART)),0),0),
		S_APR = round(isnull(((n1.S_APR + n2.S_APR) - (U1.S_APR + U2.S_APR)),0),0),
		S_MAY = round(isnull(((n1.S_MAY + n2.S_MAY) - (U1.S_MAY + U2.S_MAY)),0),0),
		S_JUN = round(isnull(((n1.S_JUN + n2.S_JUN) - (U1.S_JUN + U2.S_JUN)),0),0),
		S_JUL = round(isnull(((n1.S_JUL + n2.S_JUL) - (U1.S_JUL + U2.S_JUL)),0),0),
		S_AUG = round(isnull(((n1.S_AUG + n2.S_AUG) - (U1.S_AUG + U2.S_AUG)),0),0),
		S_SEN = round(isnull(((n1.S_SEN + n2.S_SEN) - (U1.S_SEN + U2.S_SEN)),0),0),
		S_OKT = round(isnull(((n1.S_OKT + n2.S_OKT) - (U1.S_OKT + U2.S_OKT)),0),0),
		S_NOV = round(isnull(((n1.S_NOV + n2.S_NOV) - (U1.S_NOV + U2.S_NOV)),0),0),
		S_DEC = round(isnull(((n1.S_DEC + n2.S_DEC) - (U1.S_DEC + U2.S_DEC)),0),0),
		
	 SNN = (COALESCE(Sn1.S_DEC,0)+COALESCE(Sn2.S_DEC,0)),
							
	 SNU = (COALESCE(SU1.S_DEC,0)+COALESCE(SU2.S_DEC,0))
	
	from #NDFL_13_i N1, #Dohod_35_i  N2 , #NDFL_13_i U1, #Dohod_35_i  U2, #NDFL_13_i SN1, #Dohod_35_i  SN2 ,  #NDFL_13_i SU1, #Dohod_35_i  SU2
		where n1.mode = 6
		  and n2.mode = 5 
		  and U1.MODE = 8
		  AND U2.MODE = 4	
		  AND Sn1.mode = 5
		  and Sn2.mode = 8 
		  and SU1.MODE = 7
		  AND SU2.MODE = 3	
		  
			
	-- долг за налоговым агентом		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	-- долг за налогоплательщиком
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 WHERE DOLG_NPEND <0

	insert into #NALOG_RASH
	SELECT		
		MODE = 2,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0,
		snn = 0,
		snu = 0,
		DOLG_NAEND  = 0,
		DOLG_NPEND = 0

	
	-- за налогоплательщиком долг если в плюсе
	-- если в минусе то за налоговым агентом
		
	UPDATE #NALOG_RASH 
	set S_JAN = case when isnull((select s_jan from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select s_jan from #NALOG_RASH where mode = 1),0) end ,
		S_FEB = case when isnull((select S_FEB from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_FEB from #NALOG_RASH where mode = 1),0) end ,
		S_MART= case when isnull((select S_MART from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_MART from #NALOG_RASH where mode = 1),0) end ,
		S_APR = case when isnull((select S_APR from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_APR from #NALOG_RASH where mode = 1),0) end ,
		S_MAY = case when isnull((select S_MAY from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_MAY from #NALOG_RASH where mode = 1),0) end ,
		S_JUN = case when isnull((select S_JUN from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_JUN from #NALOG_RASH where mode = 1),0) end ,
		S_JUL = case when isnull((select S_JUL from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_JUL from #NALOG_RASH where mode = 1),0) end ,
		S_AUG = case when isnull((select S_AUG from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_AUG from #NALOG_RASH where mode = 1),0) end ,
		S_SEN = case when isnull((select S_SEN from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_SEN from #NALOG_RASH where mode = 1),0) end ,
		S_OKT = case when isnull((select S_OKT from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_OKT from #NALOG_RASH where mode = 1),0) end ,
		S_NOV = case when isnull((select S_NOV from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_NOV from #NALOG_RASH where mode = 1),0) end ,
		S_DEC = case when isnull((select S_DEC from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select S_DEC from #NALOG_RASH where mode = 1),0) end ,
		
	 SNN = SNN,
							
	 SNU = SNU
	
	from #NALOG_RASH
		where mode = 2 
		 
			
	-- долг за налоговым агентом		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	-- долг за налогоплательщиком
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 WHERE DOLG_NPEND <0

 ----Начислено НДФЛ всего, в том числе по ставкам
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 3, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
		 
		
	UPDATE #NALOG_RASH 
	set S_JAN = (select (n1.s_jan + n2.s_jan) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4),
		S_FEB = (select (n1.S_FEB + n2.S_FEB) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_MART =(select (n1.S_MART + n2.S_MART) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_APR = (select (n1.S_APR + n2.S_APR) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_MAY = (select (n1.S_MAY + n2.S_MAY) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_JUN = (select (n1.S_JUN + n2.S_JUN) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_JUL = (select (n1.S_JUL + n2.S_JUL) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_AUG = (select (n1.S_AUG + n2.S_AUG) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_SEN = (select (n1.S_SEN + n2.S_SEN) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_OKT = (select (n1.S_OKT + n2.S_OKT) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_NOV = (select (n1.S_NOV + n2.S_NOV) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_DEC = (select (n1.S_DEC + n2.S_DEC) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 )
	FROM #NALOG_RASH
		where Mode = 3
	--- 13%
	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 4, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	if @varKSCOEFF = 0.13
	begin	
		UPDATE #NALOG_RASH 
		set S_JAN = (select s_jan from #NDFL_13_i where mode = 6),
			S_FEB = (select S_FEB from #NDFL_13_i where mode = 6),
			S_MART =(select S_MART from #NDFL_13_i where mode = 6),
			S_APR = (select S_APR from #NDFL_13_i where mode = 6),
			S_MAY = (select S_MAY from #NDFL_13_i where mode = 6),
			S_JUN = (select S_JUN from #NDFL_13_i where mode = 6),
			S_JUL = (select S_JUL from #NDFL_13_i where mode = 6),
			S_AUG = (select S_AUG from #NDFL_13_i where mode = 6),
			S_SEN = (select S_SEN from #NDFL_13_i where mode = 6),
			S_OKT = (select S_OKT from #NDFL_13_i where mode = 6),
			S_NOV = (select S_NOV from #NDFL_13_i where mode = 6),
			S_DEC = (select S_DEC from #NDFL_13_i where mode = 6),


		 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 5),
								
		 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 7)
		from #NALOG_RASH 
			where Mode = 4	

		UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
		from #NALOG_RASH 
			where Mode = 4	
		
		UPDATE #NALOG_RASH 
			SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
		from #NALOG_RASH 
			where Mode = 4	
			and DOLG_NPEND <0
	end
		
	-- 35%	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 5, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
		
	UPDATE #NALOG_RASH 
	set S_JAN = (select s_jan from #Dohod_35_i  where mode = 4),
		S_FEB = (select S_FEB from #Dohod_35_i  where mode = 4),
		S_MART =(select S_MART from #Dohod_35_i  where mode = 4),
		S_APR = (select S_APR from #Dohod_35_i  where mode = 4),
		S_MAY = (select S_MAY from #Dohod_35_i  where mode = 4),
		S_JUN = (select S_JUN from #Dohod_35_i  where mode = 4),
		S_JUL = (select S_JUL from #Dohod_35_i  where mode = 4),
		S_AUG = (select S_AUG from #Dohod_35_i  where mode = 4),
		S_SEN = (select S_SEN from #Dohod_35_i  where mode = 4),
		S_OKT = (select S_OKT from #Dohod_35_i  where mode = 4),
		S_NOV = (select S_NOV from #Dohod_35_i  where mode = 4),
		S_DEC = (select S_DEC from #Dohod_35_i  where mode = 4),
	
	 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #Dohod_35_i  where mode = 3 ),
							
	 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #Dohod_35_i  where mode = 8 )
	from #NALOG_RASH 
		where Mode = 5
		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	from #NALOG_RASH 
		where Mode = 5
	
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
	from #NALOG_RASH 
		where Mode = 5	and DOLG_NPEND <0

	-- 30%
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 6, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	if @varKSCOEFF = 0.30
	begin	
		UPDATE #NALOG_RASH 
		set S_JAN = (select s_jan from #NDFL_13_i where mode = 6),
			S_FEB = (select S_FEB from #NDFL_13_i where mode = 6),
			S_MART =(select S_MART from #NDFL_13_i where mode = 6),
			S_APR = (select S_APR from #NDFL_13_i where mode = 6),
			S_MAY = (select S_MAY from #NDFL_13_i where mode = 6),
			S_JUN = (select S_JUN from #NDFL_13_i where mode = 6),
			S_JUL = (select S_JUL from #NDFL_13_i where mode = 6),
			S_AUG = (select S_AUG from #NDFL_13_i where mode = 6),
			S_SEN = (select S_SEN from #NDFL_13_i where mode = 6),
			S_OKT = (select S_OKT from #NDFL_13_i where mode = 6),
			S_NOV = (select S_NOV from #NDFL_13_i where mode = 6),
			S_DEC = (select S_DEC from #NDFL_13_i where mode = 6),


		 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NALOG_RASH where mode = 5),
								
		 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 7)
		from #NALOG_RASH 
			where Mode = 4	

		UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
		from #NALOG_RASH 
			where Mode = 4	
		
		UPDATE #NALOG_RASH 
			SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
		from #NALOG_RASH 
			where Mode = 4	
			and DOLG_NPEND <0
	end

	-- 15%
	INSERT INTO #NALOG_RASH
	SELECT 7, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	-- 9%
	INSERT INTO #NALOG_RASH
	SELECT 8, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	-- 6%
	INSERT INTO #NALOG_RASH
	SELECT 9, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	-- Удержано НДФЛ	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 10, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0

		
	UPDATE #NALOG_RASH 
	set S_JAN = isnull((select U1.s_jan + U2.s_jan  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5 ),0),
		S_FEB = isnull((select U1.S_FEB + U2.S_FEB  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_MART = isnull((select U1.S_MART + U2.S_MART  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_APR = isnull((select U1.S_APR + U2.S_APR  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_MAY = isnull((select U1.S_MAY + U2.S_MAY  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_JUN = isnull((select U1.S_JUN + U2.S_JUN  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_JUL = isnull((select U1.S_JUL + U2.S_JUL  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_AUG = isnull((select U1.S_AUG + U2.S_AUG  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_SEN = isnull((select U1.S_SEN + U2.S_SEN  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_OKT = isnull((select U1.S_OKT + U2.S_OKT  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_NOV = isnull((select U1.S_NOV + U2.S_NOV  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_DEC = isnull((select U1.S_DEC + U2.S_DEC  from #NDFL_13_i U1, #Dohod_35_i  U2	where u1.mode = 8 and u2.mode = 5),0)
	from #NALOG_RASH 
		where Mode = 10		

-------------------------------------------------------		
-- 20. Общая сумма налога по итогам налогового периода
-------------------------------------------------------
	CREATE  TABLE #ALL_NALOG_Y (PER_Stav varchar(4), S_NN NUMERIC(10,2), S_NU NUMERIC(10,2), S_PERECH NUMERIC(10,2), S_PERED NUMERIC(10,2), S_VOZV NUMERIC(10,2), S_ZACH NUMERIC(10,2),DOLG_NP NUMERIC(10,2),DOLG_NA NUMERIC(10,2))
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '6%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 9),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 9) ,
		S_PERECH =  case when isnull((select s_jan from #NALOG_RASH where mode = 9),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
		S_PERED = 0,
		S_VOZV = 0,
		S_ZACH = 0,
		DOLG_NP = 0,
		DOLG_NA = 0
		
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '6%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '6%'	
		and DOLG_NP <0		
	---
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '9%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 8),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 8) ,
		S_PERECH = case when isnull((select s_jan from #NALOG_RASH where mode = 8),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '9%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '9%'	
		and DOLG_NP <0	
	
	---
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '13%',
		S_NN = 0 ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	if @varKSCOEFF = 0.13
	begin	
		UPDATE #ALL_NALOG_Y 
		set S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 4),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 4) ,
			S_PERECH = case when isnull((select s_jan from #NALOG_RASH where mode = 4),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
			S_PERED = 0,
			S_VOZV = 0,
			S_ZACH = 0
		from #ALL_NALOG_Y 
			where PER_STAV = '13%'	
		
			UPDATE #ALL_NALOG_Y 
			SET DOLG_NP = S_NN - S_NU,  
				DOLG_NA = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '13%'	
			
			UPDATE #ALL_NALOG_Y 
				SET DOLG_NA = -DOLG_NP,
					DOLG_NP = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '13%'	
				and DOLG_NP <0	
	end
	----
	
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '15%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 7),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 7) ,
		S_PERECH = case when isnull((select s_jan from #NALOG_RASH where mode = 7),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '15%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '15%'	
		and DOLG_NP <0	
	----
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '30%',
		S_NN = 0 ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	

	if @varKSCOEFF = 0.30
	begin	
			
		UPDATE #ALL_NALOG_Y 
		set S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 6),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 6),
			S_PERECH = case when isnull((select s_jan from #NALOG_RASH where mode = 6),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
			S_PERED = 0,
			S_VOZV = 0,
			S_ZACH = 0
		from #ALL_NALOG_Y 
			where PER_STAV = '30%'	
		
			UPDATE #ALL_NALOG_Y 
			SET DOLG_NP = S_NN - S_NU,  
				DOLG_NA = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '30%'	
			
			UPDATE #ALL_NALOG_Y 
				SET DOLG_NA = -DOLG_NP,
					DOLG_NP = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '30%'	
				and DOLG_NP <0		
	end
	---
		
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '35%',
		S_NN = 0  ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
		set	S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 5),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 5),
			S_PERECH = case when isnull((select s_jan from #NALOG_RASH where mode = 5),0) > 0 then (SELECT TOP 1 S_DEC FROM #Dohod_35_i where mode = 8) else 0 end 
		from #ALL_NALOG_Y 
		where PER_STAV = '35%'
		
	UPDATE #ALL_NALOG_Y 
		SET DOLG_NP = S_NN - S_NU, DOLG_NA = 0
		from #ALL_NALOG_Y where PER_STAV = '35%'	
			
	UPDATE #ALL_NALOG_Y 
		SET DOLG_NA = -DOLG_NP, DOLG_NP = 0
		from #ALL_NALOG_Y where PER_STAV = '35%' and DOLG_NP <0		
	
-------------------------------------------------------	

	
--print '1. Налоговый агент и Налогоплательщик'
	---
	SELECT  d.*, CAST(  (CAST (d.DOCCOUNT AS INT) - @varKSCNT) AS VARCHAR(254) ) AS DOCCOUNT2 , r.* FROM #DEP d , #PERSON R  
	---
	
--print 'Дети'	
--print '3.  Стандартный налоговый вычет'	
	declare @count1 int,
			@count2 int
	set @count1 = 0			
 
	SELECT * FROM #RES_VICHET

	
--print 'Имущественный налоговый вычет'	
	set @count1 = 0			
	set @count1 = (SELECT count(*)	FROM #RES_IM_VICHET)		
	
	if 	@count1 < 1
	begin 
		insert into #RES_IM_VICHET
		select distinct	
			 null,null,null,' ',null,' ',' ',null,null,null,null,0,null,null
	end 
	select * from #RES_IM_VICHET
		order by code_ded

--print '4. Необлагаемые доходы'
	set @count1 = 0			
	set @count1 = (SELECT count(*)	FROM #RES_NE_VICHET)		
	
	if 	@count1 < 1
	begin 
		insert into #RES_NE_VICHET
		select distinct	
			 '',null,null,null,null,0,0,0,0,0,0,0,0,0,0,0,0 
	end 
	select * from #RES_NE_VICHET
					
	--select * from #RES_NonNDFL_VICHET
--print '5. Налоговые ставки'	
	
--print 'и Таблица 5.2 Виды доходов (доходы не по ставке 13%)'
	--select * from #RES_EMP_STATUS
	
	set @count1 = (select count(*) from #RES_EMP_STATUS )
	set @count2 = (select count(*) from #vid_dohod_not13 ) 

	if @count1 > 0 and @count1 >= @count2 
	begin
		update #RES_EMP_STATUS 
		set month_d = v.month_d, 
	   		year_d = v.year_d,
	   		link_inc = v.link_inc,
	   		link_dep = v.link_dep,
	   		sname = v.sname,
	   		name = v.name,
	   		flag = v.flag,
	   		perc_stav = v.perc_stav
		 from #RES_EMP_STATUS r, #vid_dohod_not13 v 
		 where v.year_d = @cYear	
	end  
	else	
		begin
			insert into #RES_EMP_STATUS 
			select distinct	
			   null, 
			   null,
			   null, 
			   null,
			   NULL,
			   [month_d] = v.month_d, 
	   		   [year_d] = v.year_d,
	   		   [link_inc] = v.link_inc,
	   		   [link_dep] = v.link_dep,
	   		   [sname] = v.sname,
	   		   [name] = v.name,
	   		   [flag] = v.flag,
	   		   [perc_stav] = v.perc_stav
			FROM 
				#vid_dohod_not13 v
	  end	

	select * from #RES_EMP_STATUS 


	--select * from  #vid_dohod_not13
	
--print '6.предыдущее место работы'	
	declare @countPrevInfo int
	set @countPrevInfo = 0
	set @countPrevInfo = (SELECT count(*)	FROM #DEP_Prev)
	
	if 	@countPrevInfo < 1
	begin 
		insert into #DEP_Prev
		select distinct	
			[LINK_DEP] = null,[NALOG] = ' ',[INN] = ' ',[KPP] = ' ',[OKATO] = ' ',[FULL_NAME] = ' ',[ADDRES] = ' ',[SUMMA_13]= 0
	end 
	SELECT * FROM #DEP_Prev
		
		
--print ' Сумма доходов, облагаемых по ставке 13% '	
	--set @count1 = 0
	--set @count1 = (SELECT count(*)	FROM #Prev_dohod)
	
	--if 	@count1 < 1
	--begin 
	--	insert into #Prev_dohod
	--	select distinct	
	--		[LINK_EMPL] = 1,
	--		[REF_TYP_INCOMS] = 0, 
	--		[COD_INC] = '.',
	--		[NAME_INC] = '.',
	--	    [SUMM_INC] = 0
	--end 
	--select * from #Prev_dohod	

--print ' Сумма необлагаемых доходов по ставке 13% '	
	set @count1 = 0
	if	@countPrevInfo < 1
	begin 
		delete from #Prev_dohod_NO
	end	
	
	set @count1 = (SELECT count(*)	FROM #Prev_dohod_NO)

	if 	@count1 < 1 
	begin 
		insert into #Prev_dohod_NO
		select distinct	
			[LINK_EMPL] = 0,[REF_TYP_INCOMS] = ' ',	[COD_INC] = ' ',[NAME_INC] = ' ', [SUMM_INC] = 0, [PER_YEAR] = ' '
	end 
	select * from #Prev_dohod_NO	
	
--print 'Налоговые вычеты с предыдущего места работы по типам'
	set @count1 = 0

	if	@countPrevInfo < 1
	begin 
		delete from #Prev_ded
	end	
	
	set @count1 = (SELECT count(*)	FROM #Prev_ded)
	
	if 	@count1 < 1 or 	@countPrevInfo < 1
	begin 
		insert into #Prev_ded
		select distinct	
			[LINK_EMPL] = 0,[LINK_DED] = 0,[CODE_DED] = ' ',[NAME_DED] = ' ',[SUMM_DED] = 0,[TYPE] = null,[PER_YEAR] = null
	end 	
	select * from #Prev_ded
--print '7. доходы облагаемые по ставке 13%'  	
--	select * from #Dohod_13	
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_13_1)
	
	if 	@count1 < 1
	begin 
		insert into #Dohod_13_1
		select 
			null,' ',' ',null,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,
			null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0																							
	end 	
	select * from #Dohod_13_1
--print ' Итого 13% месяц и год '
	select * from #Dohod_13_i
--print '8. необлагаемые суммы налогов'  
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_13_predel)
	if 	@count1 < 1
	begin 
		insert into #Dohod_13_predel
		select
			null, 
			null, 
			null, 
			0,
			0,
            0,          
            0,    
			0,        
            0,          
            0,          
            0,        
            0,      
            0,         
            0,         
            0,          
            0	
    end  
	select * from #Dohod_13_predel
--print ' Итого месяц и год'	
	select * from #Dohod_13_predel_i
--print '9. Сумма облагаемых доходов (месяц и год)'
	select * from #Obl_Dohod_i
--print '10. Вычеты фактически предоставленные , стандартные, имущестевнные, проффессиональные'
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #DED_FACT)
	if 	@count1 < 1
	begin 
		insert into #DED_FACT
		select
			null, 
			null, 
			null, 
			null,
			null,
            null,          
            null,         
       null,        
            0,          
            null,          
            null,        
            0,      
            null,         
            null,         
            0,          
            null,	
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,         
            0,          
            null
    end  
	select * from #DED_FACT 
--	select * from #DED_FACT_i
--	select * from #OBL_base_fi
		-- итоги по месяцам и за год 
		--	 mode = 1 и mode = 2
		
--print '11.Облагаемая база ставка 13% ' 	
		-- итоги по месяцам и за год 
		--	 mode = 3 и mode = 4
--print '12.НДФЛ по ставке 13% 	--сумма начисленного налого С НАЧАЛА ГОДА , за месяц'
		-- за месяц и год по начисленным 	 mode = 5 и mode = 6
		-- за месяц и год по удержанным 	 mode = 7 и mode = 8
		select * from #NDFL_13_i  order by mode

--print '15.ДОходы, облагаемая база со ставкой  35%'
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_35)
	
	if 	@count1 < 1
	begin 
		insert into #Dohod_35_m
		select 
		   [link_empl] = 1,  
		   [name]  = ' ', 
		   [sname] = ' ', 
		   [link_inc] = null,	
		   [NUM1] = null,
		   [summa_1] = null,
		   [d1] = null,
		   [num2] = null,
		   [summa_2] = null,
		   [d2] = null,
		   [num3] = null,
		   [summa_3] = null,
		   [d3] = null,
		   [num4] = null,
		   [summa_4] = null,
		   [d4] = null,
		   [num5]= null,
		   [summa_5] = null,
		   [d5] = null,
		   [num6]= null,
		   [summa_6] = null,
		   [d6] = null,
		   [num7]= null,
		   [summa_7]  = null,
		   [d7] = null,
		   [num8]= null,
		   [summa_8]  = null,
		   [d8]  = null,
		   [num9]= null,
		   [summa_9] = null,
		   [d9] = null,
		   [num10]= null,
		   [summa_10] = null,
		   [d10] = null,
		   [num11]= null,
		   [summa_11] = null,
		   [d11] = null,
		   [num12]= null,
		   [summa_12] = null ,
		   [d12] = null 
		    
	end		   
---	select * from #Dohod_35
	select * from #Dohod_35_m
--print 'Итого за месяц'	
--print '16.НДФЛ по ставке 13 %'
	select * from #Dohod_35_i
--print '17.Расчеты по налогу  и 20. общая сумма по итогам налогового периода '	
	select * from #NALOG_RASH	
	select * from #ALL_NALOG_Y

	---	

	---
	EXEC dbo.BufferClear

	DROP TABLE #E_SUBDIV
	DROP TABLE #S_OBOSOB
	DROP TABLE #P_OBOSOB	
	DROP TABLE #PERSON
	DROP TABLE #RES_VICHET
--	DROP TABLE #RES_CHILD_VICHET
	DROP TABLE #RES_IM_VICHET
	DROP TABLE #RES_NE_VICHET
	--DROP TABLE #RES_NonNDFL_VICHET
	DROP TABLE #RES_EMP_STATUS
	drop table #vid_dohod_not13
	DROP TABLE #DEP_Prev
	DROP TABLE #Prev_dohod	
	DROP TABLE #Prev_dohod_NO
	DROP TABLE #Prev_ded
	DROP TABLE #Dohod_13
	DROP TABLE #Dohod_13_1
	drop table #Dohod_13_predel
	drop table #Dohod_13_i
	drop table #Dohod_13_predel_i
	drop table #Obl_Dohod_i
	drop table #DED_FACT 
--	drop table #DED_FACT_i
--	drop table #OBL_base_fi

	drop table #NDFL_13_i

	drop table #Dohod_35
	drop table #Dohod_35_m
	drop table #Dohod_35_i

	drop table #MONTHES
	drop table #NALOG_RASH	
	drop table #ALL_NALOG_Y	


END

















GO


GRANT EXECUTE ON dbo.[SS_REP_CARD_NDFL] TO PUBLIC

GO


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

GO

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

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = 'Пункт постановления/распоряжения' + ' ' + CODE + ' ' + [NAME] FROM KO_PUNKT_POSTANOV WITH (UPDLOCK) WHERE LINK = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM KO_PUNKT_POSTANOV WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'KO_PUNKT_POSTANOV', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0


GO


GRANT EXECUTE ON dbo.[KO_PUNKT_POSTANOV_DELETE] TO PUBLIC

GO


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


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

GO

--- ФОРМИРОВАНИЕ АКТА ЗА ВЫПОЛНЕННЫЕ РАБОТЫ ИЗ ВЫДАННОЙ СЧЕТ-ФАКТУРЫ () --- 
CREATE PROCEDURE dbo.BK_SAVE_AKT_EXEC_FROM_INVOICE
	@parm_intINVOICE	INT,
	@parm_intLINK_DOC	INT	OUTPUT
AS
BEGIN
	DECLARE
		@intOBJ_REF	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		@strDOC_NUMBER	VARCHAR (25),
		@strINVOICE_NUMBER	VARCHAR (25),
		@dDOC_DATE	DATETIME,
		@intDOG_TYPE	INT,
		@intLINK_OSNOV	INT,
		@intERROR	INT,

		@cINV_TYPE	VARCHAR (30),
		@intLINK_MC	INT,
		@cSFIN_CODE	CHAR (1),
		@intORDERS INT,
		@intUM_LINK INT, 
		@PRICE NUMERIC (18,4), 
		@TAX_RATE NUMERIC(5,2),
		@SFIN_NAME VARCHAR(20), 
		@intLINK_ROW	INT,
		@SUM		NUMERIC (28,4),
		@SUM_NALOG	NUMERIC (28,4),
		@SUMMA_ALL	NUMERIC (28,4),
		@LINK_EKR	INT,

	-- 20080827 ---
		@strOBJ_REF_CODE	VARCHAR (30),
		@strDOC_REF_CODE	VARCHAR (30),
		@strCOMMENT	VARCHAR (254),
		@intCLIENT_LN	INT,
		@lnTAX_RATE	NUMERIC (4,2),
		@QTY		NUMERIC (28,4),
		@intTYPE_NUMBER		INT -- 0 - номер док-та генерируется, 1 - номер равен номеру СЧФК

	SELECT @strOBJ_REF_CODE	= 'DOC_REF_INVOICE_OUT_AKT_EXEC',
		@strDOC_REF_CODE = 'DOCUMENTS_AKT_EXEC_SERVICES'

	EXEC @intOBJ_REF = dbo.X_GET_OBJ_LINK @strOBJ_REF_CODE 

	/* -- ДАННЫЕ ИЗ СЧЕТ ФАКТУРЫ -- */
	SELECT 	@intDEP_LINK	=	G.DEP_LINK,
		@dDOC_DATE	=	G.[DATE],
		@strINVOICE_NUMBER = G.NUMBER,
--		@intACC_LINK	=	COALESCE (G.ACC, T1.MAIN_LINK),
		@intACC_LINK	=	T1.MAIN_LINK,
		@intCLIENT_LN	=	G.BUY_LINK,
		@intLINK_OSNOV	=	G.OSNOV,
		@lnTAX_RATE		=	G.TAX_RATE
	FROM dbo.DOCUMENTS_INVOICE_ISSUED G 
	INNER JOIN dbo.DICTIONARY_DEPARTMENT T1 ON (T1.LINK = G.DEP_LINK)
	WHERE G.LINK = @parm_intINVOICE

	--- ФОРМИРОВАНИЕ ДОКУМЕНТА --- 
	--- Создание ---
	IF @intTYPE_NUMBER = 1
		SET @strDOC_NUMBER = @strINVOICE_NUMBER
	ELSE
		EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER @strDOC_REF_CODE, @strDOC_NUMBER output, @intDEP_LINK
	
	SET @parm_intLINK_DOC = (SELECT LINK FROM dbo.XK_GetTable_Doc_FOREIGN (@parm_intINVOICE)
					WHERE DOC_CODE = @strDOC_REF_CODE)

	SELECT @strCOMMENT = 'Автосформирован из с\ф выданной № ' + RTRIM (@strINVOICE_NUMBER) + 
		' от ' + CONVERT (VARCHAR (10), @dDOC_DATE, 104)

	EXEC @intERROR = dbo.X_SAVE_DOCUMENTS_AKT_EXEC_SERVICES @parm_intLINK_DOC OUTPUT, @strDOC_NUMBER,
		@dDOC_DATE, DEFAULT, DEFAULT, @strCOMMENT, @intDEP_LINK, @intACC_LINK,
		@intCLIENT_LN, @intLINK_OSNOV, @lnTAX_RATE

	IF @intERROR <> 0
		RETURN @intERROR
	
	IF @parm_intLINK_DOC IS NULL
	BEGIN
		RAISERROR ('Документ не сформирован!', 11, 1)
		RETURN 1
	END

	EXEC dbo.X_UPDATE_G_PROV_REF @parm_intINVOICE, @intOBJ_REF, @parm_intLINK_DOC

	--- !!!СОХРАНЯЕМ ТАБЛИЧНУЮ ЧАСТЬ!!! --- 
	-- Табличная часть СЧ-Фактуры --
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT 
				ORDERS,
				INV_TYPE,
				INV_LINK,
				UM_LINK,
				QTY,
				PRICE,
				SUMMA,
				STAVKA_NDS,
				SUMMA_NDS,
				SUMMA_ALL,
				EKR_LINK,
				SFIN_CODE,
				SFIN_NAME
			FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (@parm_intINVOICE) T1
			WHERE INV_TYPE = 'DICTIONARY_SERV'
			ORDER BY ORDERS

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @intORDERS, @cINV_TYPE, @intLINK_MC, @intUM_LINK, @QTY, @PRICE, @SUM,
			@TAX_RATE, @SUM_NALOG, @SUMMA_ALL, @LINK_EKR, @cSFIN_CODE, @SFIN_NAME

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @intLINK_ROW = NULL

		EXEC @intERROR = dbo.BK_SAVE_DOC_TABLE_MZ_NDS
			@intLINK_ROW OUTPUT,
			@parm_intLINK_DOC,
			@intORDERS,
			@cINV_TYPE,
			@intLINK_MC,
			@PRICE,
			DEFAULT,
			DEFAULT,
			@QTY,
			@SUM,
			@TAX_RATE,
			@SUM_NALOG,
			@SUMMA_ALL,
			@LINK_EKR,
			@cSFIN_CODE 

		IF @intERROR <> 0
			RETURN @intERROR

		FETCH NEXT FROM #DATA_CURSOR
			INTO @intORDERS, @cINV_TYPE, @intLINK_MC, @intUM_LINK, @QTY, @PRICE, @SUM,
				@TAX_RATE, @SUM_NALOG, @SUMMA_ALL, @LINK_EKR, @cSFIN_CODE, @SFIN_NAME
	END

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

RETURN 0
END

GO


GRANT EXECUTE ON dbo.[BK_SAVE_AKT_EXEC_FROM_INVOICE] TO PUBLIC

GO



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

GO

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

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

*******************************************************************************/
-- Процедура импорта структур форм из временных таблиц.
CREATE PROCEDURE dbo.[ro_import_form_struct]
AS
--SET NOCOUNT ON
declare @bd DATETIME
DECLARE @only_add TINYINT 
SET @only_add = 0

IF ISNULL((SELECT COUNT(*) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'OBJ_UPDATE_SVOD') AND RTRIM(SUBSTRING(VALUE,22,8))='12.11.00'),0) > 1000
BEGIN
   SET @only_add = 1 -- чтобы ничего не затереть у пользователей
END 

set @bd = getdate() 

DECLARE @t_Forms TABLE (Link_Form INT, Link_Form_imp INT, maxOrderRule int)
DECLARE @t_Forms_New TABLE (Link_Form INT)
create table #t_Tables (Link_Table INT, Link_Table_imp INT, cnt_Cols TINYINT, cnt_Cols_imp TINYINT)
declare @t_Tables_New table (Link_Table INT)
DECLARE @t_Tables_Del table (Link_Table INT)
create table #t_Cols (Link_Col INT, Link_Col_imp INT)
DECLARE @t_Cols_new TABLE (Link_Col INT, Link_Table INT)
DECLARE @t_Cols_del TABLE (Link_Col INT, Link_Table INT)
create table #t_Rows (Link_Row INT, Link_Row_imp INT)
create table #t_Rows_del (Link_Row INT)
DECLARE @t_Rows_new TABLE (Link_Row INT)

Create index #IX_Tables on #t_Tables (link_table)
Create index #IX_Tables_imp on #t_Tables (link_table_imp)
Create index #IX_Cols on #t_Cols (link_col)
Create index #IX_Cols_imp on #t_Cols (link_col_imp)
Create index #IX_Rows on #t_Rows (link_row)
Create index #IX_Rows_imp on #t_Rows (link_row_imp)
Create index #IX_Rows_del on #t_Rows_del (link_row)

DECLARE @LinkTable INT, @LinkCodeCol INT, @LinkCodeColNew INT

INSERT @t_Forms (Link_Form, Link_Form_imp)
SELECT F.Link_Form, I.Link_Form
FROM report_forms F JOIN report_forms_U I ON F.code = I.Code AND F.Start_Date = I.Start_Date
where isnull(I.update_date, '21000101') > isnull(F.update_date, '19000101')

INSERT @t_Forms_New (Link_Form)
SELECT Link_Form
FROM report_forms_U U
WHERE not exists(select top 1 * from report_forms F where U.Code = F.Code and U.Start_Date = F.Start_Date)

print 'form'
print convert(varchar(30), getdate() - @BD, 114)

INSERT #t_Tables (Link_Table,Link_Table_imp, cnt_Cols, cnt_Cols_imp) 
SELECT T.Link_Table, I.Link_Table, (SELECT COUNT(*) FROM dbo.REPORT_COLOUMNS RC WHERE RC.Link_Table = T.Link_Table), (SELECT COUNT(*) FROM dbo.REPORT_COLOUMNS_U RC WHERE RC.Link_Table = I.Link_Table)
FROM report_tables T
	JOIN @t_Forms F ON T.Link_Form = F.Link_Form
	JOIN dbo.REPORT_TABLES_U I ON I.Link_Form = F.Link_Form_imp AND I.orders = T.orders


INSERT @t_Tables_New (Link_Table)
SELECT Link_Table
FROM report_tables_U U
WHERE not exists (SELECT top 1 * FROM #t_Tables T where T.Link_Table_imp = U.Link_Table)

INSERT @t_Tables_Del (Link_Table)
SELECT Link_Table
FROM report_tables T JOIN @t_Forms F ON T.Link_Form = F.Link_Form
WHERE not exists(SELECT top 1 * FROM #t_Tables T1 where T1.Link_Table = T.Link_Table)

print 'tables'
print convert(varchar(30), getdate() - @BD, 114)

INSERT #t_Cols (Link_Col, Link_Col_imp)
SELECT C.Link_Col, I.Link_Col
FROM report_coloumns C
	JOIN #t_Tables T ON C.Link_Table = T.Link_Table
	JOIN dbo.REPORT_COLOUMNS_U I ON T.Link_Table_imp = I.Link_Table
WHERE (T.cnt_Cols = T.cnt_Cols_imp AND C.orders = I.orders)
		OR
		(T.cnt_Cols <> T.cnt_Cols_imp AND C.Name = I.Name)
		
INSERT @t_Cols_New (Link_Col, Link_Table)
SELECT Link_Col, Link_Table
FROM dbo.REPORT_COLOUMNS_U U
WHERE not exists(SELECT top 1 * FROM #t_Cols C where C.Link_Col_imp = U.Link_Col)


INSERT @t_Cols_Del (Link_Col, Link_Table)
SELECT Link_Col, C.Link_Table
FROM dbo.REPORT_COLOUMNS C JOIN #t_Tables T ON C.link_Table = T.Link_Table
WHERE not exists(SELECT top 1 * FROM #t_Cols C1 where C1.Link_Col = C.Link_Col)

print 'col'
print convert(varchar(30), getdate() - @BD, 114)

insert #t_Rows (Link_Row, Link_Row_imp)
select R.Link_Row, U.Link_Row
from i_report_rows R 
	join #t_Tables T on R.Link_Table = T.Link_Table
	join (select  RFU.Formula as Code, RTU.Link_Table, RFU.Link_Row from report_tables_U RTU join report_formula_U RFU on RFU.Link_Col = RTU.Link_Code_Col ) U
			on U.Link_Table = T.Link_Table_imp and convert(varchar(50), U.Code) = convert(varchar(50), R.Code)

/*
insert #t_Rows (Link_Row, Link_Row_imp)
select R.Link_Row, U.Link_Row
from report_rows R 
	join #t_Tables T on R.Link_Table = T.Link_Table
	join report_rows_U U on U.Link_Table = T.Link_Table_imp and U.orders = R.orders
*/

insert @t_Rows_New (Link_Row)
select Link_Row
from report_rows_U U
where not exists (select top 1 * from #t_Rows R where R.Link_Row_imp = U.Link_Row)

insert #t_Rows_del (Link_Row)
select Link_Row
from report_rows RR join #t_Tables T on RR.Link_Table = T.Link_Table
where not exists (select top 1 * from #t_Rows R1 where R1.Link_Row = RR.Link_Row) 

print 'row'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- Обновление таблицы REPORT_FORMS.
-------------------------------------------------------------------------------
IF @only_add = 0
BEGIN 
   UPDATE [A]
   SET [NAME]                    = [B].[NAME],
       [CODE]                    = [B].[CODE],
       [START_DATE]              = [B].[START_DATE],
       [PERIODIC]                = [B].[PERIODIC],
       [IsSvod]                  = [B].[IsSvod],
       [IsExported]              = [B].[IsExported],
       [IsUserForm]              = [B].[IsUserForm],
       [PRINT_OBJECT_METHOD]     = [B].[PRINT_OBJECT_METHOD],
       [QUERY_ADD_MODULE]        = [B].[QUERY_ADD_MODULE],
       [QUERY_BEFORE]            = [B].[QUERY_BEFORE],
       [QUERY_REPMAKER]          = [B].[QUERY_REPMAKER],
       [QUERY_REPORT]            = [B].[QUERY_REPORT],
       [QUERY_REPORT_PATH]       = [B].[QUERY_REPORT_PATH],
       [FORM_TYPE]               = [C].[LINK],
       [EXPORT_PROC]             = [B].[EXPORT_PROC],
       [DECRIPT_PROC]            = [B].[DECRIPT_PROC],
       [IsKonsolid]              = [B].[IsKonsolid],
       [PARAM_EXPORT]            = [B].[PARAM_EXPORT],
       [PARAM_IMPORT]            = [B].[PARAM_IMPORT],
       [OBJECT]                  = [B].[OBJECT],
       [ExportCode]              = [B].[ExportCode],
       [IS_AUTOFILL]             = [B].[IS_AUTOFILL],
       [ATRIBUTS]                = [B].[ATRIBUTS],
       [UPDATE_DATE]             = [B].[UPDATE_DATE],
       [SvodProc]                = [B].[SvodProc],
       [END_DATE]                = [B].[END_DATE],
       [COMMENT]                 = [B].[COMMENT],             
       [PRINT_OBJECT_METHOD_NEW] = [B].[PRINT_OBJECT_METHOD_NEW],
       [QUERY_BEFORE_PRINT_NEW]  = [B].[QUERY_BEFORE_PRINT_NEW],
       [QUERY_REPORT_NEW]        = [B].[QUERY_REPORT_NEW],
       [IS_CALC]                 = [B].[IS_CALC],
       [HINT_FILE_ID]            = NULL,
       [GUID]					  = [B].[GUID]
   FROM dbo.[REPORT_FORMS] [A]
   JOIN @t_Forms F ON A.link_form = F.Link_Form
   JOIN dbo.[REPORT_FORMS_U] [B] ON F.Link_Form_imp = B.Link_Form
   JOIN dbo.[S_OBJECTS_U]	[S]		ON [S].[Link] = [B].[Form_Type]
   JOIN dbo.[S_OBJECTS]    [C] ON [S].[CODE] = [C].[CODE]
END 
ELSE
BEGIN     
   UPDATE [A]
   SET [NAME]                    = [B].[NAME],
       [CODE]                    = [B].[CODE],
       [START_DATE]              = [B].[START_DATE],
       [IsSvod]                  = [B].[IsSvod],
       [IsExported]              = [B].[IsExported],
       [IsUserForm]              = [B].[IsUserForm],
       [PRINT_OBJECT_METHOD]     = [B].[PRINT_OBJECT_METHOD],
       [QUERY_ADD_MODULE]        = [B].[QUERY_ADD_MODULE],
       [QUERY_BEFORE]            = [B].[QUERY_BEFORE],
       [QUERY_REPMAKER]          = [B].[QUERY_REPMAKER],
       [QUERY_REPORT]            = [B].[QUERY_REPORT],
       [QUERY_REPORT_PATH]       = [B].[QUERY_REPORT_PATH],
       [FORM_TYPE]               = [C].[LINK],
       [EXPORT_PROC]             = [B].[EXPORT_PROC],
       [DECRIPT_PROC]            = [B].[DECRIPT_PROC],
       [PARAM_EXPORT]            = [B].[PARAM_EXPORT],
       [PARAM_IMPORT]            = [B].[PARAM_IMPORT],
       [OBJECT]                  = [B].[OBJECT],
       [ExportCode]              = [B].[ExportCode],
       [IS_AUTOFILL]             = [B].[IS_AUTOFILL],
       [ATRIBUTS]                = [B].[ATRIBUTS],
       [UPDATE_DATE]             = [B].[UPDATE_DATE],
       [SvodProc]                = [B].[SvodProc],
       [END_DATE]                = [B].[END_DATE],
       [COMMENT]                 = [B].[COMMENT],             
       [PRINT_OBJECT_METHOD_NEW] = [B].[PRINT_OBJECT_METHOD_NEW],
       [QUERY_BEFORE_PRINT_NEW]  = [B].[QUERY_BEFORE_PRINT_NEW],
       [QUERY_REPORT_NEW]        = [B].[QUERY_REPORT_NEW],
       [IS_CALC]                 = [B].[IS_CALC],
       [GUID]					  = [B].[GUID]
   FROM dbo.[REPORT_FORMS] [A]
   JOIN @t_Forms F ON A.link_form = F.Link_Form
   JOIN dbo.[REPORT_FORMS_U] [B] ON F.Link_Form_imp = B.Link_Form
   JOIN dbo.[S_OBJECTS_U]	[S]		ON [S].[Link] = [B].[Form_Type]
   JOIN dbo.[S_OBJECTS]    [C] ON [S].[CODE] = [C].[CODE]
END

INSERT dbo.[REPORT_FORMS]([NAME],[CODE],[START_DATE],[PERIODIC],[IsSvod],[IsExported],[IsUserForm],[IsUsedRazdel], [IsUsedCelSt], [IsUsedRashod],[PRINT_OBJECT_METHOD],[QUERY_ADD_MODULE],[QUERY_BEFORE],[QUERY_REPMAKER],[QUERY_REPORT],[QUERY_REPORT_PATH],[FORM_TYPE],[EXPORT_PROC],[DECRIPT_PROC],[IsKonsolid],[PARAM_EXPORT],[PARAM_IMPORT],[OBJECT],[ExportCode],[IS_AUTOFILL],[ATRIBUTS],[UPDATE_DATE],[SvodProc],[END_DATE],[COMMENT],[PRINT_OBJECT_METHOD_NEW],[QUERY_BEFORE_PRINT_NEW],[QUERY_REPORT_NEW],[IS_CALC],[HINT_FILE_ID],[GUID],[IsRemoteAccess])
SELECT [B].[NAME],[B].[CODE],[B].[START_DATE],[B].[PERIODIC],[B].[IsSvod],[B].[IsExported],[B].[IsUserForm],0,0,0,[B].[PRINT_OBJECT_METHOD],[B].[QUERY_ADD_MODULE],[B].[QUERY_BEFORE],[B].[QUERY_REPMAKER],[B].[QUERY_REPORT],[B].[QUERY_REPORT_PATH],[C].[LINK],[B].[EXPORT_PROC],[B].[DECRIPT_PROC],[B].[IsKonsolid],[B].[PARAM_EXPORT],[B].[PARAM_IMPORT],[B].[OBJECT],[B].[ExportCode],[B].[IS_AUTOFILL],[B].[ATRIBUTS],[B].[UPDATE_DATE],[B].[SvodProc],[B].[END_DATE],[B].[COMMENT],[B].[PRINT_OBJECT_METHOD_NEW],[B].[QUERY_BEFORE_PRINT_NEW],[B].[QUERY_REPORT_NEW],[B].[IS_CALC],NULL,[B].[GUID],0
FROM @t_Forms_New  [A]
JOIN report_forms_U   [B] ON [A].[Link_Form] = [B].[Link_Form]
JOIN dbo.[S_OBJECTS_U] [S] ON [B].[FORM_TYPE] = [S].[Link]
JOIN dbo.[S_OBJECTS] [C] ON [S].[CODE] = [C].[CODE]

INSERT @t_Forms (Link_Form, Link_Form_imp) -- теперь все соответствия форм
SELECT F.Link_Form, I.Link_Form
FROM report_forms F JOIN report_forms_U I ON F.code = I.Code AND F.Start_Date = I.Start_Date
	JOIN @t_Forms_New N ON N.Link_Form = I.Link_Form

print 'form'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- удаление REPORT_TABLES, REPORT_COLOUMNS, REPORT_ROWS
-------------------------------------------------------------------------------
-- сначала удаляем все системные правила
DELETE report_control_rules
where Link_Rule in (select Link_Rule FROM report_control_rows R join @t_Tables_del T ON  T.Link_Table = R.Link_Table)

DELETE report_control_rules
where Link_Rule in (select Link_Rule FROM report_control_rows R join @t_Cols_del C ON  C.Link_Col = R.Link_Col)

DELETE report_control_rules
where Link_Rule in (select Link_Rule FROM report_control_rows R join #t_Rows_del RD ON  RD.Link_Row = R.Link_Row)


DELETE A
FROM dbo.REPORT_Tables A join @t_Tables_Del C on A.Link_Table = C.Link_Table

DELETE A
FROM dbo.REPORT_Coloumns A join @t_Cols_Del C on A.Link_Col = C.Link_Col

DELETE A
FROM dbo.REPORT_Rows A join #t_Rows_del R on A.Link_Row = R.Link_Row

print 'del'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- REPORT_TABLES
-------------------------------------------------------------------------------
UPDATE [A]
SET [Name] = I.[Name],
   Val_Type = I.Val_Type,
   Script_Str = I.Script_Str,
   order_rule = I.order_rule,
   IS_DINAMIC = I.IS_DINAMIC,
   Doschet_Tree = I.Doschet_Tree,
   GUID = I.GUID
FROM dbo.REPORT_TABLES [A] JOIN #t_Tables T ON A.link_table = T.Link_Table
   JOIN dbo.REPORT_TABLES_U I ON T.Link_Table_imp = I.Link_Table

INSERT dbo.REPORT_TABLES ([Name],Link_Form,Orders,Link_Code_Col,Val_Type,Script_Str,order_rule,IS_DINAMIC,GUID, Doschet_Tree) 
SELECT I.[Name],F.Link_Form,I.Orders,NULL,I.Val_Type,I.Script_Str,I.order_rule,I.IS_DINAMIC,I.GUID, I.Doschet_Tree
FROM dbo.REPORT_TABLES_U I JOIN @t_Tables_New T ON I.Link_Table = T.Link_Table
	JOIN @t_Forms F ON I.Link_Form = F.Link_Form_imp
	
INSERT #t_Tables (Link_Table,Link_Table_imp, cnt_Cols, cnt_Cols_imp) -- теперь все соответствия таблиц
SELECT T.Link_Table, I.Link_Table, (SELECT COUNT(*) FROM dbo.REPORT_COLOUMNS RC WHERE RC.Link_Table = T.Link_Table), (SELECT COUNT(*) FROM dbo.REPORT_COLOUMNS_U RC WHERE RC.Link_Table = I.Link_Table)
FROM report_tables T
	JOIN @t_Forms F ON T.Link_Form = F.Link_Form
	JOIN report_tables_U I ON I.Link_Form = F.Link_Form_imp AND I.orders = T.orders
	JOIN @t_Tables_New N on N.Link_Table = I.Link_Table

print 'tables'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- REPORT_COLOUMNS
-------------------------------------------------------------------------------
IF @only_add = 0
BEGIN 
   UPDATE [A]
   SET Orders = I.orders,
	   [Name] = I.[Name],
	   IsExported = I.IsExported,
	   Col_Type = I.Col_Type,
	   Export_Order = I.Export_Order,
	   Calc_Orders = I.Calc_Orders,
	   IsEdited = I.IsEdited,
	   Val_Len = I.Val_Len,
	   Dictionary = I.Dictionary,
	   Dictionary_Columns_List = I.Dictionary_Columns_List,
	   Dictionary_Fields_List = I.Dictionary_Fields_List,
	   input_mask = I.input_mask,
	   [property] = I.[property],
	   STR_PROPERTY = I.STR_PROPERTY,
	   [GUID] = I.[GUID], 
      [Dictionary_Where] = I.[Dictionary_Where]   
   FROM dbo.REPORT_COLOUMNS A JOIN #t_Cols C ON A.Link_Col = C.Link_Col
	   JOIN dbo.REPORT_COLOUMNS_U I ON C.Link_col_imp = I.Link_Col
END 
ELSE BEGIN
   UPDATE [A]
   SET Orders = I.orders,
	   IsExported = I.IsExported,
	   Col_Type = I.Col_Type,
	   Export_Order = I.Export_Order,
	   Calc_Orders = I.Calc_Orders,
	   IsEdited = I.IsEdited,
	   [GUID] = I.[GUID]
   FROM dbo.REPORT_COLOUMNS A JOIN #t_Cols C ON A.Link_Col = C.Link_Col
	   JOIN dbo.REPORT_COLOUMNS_U I ON C.Link_col_imp = I.Link_Col
END   
   

INSERT dbo.REPORT_COLOUMNS (Orders,[Name],Link_Table,IsExported,Col_Type,Export_Order,Calc_Orders,IsEdited,Val_Len,Dictionary,Dictionary_Columns_List,Dictionary_Fields_List,input_mask,[property],STR_PROPERTY,[GUID], [Dictionary_Where])
SELECT I.Orders,I.[Name],T.Link_Table,I.IsExported,I.Col_Type,I.Export_Order,I.Calc_Orders,I.IsEdited,I.Val_Len,I.Dictionary,I.Dictionary_Columns_List,I.Dictionary_Fields_List,I.input_mask,I.[property],I.STR_PROPERTY,I.[GUID], I.[Dictionary_Where]
FROM dbo.REPORT_COLOUMNS_U I JOIN @t_Cols_New N ON I.Link_Col = N.Link_Col
	JOIN #t_Tables T on I.Link_Table = T.Link_Table_imp


INSERT #t_Cols (Link_Col, Link_Col_imp)  -- теперь все соответствия колонок
SELECT C.Link_Col, I.Link_Col
FROM report_coloumns C
	JOIN #t_Tables T ON C.Link_Table = T.Link_Table
	JOIN dbo.REPORT_COLOUMNS_U I ON T.Link_Table_imp = I.Link_Table
	JOIN @t_Cols_New N ON N.Link_Col = I.Link_Col
WHERE C.orders = I.orders

print 'col'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- REPORT_CODE_COL
-------------------------------------------------------------------------------
-- для существующих таблиц возможно нужно будет перенести данные
DECLARE cur_Tables CURSOR LOCAL STATIC FOR
SELECT RT.Link_Table, Link_Code_Col
FROM report_tables RT JOIN #t_Tables T ON RT.Link_Table = T.Link_Table
WHERE Link_Code_Col IS NOT NULL 

OPEN cur_Tables

FETCH NEXT FROM cur_Tables
INTO @LinkTable, @LinkCodeCol

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @LinkCodeColNew = (SELECT top 1 C.Link_Col FROM dbo.REPORT_TABLES_U I JOIN #t_Tables T ON I.Link_Table = T.Link_Table_imp and T.Link_Table =  @LinkTable JOIN #t_Cols C ON C.Link_Col_imp = I.Link_Code_Col)

	IF @LinkCodeColNew IS NOT NULL
	BEGIN 
		EXEC dbo.[RA_MOVE_CODE_COL] @LinkCodeColNew
		UPDATE report_tables SET Link_Code_Col = @LinkCodeColNew WHERE Link_Table = @LinkTable
	END

--	exec dbo.[I_REPORT_CREATE_PROC] @LinkTable
	
	FETCH NEXT FROM cur_Tables
	INTO @LinkTable, @LinkCodeCol
END 

CLOSE cur_Tables

DEALLOCATE cur_Tables

-- для новых таблиц
UPDATE [A]
SET Link_Code_Col = C.Link_Col
FROM dbo.REPORT_TABLES [A] JOIN #t_Tables T ON A.Link_Table = T.Link_Table
	JOIN dbo.REPORT_TABLES_U I ON T.Link_Table_imp = I.Link_Table
	JOIN #t_Cols C ON C.Link_Col_imp = I.Link_Code_Col
WHERE A.Link_Code_Col IS NULL

print 'report_code_col'
print convert(varchar(30), getdate() - @BD, 114)
-----------------------------------------------------------------------------
-- REPORT_ROWS
-------------------------------------------------------------------------------
UPDATE A
set	Calc_Orders = I.Calc_Orders,
	Print_Null = I.Print_Null,
	Orders = I.Orders,
	GUID = I.GUID
FROM dbo.REPORT_ROWS A JOIN #t_Rows T ON A.Link_Row = T.Link_Row
	JOIN dbo.REPORT_ROWS_U I ON T.Link_Row_imp = I.Link_Row 

INSERT dbo.REPORT_ROWS (Orders,Link_Table,Calc_Orders,Print_Null,GUID)
SELECT RRU.Orders, T.Link_Table, RRU.Calc_Orders, RRU.Print_Null, RRU.GUID
FROM report_rows_U RRU join #t_Tables T on RRU.Link_Table = T.Link_Table_imp
	join @t_Rows_New N on N.Link_Row = RRU.Link_Row

insert #t_Rows (Link_Row, Link_Row_imp) -- теперь все соответствия
select R.Link_Row, RU.Link_Row
from report_rows R 
	join #t_Tables T on R.Link_Table = T.Link_Table
	join report_rows_U RU on R.orders = RU.orders and Ru.Link_Table = T.Link_Table_imp
where RU.Link_Row in (select Link_Row from @t_Rows_New)

print 'row'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- REPORT_FORMULA
-------------------------------------------------------------------------------
IF @only_add = 0
BEGIN 
   UPDATE A
   set Formula = U.Formula
   from report_formula A join #t_Cols C on A.Link_Col = C.Link_Col
		   join #t_Rows R on A.Link_Row = R.Link_Row
		   join report_formula_U U on U.Link_Row = R.Link_Row_imp and U.Link_Col = C.Link_Col_imp
END 

delete A
from report_formula A
where not exists(select top 1 * from report_formula_U RFU join #t_Cols C on C.Link_Col_imp = RFU.Link_Col 
					 join #t_Rows R on R.Link_Row_imp = RFU.Link_Row where A.Link_Row = R.Link_Row and A.Link_Col = C.Link_Col)
	and exists(select top 1 * from #t_Rows R where R.Link_Row = A.Link_Row)

insert report_formula (Link_Row, Link_Col, Formula)
select R.Link_Row, C.Link_Col, RFU.Formula
from report_formula_U RFU  join #t_Cols C on RFU.Link_Col = C.Link_Col_imp
		join #t_Rows R on RFU.Link_Row = R.Link_Row_imp
where not exists(select top 1 * from report_formula RF where RF.Link_Row = R.Link_Row and RF.Link_Col = C.Link_Col)

print 'formula'
print convert(varchar(30), getdate() - @BD, 114)

-------------------------------------------------------------------------------
-- ГРУППЫ ФОРМ
-------------------------------------------------------------------------------
update A
set Name = U.Name,
	System = U.System
from report_form_groups A, report_form_groups_U U
where A.Code = U.Code

insert report_form_groups (Code, Name, System)
select U.Code, U.Name, U.System
from report_form_groups_U U
where not exists(select top 1 * from report_form_groups G where G.Code = U.Code)

insert report_form_groups_ref (link_form, Link_Form_Groups)
select distinct F.Link_Form, G.Link
from report_form_groups_ref_U U join @t_Forms F on F.Link_Form_imp = U.Link_Form
	join report_form_groups_U UG on UG.Link = U.Link_Form_Groups
	join report_form_groups G on G.Code = UG.Code
where not exists(select top 1 * from report_form_groups_ref R where R.Link_Form = F.Link_Form and R.Link_Form_Groups = G.Link)

print 'group'
print convert(varchar(30), getdate() - @BD, 114)
-------------------------------------------------------------------------------
-- ПРАВА
-------------------------------------------------------------------------------
declare @LinkForm int
declare cur_New_Form cursor local static for
select F.Link_Form
from @t_Forms_New N join @t_Forms F on F.Link_Form_imp = N.Link_Form
	join report_forms RF on F.Link_Form = RF.Link_Form
order by RF.Start_Date

open cur_New_Form

fetch next from cur_New_Form
into @LinkForm

while @@fetch_status = 0
begin
	exec dbo.[RA_UNION_FORM_SET_PERSMISSIONS] @LinkForm

	fetch next from cur_New_Form
	into @LinkForm
end

close cur_New_Form
deallocate cur_New_Form
print 'perm'
print convert(varchar(30), getdate() - @BD, 114)
-------------------------------------------------------------------------------
-- ПРАВИЛА
-------------------------------------------------------------------------------
---- группы междокументных правил
update A
set Code = U.Code,
	Name = U.Name,
	Type = U.Type,
	System = U.System,
	dt_begin = U.dt_begin,
	dt_end = U.dt_end
from report_group_ks A join report_group_KS_U U on A.Code = U.Code

DELETE a
FROM [REPORT_CONTROL_RULES] A
WHERE ([IsSystemsRule] = 1 OR ([IsSystemsRule] = 0 AND ([REGION] IS NULL OR [REGION] IN ('')))) AND ISOUTSIDE = 1
	AND Link_Rule in (select GR.Link_Rule from report_control_group GR join report_group_ks G on GR.link_group_ks = G.link_group_ks join report_group_ks_U GU on G.Code = GU.Code where exists(select top 1 * from report_control_group_U CGU where GU.link_group_ks = CGU.link_group_ks))


insert report_group_ks (code, Name, Type, System, dt_begin, dt_end)
select Code, Name, Type, System, dt_begin, dt_end
from report_group_ks_U U
where not exists(select top 1 * from report_group_ks G where G.Code = U.Code)

declare @maxLink int, @minLink int, @NowDate datetime, @maxOrderRule int

set @NowDate = getdate()

select @maxLink=isnull(max(link_rule),1) from REPORT_CONTROL_RULES   
select @minLink=isnull(min(link_rule),1) from REPORT_CONTROL_RULES_U
set @maxLink = @maxLink - @minLink + 1

INSERT @t_Forms (Link_Form, Link_Form_imp) -- те формы, которые исправляли пользователи, для них нужны КС
SELECT F.Link_Form, I.Link_Form
FROM report_forms F JOIN report_forms_U I ON F.code = I.Code AND F.Start_Date = I.Start_Date
where not exists(select top 1 * from  @t_Forms F1 where F1.Link_Form =  F.Link_Form and F1.Link_Form_imp =  I.Link_Form) 

DELETE A
FROM dbo.[REPORT_CONTROL_RULES] A JOIN @t_Forms F on A.Link_Form = F.Link_Form and A.IsOutside = 0
WHERE ([IsSystemsRule] = 1 OR ([IsSystemsRule] = 0 AND ([REGION] IS NULL OR [REGION] IN (''))))

insert #t_Tables (Link_Table, Link_Table_imp, cnt_Cols , cnt_Cols_imp)
select RT.Link_Table, RTU.Link_Table, 0, 0
from report_tables RT join @t_Forms F on F.link_Form = RT.Link_Form
		join report_tables_U RTU on RTU.Link_Form = F.Link_Form_imp and RT.orders = RTU.orders
where not exists(select * from #t_Tables T where T.link_table = RT.Link_Table and T.Link_Table_imp = RTU.link_table)

insert  #t_Cols (Link_Col, Link_Col_imp)
select RT.Link_Col, RTU.Link_Col
from report_coloumns RT join #t_Tables F on F.link_table = RT.Link_table
		join report_coloumns_U RTU on RTU.link_table = F.link_table_imp and RT.orders = RTU.orders
where not exists(select * from #t_Cols T where T.Link_Col = RT.Link_Col and T.Link_Col_imp = RTU.Link_Col)

insert  #t_Rows (Link_Row, Link_Row_imp)
select RT.Link_Row, RTU.Link_Row
from report_rows RT join #t_Tables F on F.link_table = RT.Link_table
		join report_rows_U RTU on RTU.link_table = F.link_table_imp and RT.orders = RTU.orders
where not exists(select * from #t_Rows T where T.Link_Row = RT.Link_Row and T.Link_Row_imp = RTU.Link_Row)

update A
set maxOrderRule = isnull(Ru.maxOrderRule, 0)
from @t_Forms A join (select Link_Form, max(OrderRule) as maxOrderRule from report_control_rules where IsOutside = 0 group by Link_Form) Ru on A.Link_Form = Ru.Link_Form

update A
set maxOrderRule = isnull(maxOrderRule, 0)
from @t_Forms A

select @maxOrderRule = max(OrderRule)
from report_control_rules where IsOutside = 1

set @maxOrderRule = isnull(@maxOrderRule, 0)

	SET IDENTITY_INSERT  REPORT_CONTROL_RULES ON 

	insert into  REPORT_CONTROL_RULES ([link_rule],[Link_Task], [IsOutside], [Link_Form], [OrderRule], [Period], [Period_nom], [Org_Level], [IsSvod], [Str_Rule], [IsDoschet], [Calc_Orders],[isSystemsRule],[Modify_Date],[Cols],[Rows],[Rows_desc],REGION,COMMENT,SIGN_SR,ALGORITHM,ATR_CODE_SR)
	select U.link_rule+@maxLink, S.link,U.isOutside,F.link_form, 
case when U.IsOutside = 0 then U.OrderRule + F.maxOrderRule else U.OrderRule + @maxOrderRule end,U.Period,U.Period_nom, U.Org_Level, U.IsSvod, U.Str_Rule, U.IsDoschet, U.Calc_Orders,U.isSystemsRule,@NowDate,U.Cols,U.Rows,U.Rows_desc,U.REGION,U.COMMENT,U.SIGN_SR,U.ALGORITHM,U.ATR_CODE_SR 
	from report_control_rules_U U
		left join s_objects_U SU on U.link_task = SU.link
		left join s_objects S on S.Code = SU.Code
		left join @t_Forms F on U.Link_Form = F.Link_Form_imp

	insert into report_control_rows(Link_Rule, OrderRow, Val_Type, Sign, Link_Form, Link_Table, Link_Col, Link_Row, Period_Form, Factor, Code_Row, Exec_Proc, Exec_Proc_Desc,Filter,Filter_Desc,Maska,Maska_desc,period_type,budg_code,PERIOD_YEAR,ATR_CODE,PART,BEGIN_DATE,PX, PX_COMMENT)
	select  U.link_rule+@maxLink, U.OrderRow, U.Val_Type, U.Sign, F.Link_Form, T.Link_Table, C.Link_Col, R.Link_Row, U.Period_Form, U.Factor, U.Code_Row, U.Exec_Proc, U.Exec_Proc_Desc,U.Filter,U.Filter_Desc,U.Maska,U.Maska_desc,U.period_type,U.budg_code,U.PERIOD_YEAR,U.ATR_CODE,U.PART,U.BEGIN_DATE,U.PX, U.PX_COMMENT 
	from report_control_rows_U U
		left join @t_Forms F on U.Link_Form = F.Link_Form_imp
		left join #t_Tables T on U.Link_Table = T.Link_Table_imp
		left join #t_Cols C on U.Link_Col = C.Link_Col_imp
		left join #t_Rows R on U.Link_Row = R.Link_Row_imp
	where U.link_rule+@maxLink in (select R1.Link_rule from report_control_rules R1)


	insert report_control_group (Link_Rule, Link_Group_KS)
	select U.link_rule+@maxLink, G.Link_Group_KS
	from report_control_rules_U U join report_control_group_U GU on U.Link_rule = GU.Link_Rule
		join report_group_ks_U GU1 on GU1.Link_Group_KS = GU.Link_Group_KS
		join report_group_ks G on GU1.Code = G.Code
	where U.link_rule+@maxLink in (select R1.Link_rule from report_control_rules R1)
  
	SET IDENTITY_INSERT  REPORT_CONTROL_RULES OFF 

	drop table #t_Tables
	drop table #t_Cols
	drop table #t_Rows
	drop table #t_Rows_Del

-------------------------------------------------------------------------------
-- ПОДСКАЗКИ ДЛЯ ФОРМ
-------------------------------------------------------------------------------

	set @maxLink = isnull((select max(ID) from dbo.r_files),0)
	set @minLink = isnull((select min(ID) from dbo.r_files_U),0)

	SET IDENTITY_INSERT r_files ON 

	insert r_files (ID, Name, Path, CreateDate, FileSize)
	select ID+@maxLink - @minLink + 1, Name, Path, CreateDate, FileSize
	from dbo.r_files_U

	insert r_fileparts (File_ID, Orders, Body)
	select File_ID+@maxLink - @minLink + 1, Orders, Body
	from dbo.r_fileparts_U

	SET IDENTITY_INSERT r_files OFF

	update report_forms
	set hint_file_id = U.hint_file_id +@maxLink - @minLink+1
	from dbo.report_forms_U U
		join @t_Forms F on F.Link_Form_imp = U.Link_Form
	where report_forms.Link_Form = F.Link_Form


GO


GRANT EXECUTE ON dbo.[ro_import_form_struct] 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_FILL_WITH_DICT_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_FILL_WITH_DICT_ALL]
GO

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

*******************************************************************************/
CREATE       procedure dbo.RN_FILL_WITH_DICT_ALL
	@LSF int, -- линк сохраненного отчета
    @LF int, --линк отчета
	@OrderTable int=0 ,-- порядковый номер таблицы
	@cTMP_Table varchar(10)='', -- '#' данные записываем #REPORT_DINAMICS
	@Link_table int=0
AS
declare  @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
	@ExecStr varchar(8000), @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @option_import_report INT, @DictWhere VARCHAR(1000), @LinkOrg INT, @LinkBudg INT, @vcDate VARCHAR(10)

IF @OrderTable<>0
	select @LC = Link_Code_Col, @LT = Link_Table from report_tables where orders = @OrderTable and Link_Form = @LF
ELSE
	begin
		select @LC = Link_Code_Col, @LT = Link_Table,@OrderTable=orders,@LF=Link_Form from report_tables where link_table = @Link_table
		
	end
if @LC is NULL
begin
	return -2
end

IF exists(select * from report_tables where link_table=@LT and val_type=0)
	RETURN 


select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List), @DictWhere = RTRIM([Dictionary_Where]) from report_coloumns where Link_Col = @LC

SELECT @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere,'%link_org%',LTRIM(STR(link_organization))),'%link_budg%',LTRIM(STR(isnull(link_type_svod,0)))), '%date%', 'convert(datetime,''' + CONVERT(VARCHAR(10), begin_date, 112) + ''',112)')
FROM dbo.report_saved_forms
WHERE [Link_Saved_Form] = @LSF 


if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
begin
	return 0 -- нет подключенных справочников
end
create table #t_CodeRow (Code varchar(50))
create index #ix_t_CodeRow on #t_CodeRow (code)
set @Cols = ''
set @Field =''
set @Fields = ''
set @Col = ''
declare @icount int
set @icount=1
set @Field=dbo.rn_getWordNum(@DictField,@icount,',')
while @Field <> '' 
begin
    set @Field=dbo.rn_getWordNum(@DictField,@icount,',')
    set @Col=dbo.rn_getWordNum(@DictCol,@icount,',')

	set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
	if @i = @OrderCol
	begin
		set @CodeCol = @Col -- ключевой столбец
		set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
	end
	else begin
		set @Fields = @Fields + @Field + ','
		set @Cols = @Cols + @Col + ','
	end
    set @icount=@icount+1
end

if @Fields = '' or @Cols = ''
begin
	return 0 -- нет полей, кроме ключевого столбца
end

set @Fields = LEFT(@Fields, LEN(@Fields) - 1)
set @Cols =  LEFT(@Cols, LEN(@Cols) - 1)

--добавление итоговых строк
        if EXISTS(select * from syscolumns where id = object_id (@DICT) and name = 'PROPERTY') and EXISTS(select * from syscolumns where id = object_id (@DICT) and name = 'CODE')
            begin
              	select @LinkCol = Link_Col from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@CodeCol, 'COL', ''))
                set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF,Link_Col,Code_Row)
               	select distinct ' + STR(@LSF) + ', ' + STR(@LinkCol) + ',RTRIM('+@FieldCol+') from '+@dict+' D where property&2>0 
                and not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  D.'+@FieldCol+')'
            end
--        print @ExecStr
         execute(@ExecStr)

IF @cTMP_Table=''
    begin
            insert #t_CodeRow
         	select distinct RTRIM(Code_Row) from report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
    end
    ELSE
    begin
        insert #t_CodeRow
     	select distinct RTRIM(Code_Row) from #report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
    end
--select * from #t_CodeRow


exec RN_FILL_WITH_CODEROW @LSF,@LF,@ORDERTABLE
while @Fields <> '' and @Cols <> ''
begin
	exec dbo.RO_FORMULA_FUNCTIONS 1, @Cols output, @Col output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @Fields output, @Field output, ','
	select @LinkCol = Link_Col from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@Col, 'COL', ''))

set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val) 
select distinct ' + STR(@LSF) + ', ' + STR(@LinkCol) + ', CR.Code, 0, max(D.' + @Field + ')
from #t_CodeRow CR inner join ' + @Dict + ' D on CR.Code = D.' + @FieldCol + '
where not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  CR.Code)'
+ ' ' + CASE WHEN isnull(@DictWhere,'') = '' THEN '' ELSE ' and ' + @DictWhere + ' ' END +  
'group by CR.Code'

set @ExecStr =  @ExecStr +' update  '+@cTMP_Table+'report_dinamics set Str_Val= D.' + @Field + '
from '+@cTMP_Table+'report_dinamics CR inner join ' + @Dict + ' D on CR.Code_row = D.' + @FieldCol + '
where CR.link_SF=' + STR(@LSF) + 'and Link_col=' + STR(@LinkCol) + 'and D.' + @Field+'<>'''''
+ ' ' + CASE WHEN isnull(@DictWhere,'') = '' THEN '' ELSE ' and ' + @DictWhere + ' ' END 

print @ExecStr
 execute(@ExecStr)
--select @ExecStr
end
exec dbo.RN_SPLIT_CODE_ROW @LSF, @OrderTable

GO
GRANT ALL ON dbo.[RN_FILL_WITH_DICT_ALL] 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].[RO_SPR_ALL_EXPORT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_SPR_ALL_EXPORT]
GO




/*
c Кейсистемс (Keysystems), 2011

   сортировка всех справочников для выгрузки 
*/
CREATE            proc 	dbo.RO_SPR_ALL_EXPORT
	 @varKSiLF int -- линк сохранного отчета
as
   declare @t_Spr table (Code varchar(100))
   declare @t_Depend table (Code varchar(100), Code_dep varchar(100))
   declare @t_Spr_result table (link int, Code varchar(100), orders int IDENTITY(1,1))
   declare @name varchar(100), @mytext varchar(8000), @pos int, @ID int, @err int
   if object_id('tempdb.dbo.#t2') is not null
	   drop table #t2

   create table #t2 (text varchar(8000), id int identity(1,1))

   insert @t_Spr (Code)
   select Dictionary
   from dbo.report_tables RT  
         join dbo.report_coloumns RC on RC.link_table = RT.link_table
   where RT.link_form = @varKSiLF and isnull(Dictionary, '') <> '' and exists(select top 1 * from dbo.Report_Spr S where S.Code = RC.Dictionary)
   
   if not exists(select * from @t_Spr)
   BEGIN
      select 0 AS link, '' AS code, 0 AS orders 
      return 1 -- нет справочник, которые сдаланы в Редакторе справочников
   end

   declare cur_spr cursor local static for select code from @t_Spr
   open cur_spr 

   fetch next from cur_spr into @name

   while @@fetch_status = 0
   begin
	   truncate table #t2
	   insert into #t2
	   execute ssp_helptext @name

	   SELECT TOP 1 @ID = ID, @mytext = text from #t2 where text like '%CREATE%' ORDER BY ID
	   SET @pos = PATINDEX('%CREATE%', @mytext)
	   SET @mytext = LEFT(@mytext, @pos-1) + 'ALTER' + SUBSTRING(@mytext, @pos + 6, 8000)
	   UPDATE #t2 set text = @mytext where ID = @ID 

	   exec @err = dbo.ssp_execresultset 'select text from #t2 order by id'

      insert @t_Depend (Code, Code_dep)
      select @name, object_name(depid)
      from dbo.sysdepends sd 
      where sd.id = object_id(@name) and exists(select top 1 * from dbo.report_spr S1 where S1.Code = object_name(sd.depid))

      while @@ROWCOUNT > 0
      begin
         insert @t_Depend (Code, Code_dep)
         select distinct S.Code_dep, object_name(depid)
         from @t_Depend S join dbo.sysdepends sd on sd.id = object_id(S.Code_dep)
         where exists(select top 1 * from dbo.report_spr S1 where S1.Code = object_name(sd.depid))
               and not exists(select top 1 * from @t_Depend D where D.Code = S.Code_dep)
      end

      fetch next from cur_spr into @name
   end

   close cur_spr
   deallocate cur_spr

   insert @t_Spr_Result(Code)
   select distinct D.Code_dep
   from @t_Depend D
   where not exists(select * from @t_Depend D1 where D1.Code = D.Code_dep)

   while @@ROWCOUNT > 0
   begin
      insert @t_Spr_Result(Code)
      select distinct D.Code
      from @t_Depend D
      where not exists(select * from @t_Depend D1 where D.Code = D1.Code and not exists(select * from @t_Spr_Result R where R.Code = D1.Code_dep) )
            and not exists(select * from @t_Spr_Result R where R.Code = D.Code)     
   end

   insert @t_Spr_Result(Code)
   select Code
   from @t_Spr S
   where not exists(select * from @t_Spr_Result R where R.Code = S.Code)

   update R
   set link = S.link
   from @t_Spr_Result R join dbo.report_spr S on R.Code = S.Code

   select 0 as checked, link, Code, MIN(orders) AS orders from @t_Spr_Result GROUP BY link, Code order by MIN(orders)
   drop table #t2

GO
GRANT ALL ON dbo.[RO_SPR_ALL_EXPORT] TO PUBLIC
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE PROCEDURE dbo.RSA_RSV_1_PFR_INV
	@varKSdDate1 DATETIME,
	@varKSdDate2 DATETIME,
	@LINK_DEP int = NULL,
	@WAY_CALC TINYINT = 7,
	@REP TINYINT = 0
AS BEGIN

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

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)

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

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

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

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

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO2,
		DOC_NUM = LEFT(MAX(DIF.DOC_NUM),30),
		DOC_DATE = LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DOC_DATE),104),''))), 
		GROUP_NAME = LEFT(MAX(DIF.GROUP_NAME),254),
		CASE 
			WHEN MAX(DIF.GROUP_NAME) = 'I ГРУППА' THEN 'I'
			WHEN MAX(DIF.GROUP_NAME) = 'II ГРУППА' THEN 'II'
			WHEN MAX(DIF.GROUP_NAME) = 'III ГРУППА' THEN 'III'
			ELSE ''
		END AS GRP2, 
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DATE_BEGIN),104),''))) AS PER_BEG,
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),ISNULL(MAX(DIF.DATE_END),dbo.DateEndOfYear(@varKSdDate1)),104),''))) AS PER_END
	FROM dbo.KU_PERS_INVALID  DIF INNER JOIN dbo.EMPL E ON DIF.PERS_LINK = E.PERS_LINK
	WHERE COALESCE(DIF.DATE_BEGIN,@varKSdDate2) <= @varKSdDate2 AND COALESCE(DIF.DATE_END,@varKSdDate1) >= @varKSdDate1
		and E.DEP_LINK = @DEP_LINK
	GROUP BY 
		DIF.PERS_LINK
		
	INSERT INTO #TMP0(PERS_LINK,FIO,FIO2,DOC_NUM,DOC_DATE,GROUP_NAME,GRP2,PER_BEG,PER_END)
	SELECT
		DIF.PERS_LINK, 
		LEFT((SELECT 
			TOP 1 LTRIM(RTRIM(DF.FM)) + ' ' + LTRIM(RTRIM(DF.IM)) + ' ' + LTRIM(RTRIM(DF.OT)) 

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

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

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

	--
	DECLARE @varKSSTART_YEAR DATETIME
	SET @varKSSTART_YEAR  = dbo.DateBeginOfYear(@varKSdDate1)

	DECLARE @varKSnYear INT, @varKSnMonth1 INT, @varKSnMONTH2 INT, @varKSnMONTH3 INT
	SELECT 
		@varKSnYear = YEAR(@varKSdDate1),
		@varKSnMonth1 = MONTH(@varKSdDate2)-2,
		@varKSnMONTH2 = MONTH(@varKSdDate2)-1,
		@varKSnMONTH3 = MONTH(@varKSdDate2)

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE #TMP		

END




GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PFR_INV] TO PUBLIC

GO

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

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

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@varKScYear AS INT)
	--DECLARE @varKSnLinkPers int
	IF @varKSnLinkPers IS NULL
		SET @varKSnLinkPers = (SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl)

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

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

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

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

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

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

---

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

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


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

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


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

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

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

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

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

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



		SET @I=@I+1
	END		
	
---->>>>>>------
	-----	Подготовка данных
	Declare @isPrevPreiod tinyint
	--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
	Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')

	Declare @SJC table (LINK_FACE int,PERS_LINK int, link_empl int, link_pays int, link_vkr int, link_ekr int, typ_per tinyint, typ_oper tinyint, summa numeric(18,2), period_begin datetime, date1 datetime, link_dep int, CODE_INC varchar(5))

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

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

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


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

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

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

	INSERT INTO #ndfl_ded_month_all_table_MONTH (MON, LINK_DED, SUMMA)
	SELECT MONTH(DATE_DED), REF_DED, SUM(SUMMA)
	FROM 
		dbo.EMPL E
		INNER JOIN SAL_DED_MONTH S ON E.LINK = S.LINK_EMPL
	WHERE
		E.PERS_LINK = @varKSnLinkPers
		AND YEAR(DATE_DED) = @varKSnYear
		--AND TYPE = 1
		AND DEP_LINK = @DEP_LINK
		----
		AND EXISTS ( SELECT * FROM #deds d WHERE d.ref_ded = s.REF_DED)
		----
	GROUP BY DATE_DED, REF_DED


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

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

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

	DELETE FROM  #MONTHES2
	DELETE FROM  #MONTHES


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

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

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




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

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

		SET @varKSI = @varKSI + 1
	END

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

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

	SET @I=1

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

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


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

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

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

	EXEC (@SQLS1) 	

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

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

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

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

		DELETE FROM  #MONTHES2
		DELETE FROM  #MONTHES

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

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

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

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

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


	END

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

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



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




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

	INSERT INTO #MONTHES2 (CODE_DED) VALUES ('')

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

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

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

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


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



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


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

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


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

	EXEC dbo.BufferClear

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






GO


GRANT EXECUTE ON dbo.[SD_REP_1NDFL2009] TO PUBLIC

GO




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

GO
--- Заполнение комиссии в документе из настроек ---
CREATE PROCEDURE dbo.BK_FILL_COMISSION_IN_DOC
	@intLINK_DOC	INT,	-- Документ, в котором заполняем --
	@intLINK_COMIS	INT	= NULL -- Комиссия, которую заносим в документ 
AS
BEGIN
	DECLARE @intERROR INT,
		@intROWCOUNT INT,
		@varKStrancount INT,
		@intDEP_LINK INT,

		@intLINK_COMISSION INT,
		@intPRED_LINK INT,
		@dDOC_DATE_COMSSION DATETIME,
		@strDOC_NUM_COMISSION VARCHAR (30)

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	SELECT @intLINK_DOC = LINK,
		@intDEP_LINK = DEP 
	FROM dbo.G_PROV WITH (NOLOCK)
	WHERE LINK = @intLINK_DOC

	IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		RETURN 5
	END
	
	-- Информация о комиссии --
	SELECT TOP 1
		@intLINK_COMISSION = LINK,
		@intPRED_LINK = EMP_PRED,
		@dDOC_DATE_COMSSION = DOC_DATE, 
		@strDOC_NUM_COMISSION = DOC_NUM
	FROM dbo.BUH_COMISSION_HEAD
	WHERE LINK = @intLINK_COMIS
		OR (ISNULL (@intLINK_COMIS, 0) = 0
			AND DEP_LINK = @intDEP_LINK
			AND ISDEFAULT = 1)
		
	IF @@ROWCOUNT = 0
		SELECT TOP 1
			@intLINK_COMISSION = LINK,
			@intPRED_LINK = EMP_PRED,
			@dDOC_DATE_COMSSION = DOC_DATE, 
			@strDOC_NUM_COMISSION = DOC_NUM
		FROM dbo.BUH_COMISSION_HEAD
		WHERE DEP_LINK = @intDEP_LINK
			AND ISDEFAULT = 1

	IF @intLINK_COMISSION IS NULL
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END
	ELSE
	BEGIN
		EXEC @intERROR = dbo.BK_UPDATE_G_PROV_COMISSION_HEAD @intLINK_DOC, 
			@intLINK_COMISSION, @intPRED_LINK, @dDOC_DATE_COMSSION,
			@strDOC_NUM_COMISSION

		IF @intERROR <> 0
			RETURN @intERROR

		--- Сохраняем членов комиссии --- 
		DELETE FROM dbo.G_PROV_COMISSION_MEMBERS WHERE DOC_LINK = @intLINK_DOC 
		SELECT @intERROR = @@ERROR
		IF @intERROR <> 0
			RETURN @intERROR

		INSERT INTO dbo.G_PROV_COMISSION_MEMBERS (DOC_LINK, ORDERS, MEMBER)
		SELECT @intLINK_DOC, 
			ORDERS,
			MEMBER
		FROM dbo.BUH_COMISSION_MEMBERS
		WHERE LINK_UP = @intLINK_COMISSION 

		SELECT @intERROR = @@ERROR
		IF @intERROR <> 0
			RETURN @intERROR
	END

	IF @@TRANCOUNT > @varKStrancount 
		COMMIT TRAN
END


GO


GRANT EXECUTE ON dbo.[BK_FILL_COMISSION_IN_DOC] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_769]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_769]
END
GO

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_769]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '|***|**************|*|*****|***|', '|000|00000000000000|8|88888|888|')
      WHERE TXT LIKE '%|***|**************|*|*****|***|%'

      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '|****|', '|0000|')
      WHERE TXT LIKE '%|****|%'
         
      INSERT @tabImport(TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER]  <= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = '#$')
      ORDER BY [ORDER]
      
      INSERT @tabImport(TXT)
      SELECT dbo.[RA_GETWORDNUM]([TXT], 5, '|') + dbo.[RA_GETWORDNUM]([TXT], 6, '|') + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 8, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 9, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 4, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 10, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 11, '|')
      FROM #IMPORT_TABLE
      WHERE TXT LIKE '%|%'
            AND dbo.[RA_GETWORDNUM]([TXT], 1, '|') IN ('10', '11', '20', '21', '50', '51')
      ORDER BY [ORDER]

      INSERT @tabImport(TXT)
      VALUES ('#')

      INSERT @tabImport(TXT)
      VALUES ('#@')

      INSERT @tabImport(TXT)
      VALUES ('ТБ=02')

      INSERT @tabImport(TXT)
      VALUES ('#$')

      INSERT @tabImport(TXT)
      SELECT dbo.[RA_GETWORDNUM]([TXT], 5, '|') + dbo.[RA_GETWORDNUM]([TXT], 6, '|') + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 8, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 9, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 4, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 10, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 11, '|')
      FROM #IMPORT_TABLE
      WHERE TXT LIKE '%|%'
            AND dbo.[RA_GETWORDNUM]([TXT], 1, '|') IN ('30')
      ORDER BY [ORDER]

      INSERT @tabImport(TXT)
      VALUES ('#')

      INSERT @tabImport(TXT)
      VALUES ('#@')

      INSERT @tabImport(TXT)
      VALUES ('ТБ=03')

      INSERT @tabImport(TXT)
      VALUES ('#$')

      INSERT @tabImport(TXT)
      SELECT dbo.[RA_GETWORDNUM]([TXT], 5, '|') + dbo.[RA_GETWORDNUM]([TXT], 6, '|') + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 8, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 9, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 4, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 10, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 11, '|')
      FROM #IMPORT_TABLE
      WHERE TXT LIKE '%|%'
            AND dbo.[RA_GETWORDNUM]([TXT], 1, '|') IN ('40')
      ORDER BY [ORDER]

      INSERT @tabImport(TXT)
      VALUES ('#')

      INSERT @tabImport(TXT)
      VALUES ('#@')

      INSERT @tabImport(TXT)
      VALUES ('ТБ=04')

      INSERT @tabImport(TXT)
      VALUES ('#$')

      INSERT @tabImport(TXT)
      SELECT dbo.[RA_GETWORDNUM]([TXT], 5, '|') + dbo.[RA_GETWORDNUM]([TXT], 6, '|') + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 8, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 9, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 4, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 10, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 11, '|')
      FROM #IMPORT_TABLE
      WHERE TXT LIKE '%|%'
            AND dbo.[RA_GETWORDNUM]([TXT], 1, '|') IN ('60')
      ORDER BY [ORDER]

      INSERT @tabImport(TXT)
      VALUES ('#')

      INSERT @tabImport(TXT)
      VALUES ('#@')

      INSERT @tabImport(TXT)
      VALUES ('ТБ=05')

      INSERT @tabImport(TXT)
      VALUES ('#$')

      INSERT @tabImport(TXT)
      SELECT dbo.[RA_GETWORDNUM]([TXT], 5, '|') + dbo.[RA_GETWORDNUM]([TXT], 6, '|') + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 8, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 9, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 7, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 10, '|')
            + '|' + dbo.[RA_GETWORDNUM]([TXT], 11, '|')
      FROM #IMPORT_TABLE
      WHERE TXT LIKE '%|%'
            AND dbo.[RA_GETWORDNUM]([TXT], 1, '|') IN ('70')
      ORDER BY [ORDER]

      INSERT @tabImport(TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER]  >= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = '#& ')
      ORDER BY [ORDER]

      TRUNCATE TABLE #IMPORT_TABLE
      
      INSERT #IMPORT_TABLE ([TXT])
      SELECT [TXT]
      FROM @tabImport
      ORDER BY [ORDER]
              
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

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

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO

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

GO

/*
© Кейсистемс (Keysystems), 2008
*/
CREATE   PROCEDURE [dbo].KU_GET_NEXT_TAB
	@DEP_LINK int = null,
	@SUBDIV_LINK int = 0,
	@NEXT varchar(10) OUTPUT
AS

IF @DEP_LINK IS NULL
	SELECT @DEP_LINK = ZB_LINK FROM KS_OPTIONS_ZB

DECLARE 
	@SOST_MODE VARCHAR(1), --Использовать составную нумерацию Таб№
	@TAB_LEN INT, --Кол-во разрядов составного Таб№
	@SUB_LEN INT --Кол-во разрядов кода подразделения
	
SET	@SOST_MODE = (select top 1 RTRIM(LTRIM(value)) from s_options where object = (select link from s_objects where code = 'KADRY_OPT6'))
SET	@TAB_LEN = (select top 1 value from s_options where object = (select link from s_objects where code = 'KADRY_OPT_TAB_OPT1'))
SET	@SUB_LEN = (select top 1 value from s_options where object = (select link from s_objects where code = 'KADRY_OPT_TAB_OPT2'))

DECLARE
	@MAX_LEN INT,
	@SUB_CODE VARCHAR(10),
	@MAX_LEN_TAB INT,
	@MAX_LEN_SUB INT,
	@MIN_LEN_TAB INT,
	@MIN_LEN_SUB INT,
	@TAB VARCHAR(10)

IF @SOST_MODE = 1 BEGIN
	
	--Проверить и вписать в рамки размеры
	SET @MAX_LEN_TAB = 10
	SET @MAX_LEN_SUB = 5
	SET @MIN_LEN_TAB = ISNULL((SELECT MAX(LEN(LTRIM(RTRIM(TAB)))) FROM dbo.EMPL),1)
	SET @MIN_LEN_SUB = ISNULL((SELECT MAX(LEN(LTRIM(RTRIM(CODE)))) FROM dbo.SUBDIV),1)

	--Длина подразделения не меньше максимальной длины ранее введенного кода подразделения
	SET @SUB_LEN = CASE WHEN @SUB_LEN < @MIN_LEN_SUB THEN @MIN_LEN_SUB ELSE @SUB_LEN END
	--Длина подразделения не больше размера поля с кодом подразделения
	SET @SUB_LEN = CASE WHEN @SUB_LEN > @MAX_LEN_SUB THEN @MAX_LEN_SUB ELSE @SUB_LEN END

	--Длина табельного не меньше максимальной длины ранее введенного табельного
	SET @TAB_LEN = CASE WHEN @TAB_LEN < @MIN_LEN_TAB THEN @MIN_LEN_TAB ELSE @TAB_LEN END
	--Длина табельного не больше размера поля с табельным номером
	SET @TAB_LEN = CASE WHEN @TAB_LEN > @MAX_LEN_TAB THEN @MAX_LEN_TAB ELSE @TAB_LEN END

	IF @TAB_LEN > @SUB_LEN BEGIN

		SELECT	@NEXT = LEFT(ISNULL(CONVERT(VARCHAR(10),MAX(CONVERT(INT,RIGHT(RTRIM(LTRIM(TAB)), @TAB_LEN - @SUB_LEN)))),'0') , 10)
		FROM	EMPL
		WHERE	LTRIM(RTRIM(TAB)) NOT LIKE '%[^0-9]%'
			AND DEP_LINK = @DEP_LINK
			
		SET @NEXT = LEFT(LTRIM(STR(MAX(CONVERT(INT, @NEXT)) + 1)),10)

		SET @NEXT = LEFT(
					CASE WHEN @TAB_LEN - @SUB_LEN - LEN(@NEXT) >= 0 THEN
							LEFT('0000000000', @TAB_LEN - @SUB_LEN - LEN(@NEXT)) + @NEXT
						ELSE --Если переполнение, то сбрасываем счётчик
							LEFT('0000000000', @TAB_LEN - @SUB_LEN - LEN('1')) + '1'
					END, 10)	
	
		SET @SUB_CODE = LEFT( ISNULL((SELECT TOP 1 CODE FROM dbo.SUBDIVISION(DEFAULT) WHERE LINK = @SUBDIV_LINK),'0'), 10)
		SET @MAX_LEN = ISNULL( (SELECT MAX(LEN(RTRIM(LTRIM(CODE)))) FROM dbo.SUBDIV),1)
		SET @SUB_CODE = LEFT( LTRIM(RTRIM(LEFT('00000', @MAX_LEN - LEN(@SUB_CODE)) + @SUB_CODE)), 10)
		SET @NEXT = LEFT( @SUB_CODE + RIGHT(@NEXT,@TAB_LEN-@SUB_LEN), 10)
	END	
	ELSE
		SET @NEXT = '1'
	
END ELSE BEGIN

	SELECT	@NEXT = LEFT( ISNULL(CONVERT(VARCHAR(10),MAX(CONVERT(INT,RTRIM(LTRIM(TAB))))),'0'), 10)
	FROM	EMPL
	WHERE	LTRIM(RTRIM(TAB)) NOT LIKE '%[^0-9]%'
		AND DEP_LINK = @DEP_LINK

	SELECT	@MAX_LEN = MAX(LEN(RTRIM(LTRIM(TAB))))
	FROM	EMPL
	WHERE	LTRIM(RTRIM(TAB)) NOT LIKE '%[^0-9]%'
		AND DEP_LINK = @DEP_LINK

	SET @NEXT = LEFT( LTRIM(STR(MAX(CONVERT(INT, @NEXT)) + 1)), 10)

	IF @MAX_LEN >= LEN(@NEXT)
		SET @NEXT = LEFT( LEFT('0000000000', @MAX_LEN - LEN(@NEXT)) + @NEXT, 10)
	ELSE
		SET @NEXT = '1'
	
END




GO


GRANT EXECUTE ON dbo.[KU_GET_NEXT_TAB] TO PUBLIC

GO

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

GO

CREATE PROCEDURE dbo.X_SAVE_DOCUMENTS_INVOICE_RECEIVED
	@varKSpLINK		int	OUTPUT,
	@varKSpNUMBER	char(25) = null,
	@varKSpDATE		datetime = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment	varchar(254) = null,
	@varKSpSEL_LINK       INT = null,
	@varKSpCONS1_SELF     BIT = null,
	@varKSpCONS1_LINK     INT = null,
	@varKSpPROD_LINK      INT = null,
	@varKSpBUY_LINK       INT = null,
	@varKSpCONS2_SELF     BIT = null,
	@varKSpCONS2_LINK     INT = null,
	@varKSpNUM_BASE       VARCHAR(6) = null,
	@varKSpDATE_BASE      DATETIME = null,
	@OSNOV    	   INT = null,
	@varKSpNALOG_DOC      NUMERIC(13,2) = null,
	@varKSpBOOK_PUR       BIT = null,
	@varKSpPAYS_LINK       INT = null,
	@pTAX_RATE		NUMERIC (4,2) = NULL,
	@COR_NUM	VARCHAR (30) = '',
	@COR_DATE	DATETIME = NULL
AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKStrancount	int,
		@varKSLinkObj	int,
		@varKS_param	int


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	--Проверка рабочего периода
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	--Проверка обязательных реквизитов
	IF @varKSpBUY_LINK IS NULL OR @varKSpBUY_LINK = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END

	SELECT @varKSLinkObj = LINK
	FROM dbo.S_OBJECTS
	WHERE CODE = 'DOCUMENTS_INVOICE_RECEIVED'

	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV
			@varKSpLINK OUTPUT,
			@varKSpNUMBER,
			@varKSpDATE,
			@varKSLinkObj,
			@varKSpDATE_PROV,
			@varKSpSumma,
			@varKSpComment,
			0,
			@varKSpBUY_LINK

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_INVOICE
			@intDOC_LINK	= @varKSpLINK,
			@intSELLER	= @varKSpSEL_LINK,
			@intBUYER	= @varKSpBUY_LINK,
			@intSHIPPER	= @varKSpCONS1_LINK,
			@intRECEIVER	= @varKSpCONS2_LINK,
			@PRODUCER	= @varKSpPROD_LINK,
			@strPAY_NUM	= @varKSpNUM_BASE,
			@dPAY_DATE	= @varKSpDATE_BASE,
			@intOSNOV	= @OSNOV,
			@nTAX_RATE	= @pTAX_RATE, 
			@intINBOOK	= @varKSpBOOK_PUR,
			@SEL_SHIP	= @varKSpCONS1_SELF,
			@BUY_RECIVE	= @varKSpCONS2_SELF,
			@strCOR_NUM	= @COR_NUM,
			@dCOR_DATE	= @COR_DATE,
			@TAX_SUM	= @varKSpNALOG_DOC

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	--Ссылка на платежку
	SELECT @varKS_param = LINK
	FROM dbo.S_OBJECTS
	WHERE CODE = 'PAYS_LINK_RECEIVED'

	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_REF
				@varKSpLINK,
				@varKS_param,
				@varKSpPAYS_LINK
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	--Событие системного журнала
	SET @varKSEventText = 'Счет-фактура полученный' + ' №' + RTRIM(@varKSpNUMBER) + ' от ' + convert(varchar, @varKSpDATE, 104)
	EXECUTE dbo.WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSLinkObj, 'G_PROV', @varKSpLINK

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[X_SAVE_DOCUMENTS_INVOICE_RECEIVED] TO PUBLIC

GO


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


GO

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

GO




/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.RO_KBK_HIST_SAVE
	@varKSparLINK_UP int,
	@varKSparNAME varchar(254),
	@varKSparLONG_NAME varchar(2000),
	@varKSparDATE_BEGIN datetime
AS
IF NOT EXISTS(SELECT * FROM dbo.REPORT_KBK_HIST WHERE LINK_UP = @varKSparLINK_UP AND NAME = @varKSparNAME AND LONG_NAME = @varKSparLONG_NAME)
	INSERT INTO dbo.REPORT_KBK_HIST(LINK_UP,NAME,LONG_NAME,DATE)
	VALUES (@varKSparLINK_UP,@varKSparNAME,@varKSparLONG_NAME,@varKSparDATE_BEGIN)

EXEC dbo.[RO_KBK_CASHE_UPDATE] @varKSparLINK_UP  

DECLARE @LF INT, @LSF INT , @cCode VARCHAR(50), @cCode_Form VARCHAR(254) 

SELECT @cCode = code, @cCode_Form = code_form
FROM dbo.report_kbk
WHERE link = @varKSparLINK_UP

EXEC dbo.DropTempTable '#t_CodeRow' 
CREATE TABLE #t_CodeRow (Code VARCHAR(50))

if (@cCode_Form LIKE '%_2011_USER%' OR (RTRIM(@cCode_Form) LIKE '%_2011' AND NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = RTRIM(@cCode_Form) + '_USER' AND @cCode = Code)))
BEGIN 
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503117M','0503117G','0503127G','0503127M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503114M','0503114G','0503137G','0503137M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      TRUNCATE TABLE #t_CodeRow
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = '000'
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      IF @cCode_Form LIKE '%ЦСР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
      END
      IF @cCode_Form LIKE '%РЗПР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  

END 
GO


GRANT EXECUTE ON dbo.[RO_KBK_HIST_SAVE] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE dbo.BK_UPDATE_G_PROV_INVOICE_COR
	(@intDOC_LINK	INT,
	@intOSNOV	INT = NULL ,
	@strCOR_NUM	VARCHAR(30) = '',
	@dCOR_DATE	DATETIME = NULL,
	@INBOOK		TINYINT	= 0
	)
AS
BEGIN
	DECLARE
		@intERROR	int,
		@intRowCount	int,
		@trancount	int,
		@intObjectLink int,
		@strEventText	varchar (254)

	--- Проверка входных значений ---
	SET @intDOC_LINK = (SELECT LINK FROM dbo.G_PROV WITH (NOLOCK) WHERE LINK = @intDOC_LINK)
	SET @intOSNOV = (SELECT LINK FROM dbo.OSNOV WITH (NOLOCK) WHERE LINK = @intOSNOV)

	SELECT 	@strCOR_NUM = ISNULL (@strCOR_NUM, ''),
		@INBOOK	= ISNULL (@INBOOK, 0)

	IF @intDOC_LINK IS NULL
		RETURN 2	

	SET @trancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	UPDATE dbo.G_PROV_INVOICE_COR 
	SET	OSNOV = @intOSNOV,
		COR_NUM = @strCOR_NUM,
		COR_DATE = @dCOR_DATE,
		INBOOK = @INBOOK
	WHERE DOC_LINK = @intDOC_LINK

	SELECT @intERROR = @@ERROR, @intRowCount = @@ROWCOUNT

	IF @intRowCount = 0 AND @intERROR = 0
	BEGIN
		INSERT INTO dbo.G_PROV_INVOICE_COR
			(DOC_LINK,
			OSNOV,
			COR_NUM,
			COR_DATE,
			INBOOK
			)
		SELECT @intDOC_LINK,
			@intOSNOV,
			@strCOR_NUM,
			@dCOR_DATE,
			@INBOOK

		SELECT @intERROR = @@ERROR
	END

	IF @intERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

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

GO


GRANT EXECUTE ON dbo.[BK_UPDATE_G_PROV_INVOICE_COR] 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_SVOD_TREE_MOVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_SVOD_TREE_MOVE]
GO





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

CREATE  PROCEDURE dbo.RO_SVOD_TREE_MOVE
	@varKSLINK int,
	@varKSlink_target int,
	@varKSmovemode int,
	@linkBudgOld	int = NULL output, -- это нужно для перетаскивания отчетов
	@LinkOrgOld	int = NULL output,
	@linkBudgNew	int = NULL output,
	@linkOrgNew	int = NULL output,
	@IsSvodOld	tinyint	= 0 output,
	@IsSvodNew	tinyint = 0 output
AS
	DECLARE @link_self int, @ORDER int, @LinkBudg int, @LinkOrg int, @linkHistory int, @BeginDate datetime, @EndDate DATETIME, @link_org INT, @link_budg INT, @link_org_new INT,  @link_budg_new int

   DECLARE  @t_table TABLE (link int, link_org INT, link_budg INT, link_org_new INT, link_budg_new INT, is_svod tinyint)
   
   INSERT @t_table (link, link_org, link_budg)
   SELECT  link, link_report_org, link_report_budg
   FROM dbo.RO_SVOD_TREE 
   where Link_self = @varKSLINK
   
	select @linkBudg = link_report_budg, @LinkOrg = link_report_org, @IsSvodOld = 1 - childrens, @linkHistory = link_history from dbo.RO_SVOD_TREE where Link = @varKSLINK

	select @BeginDate = Date from dbo.report_svod_tree_history where link = @linkHistory
	select @EndDate = Date from dbo.report_svod_tree_history where Date = (select min(Date) from dbo.report_svod_tree_history where Date > @BeginDate)

	SET @ORDER = 1
	SET @link_self = NULL

	IF @varKSmovemode=0 BEGIN -- поместить после узла
		SELECT @link_self = link_self FROM report_svod_tree WHERE link=@varKSlink_target
		SELECT @ORDER = orders+1 FROM report_svod_tree WHERE link=@varKSlink_target
	END
	ELSE BEGIN -- поместить под узлом
		SET @link_self = @varKSlink_target
		SET @ORDER = 1
	END

   if @varKSLINK = @link_self or @varKSLINK = (select link_self from dbo.report_svod_tree where link = @link_self) -- проверка на зацикливание
      return -1

	DECLARE @varKStrancount int, @varKSERROR int
--	SET IMPLICIT_TRANSACTIONS ON
--	SET @varKStrancount = @@TRANCOUNT
--	BEGIN TRAN
--	COMMIT TRAN
		IF exists(SELECT * FROM report_svod_tree WHERE orders=@ORDER and Link_Self = @Link_Self)
			UPDATE report_svod_tree SET orders=orders+1 WHERE link in 
				(SELECT link FROM report_svod_tree WHERE orders>=@ORDER and Link_Self = @Link_Self)
		UPDATE report_svod_tree SET link_self=@link_self, orders=@ORDER WHERE link=@varKSLINK


update REPORT_SVOD_TREE
set LINK_REPORT_ORG= dbo.RO_SVOD_ORG(Link)

update REPORT_SVOD_TREE
set [LINK_REPORT_BUDG] = isnull(dbo.RO_SVOD_BUDG(Link),0)

/*		IF @@ERROR <> 0
		BEGIN
			IF @@TRANCOUNT > @varKStrancount
				ROLLBACK
			RETURN 7
		END
*/
	select @linkBudgNew = link_report_budg, @linkOrgNew = link_report_org, @IsSvodNew = 1 - childrens from dbo.RO_SVOD_TREE where Link = @varKSLINK

	if @linkBudg <> @linkBudgNew
		or @linkOrg <> @linkOrgNew
	begin
		set @linkBudgOld = @linkBudg
		set @linkOrgOld = @linkOrg
		exec  RO_SVOD_TREE_MOVE_REPORT 	@linkBudgOld,@LinkOrgOld,@linkBudgNew,@linkOrgNew,@IsSvodOld,@IsSvodNew, @BeginDate, @EndDate
	end

UPDATE T
SET [link_org_new] = rst.[LINK_REPORT_ORG],
   [link_budg_new] = rst.[LINK_REPORT_BUDG],
   [is_svod] = 1 - rst.[CHILDRENS]
FROM @t_table T JOIN dbo.[RO_SVOD_TREE] rst ON rst.[link] = T.[link]

DECLARE cur CURSOR LOCAL STATIC
   FOR SELECT link_org, link_budg, link_org_new, link_budg_new
       FROM @t_table
       WHERE link_org <> link_org_new OR ISNULL(link_budg, 0) <> ISNULL(link_budg_new, 0)
       
OPEN cur

FETCH NEXT FROM cur INTO @link_org, @link_budg, @link_org_new, @link_budg_new

WHILE @@FETCH_STATUS = 0
BEGIN
   exec  RO_SVOD_TREE_MOVE_REPORT 	 @link_budg, @link_org,  @link_budg_new, @link_org_new, @IsSvodOld,@IsSvodNew, @BeginDate, @EndDate
   FETCH NEXT FROM cur INTO @link_org, @link_budg, @link_org_new, @link_budg_new
END           

--	IF @@TRANCOUNT > @varKStrancount
--		COMMIT TRAN




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO


CREATE   PROCEDURE [dbo].KO_PUNKT_POSTANOV_VIBOR
	@TYPES VARCHAR(254)
AS BEGIN
	DECLARE @varKScSQLString VARCHAR(4000)
	SET @varKScSQLString=
	'SELECT 0 AS CHECKED, 0 AS UPD, 0 AS DEL, convert(bit,0) as LOCKED,'
	+ ' T.LINK, T.CODE, NAME = LEFT(T.NAME,254)'
	+ ' FROM dbo.ko_punkt_postanov T'
	+ ' WHERE T.PRIK_TYP IN (' + @TYPES + ')' 
	+ ' ORDER BY T.NAME'
	EXEC (@varKScSQLString)
END


GO


GRANT EXECUTE ON dbo.[KO_PUNKT_POSTANOV_VIBOR] 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_Tree_KBK_doschet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_Tree_KBK_doschet]
GO

/*
c Кейсистемс (Keysystems), 2010

	Досчет по дереву КБК.
	Должны существовать следующие таблицы:
*/
-- create table #TreeKBK (Link int, Link_Self int, Code_Row varchar(50), Link_Table int, Calc tinyint, cOrderTable varchar(300), Value float default(0))
-- create table #report_dinamics(Link_SF int, Code_Row varchar(50), link_col int, float_val numeric(20,4), str_val varchar(8000), Link_Table int)

CREATE           PROCEDURE dbo.RO_Tree_KBK_doschet
  @varKSiLSF  int
AS
   CREATE table #t_TreeKBK_cols (Link_Table int, Cols varchar(100))

	--declare #Tree TABLE (Link int, Link_Self int, Value float, Link_Col INT, Code_Row varchar(50))
	declare @ExecStr nvarchar(4000), @count INT, @cStr VARCHAR(250), @region VARCHAR(250)
	create table #TreeKBK_Col (Link int, Link_Self int, Code_Row varchar(50), Link_Table int, Calc tinyint, cOrderTable varchar(300), Value float default(0), Link_Col int)
	create table #Tree (Link int, Link_Self int, Value float, Link_Col INT, Code_Row varchar(50))
   CREATE INDEX #IX_TreeKBK_Col ON #TreeKBK_Col (Link_Col, Link)
   CREATE INDEX #IX_TreeKBK_Col1 ON #TreeKBK_Col (Link_Col, Link_self)

	set @ExecStr = 'select @count = count(*) from #TreeKBK'
	exec sp_executesql @ExecStr, N'@count int output', @count = @count output

	if isnull(@count, 0) = 0
		return 0

	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
         JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rt.[Link_Form] 
   WHERE rsf.[Link_Saved_Form] = @varKSiLSF
      
   exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
   set @region=rtrim(isnull(@cstr,''))
   
   UPDATE #t_TreeKBK_cols
   SET cols = ''
   WHERE cols LIKE '%(%' AND (cols NOT LIKE '%' + RTRIM(@region) + '%' OR @region = '') 
   


update rd
set float_val = 0
from  #report_dinamics rd join #TreeKBK  T ON rd.Link_SF = @varKSiLSF and  rd.Code_Row = T.Code_Row and T.calc = 0 and T.Link_Table = rd.Link_Table
      JOIN #report_coloumns rc ON rd.link_col = rc.link_col
      JOIN #t_TreeKBK_cols tc ON tc.link_table = rc.link_table AND (CHARINDEX(',' + LTRIM(RTRIM(STR(rc.orders))) + ',', ',' + rtrim(tc.cols) + ',') > 0 OR cols = '')       
where not exists(select top 1 * from #TreeExclude E where E.Code = rd.Code_Row and (E.Link_Col = rd.Link_Col or E.Link_Col is NULL))

insert #TreeKBK_Col (Link, Link_Self, Code_Row, Link_Table, Calc, cOrderTable, Value, Link_Col)
select T.Link, T.Link_Self, T.Code_Row, T.Link_Table, T.Calc, T.cOrderTable, RD.float_val, RD.Link_Col
from #TreeKBK T join #Report_dinamics RD on T.Code_Row = RD.Code_Row and T.Link_Table = RD.Link_Table
	join #report_coloumns RC on RD.Link_Col = RC.Link_Col and RC.Col_Type = 0
    JOIN #t_TreeKBK_cols tc ON tc.link_table = rc.link_table AND (CHARINDEX(',' + LTRIM(RTRIM(STR(rc.orders))) + ',', ',' + rtrim(tc.cols) + ',') > 0 OR cols = '')


	-- грузим промежуточные итоги		

	set @ExecStr = 'insert #TreeKBK_Col (Link, Link_Self, Code_Row, Link_Table, Calc, cOrderTable, Value, Link_Col)
select T.Link, T.Link_Self, T.Code_Row, T.Link_Table, T.Calc, T.cOrderTable, 0, RC.Link_Col
from #TreeKBK T left join #report_coloumns RC on RC.Link_Table = T.Link_Table and RC.Col_Type = 0
where not exists(select * from #TreeKBK_Col T1 where T.Link_Table = T1.Link_Table and T.Link = T1.Link and RC.Link_Col = T1.Link_Col)
	and exists(select top 1 * from #TreeKBK_Col T1 where T1.Link_Self = T.Link and RC.Link_Col = T1.Link_Col)
while @@ROWCOUNT > 0
begin
insert #TreeKBK_Col (Link, Link_Self, Code_Row, Link_Table, Calc, cOrderTable, Value, Link_Col)
select T.Link, T.Link_Self, T.Code_Row, T.Link_Table, T.Calc, T.cOrderTable, 0, RC.Link_Col
from #TreeKBK T left join #report_coloumns RC on RC.Link_Table = T.Link_Table and RC.Col_Type = 0
where not exists(select * from #TreeKBK_Col T1 where T.Link_Table = T1.Link_Table and T.Link = T1.Link and RC.Link_Col = T1.Link_Col)
		and exists(select top 1 * from #TreeKBK_Col T1 where T1.Link_Self = T.Link and RC.Link_Col = T1.Link_Col)
end'

	exec sp_executesql @ExecStr, N'@varKSiLSF int', @varKSiLSF = @varKSiLSF

	-- если нет потомков, то его считать не нужно
	set @ExecStr = 'update #TreeKBK_Col
set calc = 1
where calc = 0 and not exists(select top 1 * from #TreeKBK_Col T where #TreeKBK_Col.Link = T.Link_Self and T.Link_Col = #TreeKBK_Col.Link_Col )
update #TreeKBK_Col
set calc = 1
from #TreeExclude E
where calc = 0 and E.Code = #TreeKBK_Col.Code_Row and (E.Link_Col = #TreeKBK_Col.Link_Col or E.Link_Col is NULL)
insert #Tree(Link, Link_Self, Value, Link_Col, Code_Row)
select Link, Link_self,  Value, Link_Col, T.Code_Row
from #TreeKBK_Col T
where T.calc = 1
while @@RowCount > 0 
begin
  insert #Tree(Link, Link_Self, Value, Link_Col, Code_Row)
	select V.Link_Self, #TreeKBK.Link_self, sum(V.Value), V.Link_Col, #TreeKBK.Code_Row
	from 
	(select Link_Self, T.Value, T.Link_Col, T.Calc
	from #TreeKBK_Col T
	where not exists (select top 1 * from #Tree T1 where T.Link = T1.Link and T.Link_Col = T1.Link_Col)
	union all
	select Link_Self, Value, Link_Col, 1
	from #Tree) V join #TreeKBK on V.Link_Self = #TreeKBK.Link
	where not exists(select top 1 * from #Tree T1 where T1.Link = V.Link_self and T1.Link_Col = V.Link_Col)
	group by V.Link_Self, #TreeKBK.Link_self, V.Link_Col, #TreeKBK.Code_Row
	having sum(V.calc) = count(*)
end'

exec sp_executesql @ExecStr, N'@varKSiLSF int', @varKSiLSF = @varKSiLSF

	set @ExecStr = 'update #report_dinamics
set float_val = isnull(T.Value, 0)
from #Tree T
where #report_dinamics.Link_SF = @varKSiLSF and #report_dinamics.Link_Col = T.Link_Col and #report_dinamics.Code_Row = T.Code_Row
insert #report_dinamics(Link_SF, Code_Row, link_col, float_val, str_val, Link_Table)
select @varKSiLSF, T.Code_Row, T.Link_Col, T.Value, '''', 0
from #Tree T
where round(isnull(T.value, 0),4) <> 0 and not exists(select top 1 * from #report_dinamics RD where RD.Link_SF = @varKSiLSF and RD.Link_Col = T.Link_Col and RD.Code_Row = T.Code_Row)'

exec sp_executesql @ExecStr, N'@varKSiLSF int', @varKSiLSF = @varKSiLSF

UPDATE rd
SET link_table = c.link_table
from #report_dinamics rd JOIN #t_col c ON rd.link_col = c.link_col
WHERE rd.link_TABLE = 0

GO
GRANT ALL ON dbo.[RO_Tree_KBK_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.[XD_OSNOV_SEARCH]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XD_OSNOV_SEARCH]

GO

CREATE PROCEDURE dbo.XD_OSNOV_SEARCH
	@intOsnovVid int,
	@strDocObjCode varchar(30),
	@strNum	varchar(25),
	@numSumm numeric(18,2),
	@strSummVid varchar(18),
	@strComment varchar(254),
	@datDate1 datetime,
	@datDate2 datetime,
	@iDepLink int = 0
AS
/* Определить тип документа */
DECLARE @intOsnovVidType int,
		@strObjectCode varchar(30),
		@strOsnovVidName varchar(150),
		@intObjectLink int,
		@strParentObjLink int

IF @strNum IS NULL
	SET @strNum = ''

SET @strNum = REPLACE(REPLACE(@strNum,'?','_'),'*','%')


IF @strComment IS NULL
	SET @strComment = ''

SET @strComment = REPLACE(REPLACE(@strComment,'?','_'),'*','%')

if @iDepLink = 0
	select @iDepLink = isnull(dbo.BK_GetDepZB(), dbo.GetOwnDepLink())

IF @intOsnovVid > 0 
BEGIN
	SELECT @intOsnovVidType = TYPE,@strObjectCode = OBJECT,@strOsnovVidName = NAME FROM BD_OSNOV_VID WHERE LINK = @intOsnovVid
	SELECT @intObjectLink = LINK FROM S_OBJECTS WHERE CODE = @strObjectCode
	
	IF @intOsnovVidType = 1
	BEGIN
		SELECT G.LINK,G.NUMBER,convert(char(10),G.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(G.COMMENT,'')) AS COMMENTS,
			   CONVERT(VARCHAR(18),ISNULL(G.SUMMA,0.0)) AS SUMMA,@strOsnovVidName AS VID_NAME,@intOsnovVid AS TYPE,@intOsnovVidType AS TP,@strObjectCode AS OBJECT	
		FROM G_PROV G WHERE G.DEP = @iDepLink 
			AND G.OBJECT = @intObjectLink AND G.[DATE] BETWEEN @datDate1 AND @datDate2
			AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
			AND (@strComment = '' OR G.COMMENT LIKE @strComment)
	 		AND (@strSummVid = '' OR (@strSummVid = 'равно' AND G.SUMMA = @numSumm)
								   OR (@strSummVid = 'меньше или равно' AND G.SUMMA <= @numSumm)
								   OR (@strSummVid = 'меньше' AND G.SUMMA < @numSumm)
								   OR (@strSummVid = 'больше или равно' AND G.SUMMA >= @numSumm)
	 							   OR (@strSummVid = 'больше' AND G.SUMMA > @numSumm))
	END
	
	IF @intOsnovVidType = 2
	BEGIN
		SELECT S.LINK,S.NUMBER,convert(char(10),S.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(S.COMMENTARY,'')) AS COMMENTS,
			   '' AS SUMMA,@strOsnovVidName AS VID_NAME,@intOsnovVid AS TYPE, @intOsnovVidType AS TP,@strObjectCode AS OBJECT		
		FROM SDOC S WHERE S.OBJECT = @intObjectLink AND S.[DATE] BETWEEN @datDate1 AND @datDate2
			AND S.LINK_DEP = @iDepLink
			AND (@strNum = '' OR S.NUMBER LIKE @strNum) 		
			AND (@strComment = '' OR S.COMMENTARY LIKE @strComment)
	END
	
	IF @intOsnovVidType = 3
	BEGIN
		SELECT O.LINK,O.NUMBER,convert(char(10),O.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(O.COMMENT,'')) AS COMMENTS,
			   '' AS SUMMA,@strOsnovVidName AS VID_NAME,@intOsnovVid AS TYPE,@intOsnovVidType AS TP,@strObjectCode AS OBJECT		
		FROM OSNOV_OTHER O WHERE O.TYPE_LINK = @intOsnovVid AND O.[DATE] BETWEEN @datDate1 AND @datDate2
			AND O.DEP = @iDepLink
			AND (@strNum = '' OR O.NUMBER LIKE @strNum) 		
			AND (@strComment = '' OR O.COMMENT LIKE @strComment)
	END
END
ELSE
BEGIN
	IF EXISTS(SELECT * FROM S_OBJECTS WHERE CODE = @strDocObjCode)
		BEGIN	
			SELECT @strParentObjLink = LINK FROM S_OBJECTS WHERE CODE = @strDocObjCode	

			SELECT G.LINK,cast(G.NUMBER as varchar(25)) as NUMBER,convert(char(10),G.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(G.COMMENT,'')) AS COMMENTS,
				   CONVERT(VARCHAR(18),ISNULL(G.SUMMA,0.0)) AS SUMMA, (SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = G.OBJECT) AS VID_NAME,	
				   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT)) AS TYPE, 1 AS TP,
					 (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT) AS OBJECT		
			FROM G_PROV G WHERE G.OBJECT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE IN 
			(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink)))
			 	AND G.[DATE] BETWEEN @datDate1 AND @datDate2
				AND G.DEP = @iDepLink
				AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR G.COMMENT LIKE @strComment)

			UNION

			SELECT S.LINK,cast(S.NUMBER as varchar(25)) as NUMBER,convert(char(10),S.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(S.COMMENTARY,'')) AS COMMENTS,
				   '' AS SUMMA,(SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = S.OBJECT) AS VID_NAME,
					   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = S.OBJECT)) AS TYPE, 2 AS TP,
					  (SELECT CODE FROM S_OBJECTS WHERE LINK = S.OBJECT) AS OBJECT		
				FROM SDOC S WHERE S.OBJECT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE IN 
				(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink)))
				AND S.[DATE] BETWEEN @datDate1 AND @datDate2
				AND S.LINK_DEP = @iDepLink
				AND (@strNum = '' OR S.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR S.COMMENTARY LIKE @strComment)

			UNION

			SELECT O.LINK,cast(O.NUMBER as varchar(25)) as NUMBER,convert(char(10),O.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(O.COMMENT,'')) AS COMMENTS,
				   '' AS SUMMA,(SELECT NAME FROM dbo.OSNOV_VID WHERE LINK = O.TYPE_LINK) AS VID_NAME,O.TYPE_LINK AS TYPE,3 AS TP, 
					(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK =O.TYPE_LINK) AS OBJECT
			FROM dbo.OSNOV_OTHER O WHERE O.TYPE_LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink) AND O.[DATE] BETWEEN @datDate1 AND @datDate2
				AND O.DEP = @iDepLink
				AND (@strNum = '' OR O.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR O.COMMENT LIKE @strComment)

		END
	ELSE
		BEGIN	
			SELECT G.LINK,G.NUMBER,convert(char(10),G.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(G.COMMENT,'')) AS COMMENTS,
			   CONVERT(VARCHAR(18),ISNULL(G.SUMMA,0.0)) AS SUMMA,(SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = G.OBJECT) AS VID_NAME,
			   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT)) AS TYPE, 1 AS TP,
			   (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT) AS OBJECT		
			FROM dbo.G_PROV G WHERE G.[DATE] BETWEEN @datDate1 AND @datDate2
			AND G.OBJECT NOT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'SHABLON_DOCUMENTS_PROV')
			AND G.DEP = @iDepLink
			AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
			AND (@strComment = '' OR G.COMMENT LIKE @strComment)
	 		AND (@strSummVid = '' OR (@strSummVid = 'равно' AND G.SUMMA = @numSumm)
								   OR (@strSummVid = 'меньше или равно' AND G.SUMMA <= @numSumm)
								   OR (@strSummVid = 'меньше' AND G.SUMMA < @numSumm)
								   OR (@strSummVid = 'больше или равно' AND G.SUMMA >= @numSumm)
	 							   OR (@strSummVid = 'больше' AND G.SUMMA > @numSumm))
		END
END	






GO


GRANT EXECUTE ON dbo.[XD_OSNOV_SEARCH] TO PUBLIC

GO


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


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

GO

CREATE   procedure [dbo].SALARY_REP_AVG @varKSLINK int
AS 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

----
select * from #V1

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

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


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

declare @M tinyint
Set @M = 12

IF @INSTR = 2 BEGIN

	Set @M = 13

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

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

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

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

----
set @norm_days = (Select case when Coalesce((Select top 1 payment from #CurDoc),0) = 1
				then dbo.norm_days(REF_EMPL,month(DATE1),YEAR(DATE1))
				else Day(dbo.dateEndOfMonth(Date1)) 
			end
		from #CurDoc)
----
CREATE TABLE #v2 (CAPTION VARCHAR(254), CODE varchar(2), d1 numeric(18,2), d2 numeric(18,2), d3 numeric(18,2), 
sm1 numeric(18,2), sm2 numeric(18,2), sm3 numeric(18,2), acct1 varchar(10), acct2 varchar(10), acct3 varchar(10), 
sr_mes numeric(18,2), sr_d numeric(18,2), sm_m1 numeric(18,2), sm_m2 numeric(18,2), 
sm_d1 numeric(18,2), sm_d2 numeric(18,2), sm_all0 numeric(18,2))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	EXEC (@varKSSQL_STR)

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

	EXEC (@varKSSQL_STR)

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

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

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


GO


GRANT EXECUTE ON dbo.[SALARY_REP_AVG] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








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

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

CREATE     PROCEDURE dbo.RO_ROUTE_USERS_CHECK
	@varKSiLinkRoute	int,
	@varKSiLSF			int
AS

	SELECT RR.sid, 
         U.user_ref as uid, 
         orders,  
         suser_sname(coalesce(RC.sid, dbo.[AdminGetSidByUID](M.[memberuid]), RR.sid)) AS Name, 
         suser_sname(coalesce(RC.sid, dbo.[AdminGetSidByUID](M.[memberuid]), RR.sid)) as LOGIN, 
         isnull(dbo.[SD_GetEmplName]([U].[USER_REF]), '') as FIO, 
         isnull(RC.checking, 0) as checking,
         user_name(M.groupuid) AS Name_group
	FROM report_route_users RR 
      LEFT JOIN dbo.sysmembers M on M.groupuid = dbo.AdminGetUidBySid(RR.sid)
      left join dbo.[WHO_IS_WHO] U on RR.sid = U.sid OR M.[memberuid] =dbo.AdminGetUidBySid(U.sid)
		left join dbo.report_route_check RC on (RR.sid = RC.sid OR M.[memberuid] =dbo.AdminGetUidBySid(RC.sid)) and RC.LSF = @varKSiLSF
	where RR.Link_Route = @varKSiLinkRoute
	order by orders
	
	return 1
GO
GRANT ALL ON dbo.[RO_ROUTE_USERS_CHECK] 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_PRINT_PP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_PRINT_PP]
GO

CREATE PROCEDURE dbo.BB_PRINT_PP @cBufferID varchar(100)
AS BEGIN

	SELECT LINK_DOC = P.LINK,
		DataD = P.DATE, 
		Nom_Por = P.NUMBER, 
		Vidpl = CASE WHEN P.KIND IS NULL THEN ' ' ELSE LTRIM(RTRIM(P.KIND)) END, 
		[STATUS] = ISNULL(PA.STATUS, ''), 
		SUM_DOC = ISNULL(P.SUMMA, 0.00), 
		VID_OPL = CASE WHEN P.PAYKIND IS NULL THEN ' ' ELSE P.paykind END, 
		NAZ_PL = CASE WHEN P.REASON IS NULL THEN ' ' ELSE P.REASON END,
		SROK_PL = P.SROK, 
		OCHER = CASE WHEN P.[ORDER] IS NULL THEN ' ' ELSE P.[ORDER] END,
		
		--Плательщик
		PLATEL = dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, P.S_ACC_LINK), 
		--APO.SHABLON_D,APOD.SHABLON_D, 
		INN_PL = isnull(P.S_INN, ''), 
		KPP_PL = CASE WHEN ISNULL(P.PRINT_KPP, 0) = 1 THEN P.S_KPP ELSE '' END, 
		SCH_PLAT = isnull(P.S_SCH_K,P.S_ACC_NUM), 
		BIK_PLAT = isnull(P.S_BIK, SB.BIK), 
		BANK_PLAT = case isnull(DPO.FullBank, 0) when 0 then isnull(P.S_BANK, SB.name) else isnull(P.S_FBANK, SB.FNAME) end + ' ' + case isnull(DPO.Bank_cityP, 0) when 0 then '' else isnull(P.S_BANK_CITY, SB.CITY) end,
		SCH_B_PLAT = isnull(P.S_SCH_B, SB.KS), 
			
		--Получатель
		POLUCH = dbo.BB_DEP_NAME_FOR_SHABLON(CASE WHEN DOH_CODE is not null or PA.OKATO is not null or P_REASON is not null or PA.PERIOD is not null or TREBNUM is not null or TREBDATE is not null or P_TYPE is not null or STATUS is not null THEN isnull(APO.SHABLON_N, APOD.SHABLON_N) else isnull(APO.SHABLON_S, APOD.SHABLON_S) end, default, P.D_ACC_LINK), 
		INN_POL = ISNULL(P.D_INN, ''),
		KPP_POL = CASE WHEN ISNULL(P.PRINT_KPP, 0) = 1 THEN P.D_KPP ELSE '' END, 
		SCH_POL = isnull(P.D_SCH_K,P.D_ACC_NUM), 
		BIK_POL = isnull(P.D_BIK, DB.BIK), 
		BANK_POL = rtrim(case isnull(DPO.FullBank_R, 0) when 0 then isnull(P.D_BANK, DB.name) else isnull(P.D_FBANK, DB.FNAME) end) + ' ' + case isnull(DPO.Bank_city, 0) when 0 then '' else isnull(P.D_BANK_CITY, DB.CITY) end, 
		SCH_B_POL = isnull(P.D_SCH_B, DB.KS), 
		
		--Назначение платежа
		KOMM1 = case P.BK_IN_TGT when 1 then rtrim(replace(replace(replace(replace(replace(replace(
												case isnull(ltrim(rtrim(P.BO_NUM)),'') when '' then rtrim(dbo.BB_DDELIM_DEL(isnull(APO.LS_FMT, APOD.LS_FMT),'<БО>')) else isnull(APO.LS_FMT, APOD.LS_FMT) end, 
												'<БО>', isnull(ltrim(rtrim(P.BO_NUM)),'')),
												'<Счет>', case P.S_ACC_TYPE when 1 then '' else rtrim(P.S_ACC_NUM) end),
												'<Перевод_строки>', '
)'),												'<БК>',rtrim(dbo.BB_BK_FOR_SHABLON(P.LINK, isnull(APO.SHABLON_BK, APOD.SHABLON_BK),isnull(APO.DELIM, APOD.DELIM),isnull(APO.DELIM5, APOD.DELIM5)))),
													--'<БК>',/*str(P.S_ACC_LINK) + '#' +*/ APO.SHABLON_BK /*+ '#' + APO.DELIM + '#' + APO.DELIM5*/),
												'<Руб>',rtrim(ltrim(str(floor(P.SUMMA))))),
												'<Коп>', right('00' + rtrim(ltrim(str((P.SUMMA - floor(P.SUMMA)) * 100))),2))) + ' ' 
																				 
		
				else '' end + ltrim(replace(P.TARGETTEXT,char(13),'')) + ' ' + ltrim(dbo.PrintPlatporGetNDSString(P.LINK, 1)), 
		--[Num_BO] = BO_NUM,
		--targettext = targettext,
		
		-- Налоговый платеж
		DOH_CODE = rtrim(ISNULL(replace(PA.DOH_CODE,'.',''), '')) + ISNULL(PA.SGU_CODE, ''), 
		OKATO = ISNULL(PA.OKATO, ''), 
		P_REASON = ISNULL(PA.P_REASON, ''),
		PERIOD = ISNULL(PA.PERIOD, ''),
		TREBNUM = ISNULL(PA.TREBNUM, ''),
		TREBDATE = CASE WHEN PA.ZERODATE = 1 THEN '0' ELSE ISNULL(convert(varchar(10), PA.TREBDATE,  104), '') END, 
		P_TYPE = ISNULL(PA.P_TYPE, ''),  
		STATUS = ISNULL(PA.STATUS, ''), 
		DPP_REAL = '', 
		SUMPROP = '', 
		SUMREAL = '',
		
		-- Настройки
		month_prop = ISNULL(DPO.MONTH, 0), 
		ShowPoint = ISNULL(DPO.POINT, 1), 
		ShowZero = ISNULL(DPO.ZERO, 0),
		ShowEqual = ISNULL(DPO.Equal, 0),
		
		DPO.SHOW_KOP,
		--DPO.SHOW_RUB,
		DPO.SUM_UCASE,
		--APO.DELIM,
		--APO.DELIM2,
		--APO.DELIM3,
		--APO.SHOW_SM,
		--APO.DELIM5,
		--APO.SUMALONE
--		[InnAlone] = 0,
		BO = '№ ' + rtrim(FC.NUMBER) + ' от ' + convert(varchar(10), FC.DATE, 104)
		
	FROM dbo.DOCUMENTS_PAY P
	inner join dbo.DOCUMENTS_PAY_ADD PA on P.LINK = PA.LINK
	inner join dbo.BufferGetTableByID(@cBufferID) B on P.LINK = B.LINK
	inner join dbo.DOCUMENTS_PAY_OPTIONS DPO on 1=1
	left join dbo.TREASURY_ACCOUNTS DTA on DTA.LINK = P.D_SCH_K_LINK 
	left join dbo.BANKS DB on DB.LINK = DTA.BANK_LINK
	left join dbo.TREASURY_ACCOUNTS STA on STA.LINK = P.S_SCH_K_LINK 
	left join dbo.BANKS SB on SB.LINK = STA.BANK_LINK
	left join dbo.BB_PAY_ACC_OPTIONS APO on APO.LINK_ACC = P.S_ACC_LINK
	left join dbo.DOCUMENTS_PAY_ACC_OPTIONS APOD on APOD.OSN = 1
	left join dbo.DEPARTMENT_ACCOUNTS DA on APOD.LINK_ACC = DA.LINK and P.S_ACC_TYPE = DA.TYPE
	left join dbo.FINANS_CONTRACT_AND_CHANGES FC on FC.LINK = P.DOG_LINK
	where P.S_ACC_TYPE = DA.TYPE
	EXEC dbo.BufferClear @cBufferID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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

@varKSRefPay int, 
@varKSLinkVKR int,
@LINK_EKR INT, 
@varKSlinkPers int, 
@varKSMonth int, 
@varKSYear int, 
@varKSFlagMS  tinyint,
@varKSFlagShow int = 0,
@DEP_LINK INT  = NULL
AS

SET NOCOUNT ON

DECLARE @varKSDATE1 datetime, 
		  @varKSlinkFace 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 = @varKSLinkVKR),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 @varKSFlagMS = 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

SET @varKSDATE1 = dbo.DateEndOfMonth(dbo.convertDMY2Date(1,@varKSMonth,@varKSYear))
SELECT @varKSlinkFace = @varKSlinkPers 

DECLARE @varKST1 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 @varKSlinkEmpl int,  @varKSPred_Mesto_Rab numeric(15,2), 	  @varKSFlagD int

Set @varKSlinkEmpl = (Select top 1 link from dbo.empl where PERS_LINK = @varKSlinkPers)

if @varKSFlagShow = 1 
	select 'Сотрудник:  '+ LTRIM(RTRIM(P.FM)) + ' ' + SUBSTRING(LTRIM(RTRIM(P.IM)),1,1) + '.' + SUBSTRING(LTRIM(RTRIM(P.OT)),1,1)
		+  ', месяц ' + convert(varchar(2),@varKSMonth)+ ', год ' +convert(varchar(4),@varKSYear) as [Исходные данные],
		[Отчисление] = (select rtrim(name) from pays where link =@varKSRefPay)  FROM dbo.PERSON P where link = @varKSlinkFace



DECLARE @varKSNASTR TABLE
([LINK_MINROT] 	[int],
 [REF_PAY]			[int],
 [CODE]				[varchar](5),
 [NAME]				[varchar](254),
 [PREDEL]			[numeric](19, 2))

INSERT INTO @varKSNASTR([LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL])
SELECT [LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL] FROM dbo.Salary_deduct_esn(@varKSDATE1)

SELECT @varKSPred_Mesto_Rab = 0, @varKSFlagD = 0
IF YEAR(dbo.kd_DateBeginWork(@varKSlinkEmpl,null)) = @varKSYear
BEGIN
	SET @varKSPred_Mesto_Rab = (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @varKSlinkEmpl and LINK_DED in (select REF_PAY from @varKSNASTR))
	IF @varKSPred_Mesto_Rab IS null or @varKSPred_Mesto_Rab < 0
		SET @varKSPred_Mesto_Rab = 0
	SET @varKSFlagD = 1
	
	IF  @varKSFlagShow = 1 
		SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@varKSlinkEmpl)),'0')) + ' , вычеты: '+
		 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@varKSlinkEmpl and LINK_DED in (select REF_PAY from @varKSNASTR) )),'0'))  as 'Данные с предыдущего места работы'
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 G.YEAR = @varKSYear
			AND G.MONTH <= @varKSMonth
			AND G.LINK_DEP = @DEP_LINK
			AND GT.LINK_PAY = @varKSRefPay
			AND GT.PERS_LINK = @varKSlinkFace
	),0)

IF @SUM_DGH <> 0 AND @varKSFlagShow = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),@SUM_DGH),'0')) as 'Доход по договорам ГПХ'

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

INSERT INTO @varKST1 ([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 = @varKSLinkVKR 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 = @varKSLinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
FROM 
	dbo.MONTHS M,
	dbo.S_J_C_Short SJ, 
	dbo.TAX_REF TR 
WHERE 
	(TR.LINK_TAX = @varKSRefPay) AND (TR.LINK_PAYS =  SJ.LINK_PAYS) AND (SJ.LINK_FACE = @varKSlinkFace) 
	AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) AND (M.NUM <= @varKSMonth) AND (YEAR(SJ.PERIOD_BEGIN)=@varKSYear)
	AND sj.LINK_DEP = @DEP_LINK
GROUP BY  M.NUM


if @varKSFlagShow = 1 
	SELECT [num] as [Месяц], [summa] as [Сумма с нач года],summa_vkr as [Сумма с нач года по ВКР/ЕКР], summa_m as [Сумма за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР/ЕКР]  FROM @varKST1

--Если суммы, которые раньше были в базе убрали из базы, теперь базовой суммы вообще нет
IF NOT EXISTS(SELECT * FROM @varKST1)
	INSERT INTO @varKST1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	VALUES(@varKSMonth, 0, 0, 0, 0)

DECLARE @varKSTemp1_1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

INSERT INTO @varKSTemp1_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 = @varKSLinkVKR 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, 
	dbo.S_J_C_Short SJ, 
	dbo.TAX_REF TR
WHERE 
	TR.LINK_TAX = @varKSRefPay AND TR.LINK_PAYS =  SJ.LINK_PAYS AND (SJ.LINK_FACE = @varKSlinkFace)
	AND YEAR(SJ.PERIOD_BEGIN)=@varKSYear AND M.NUM <= @varKSMonth 
 	AND SJ.LINK_PAYS IN (SELECT LINK FROM dbo.PAYS WHERE LINK_INC IN
					(SELECT LINK FROM dbo.DICTIONARY_TYP_INCOMS WHERE REF_DEDUCT IN (SELECT REF_PAY FROM @varKSNASTR)))
	AND sj.LINK_DEP = @DEP_LINK
GROUP BY 
	M.NUM,SJ.LINK_PAYS

/*if @varKSFlagShow = 1  
	select *  from @varKSTemp1_1*/

DECLARE @varKSTemp1 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 @varKSTemp1 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR])
SELECT NUM,LINK_PAYS,
		[PREDEL] =  ISNULL((SELECT TOP 1 PREDEL FROM @varKSNASTR 
								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 @varKSTemp1_1
GROUP BY NUM,LINK_PAYS

DECLARE @varKSTemp2 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2),
 [SALDO]			[numeric](19,2),
 [KOEF]			[numeric](19,2))

---


INSERT INTO @varKSTemp2 ([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 @varKSPred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @varKSTemp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @varKSPred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @varKSTemp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END)
				- (CASE WHEN @varKSPred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @varKSTemp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @varKSPred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @varKSTemp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END),
		 [KOEF] 	= (CASE WHEN (SELECT SUM(MP_M) FROM @varKSTemp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) = 0 
						THEN 0 ELSE (CASE WHEN (SELECT SUM(MP_M) 
				                         FROM @varKSTemp1 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 @varKSTemp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) END) END)
FROM @varKSTemp1 T1


declare @predel numeric(18,2)
Set @predel = COALESCE((SELECT TOP 1 PREDEL FROM @varKSTemp1),0)


DECLARE @varKSTemp3 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 @varKSTemp3 ([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 @varKSTemp2 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 @varKSTemp2 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 @varKSTemp2 T --WHERE SALDO > 0
GROUP BY T.NUM,T.PREDEL,T.SALDO,T.LINK_PAYS, KOEF 
ORDER BY T.NUM

if @varKSFlagShow = 1  
	select num as [Месяц], LINK_PAYS as [Вычет], summa as [Скидка по ВКР/ЕКР], summa_all as [Скидка с начала года], summa_m as [Скидка за месяц]  from @varKSTemp3


DECLARE @varKSPREDEL_INV [numeric](15, 2)
SET @varKSPREDEL_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 <=@varKSDATE1 ORDER BY PERIOD DESC) AND (REF_PAY = @varKSRefPay)),0)

DECLARE @varKST2_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 @varKST2_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 @varKSTemp3 T WHERE T.NUM <= T1.NUM),0),  
		 [MP] 		= ISNULL((SELECT SUM(SUMMA_ALL) FROM @varKSTemp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_VKR]	= ISNULL((SELECT SUM(SUMMA) FROM @varKSTemp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M] 	= ISNULL((SELECT SUM(SUMMA_M) FROM @varKSTemp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA_M_VKR) FROM @varKSTemp3 T WHERE T.NUM = T1.NUM),0),  
--		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA) FROM @varKSTemp3 T WHERE T.NUM = T1.NUM),0),  
		 [STATUS] 	= dbo.is_invalid(@varKSlinkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,T1.NUM,@varKSYear))), 
		 [INV] 		= cast(0 as numeric(15,2))
FROM @varKST1 T1 
GROUP BY T1.NUM,T1.SUMMA,T1.SUMMA_VKR,T1.SUMMA_M,T1.SUMMA_M_VKR
ORDER BY T1.NUM


DECLARE @varKSsumma_m 	[numeric](15, 2), 
		  @varKSmp_m 		[numeric](15, 2),
		  @varKSnum 		[int], 
		  @varKSFlag 		[bit], 
		  @varKSitog 		[numeric](15, 2)

SET @varKSitog = 0
DECLARE TMP_CUR CURSOR
FOR SELECT SUMMA_M, MP_M,NUM FROM @varKST2_1 WHERE STATUS = 2
OPEN TMP_CUR
FETCH TMP_CUR INTO @varKSsumma_m,@varKSmp_m,@varKSnum
WHILE (@@FETCH_STATUS  = 0) AND (@varKSPREDEL_INV - @varKSitog) > 0 BEGIN
	IF @varKSPREDEL_INV < (@varKSitog+ @varKSsumma_m - @varKSmp_m)
		UPDATE @varKST2_1 SET INV =(@varKSPREDEL_INV-@varKSitog) WHERE NUM = @varKSnum
	ELSE
		UPDATE @varKST2_1 SET INV =(@varKSsumma_m - @varKSmp_m) WHERE NUM = @varKSnum
	
	SET @varKSitog = @varKSitog + @varKSsumma_m - @varKSmp_m
	FETCH TMP_CUR INTO @varKSsumma_m,@varKSmp_m,@varKSnum
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 @varKSNASTR 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) = @varKSYear
	and
	E.PERS_LINK = @varKSlinkPers	
	and 
	MONTH(cj.PERIOD_BEGIN) <= @varKSMonth
	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 @varKST2_1 SET INV = ISNULL(INV,0) + ISNULL((SELECT SUM(SUMMA_M) FROM #DED_U WHERE MON = NUM),0)

--Расчет налога
--
DECLARE @varKST2 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]) -- Категория тарифа

INSERT INTO @varKST2 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],[INV_VKR],[TARIF])
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(@varKSlinkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@varKSYear))) = 2 THEN 3 ELSE @TARIF END
FROM 
	@varKST2_1

if @varKSFlagShow = 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 [ТАРИФ]  from @varKST2
	

DECLARE @varKSWAY_CALC [int]
SELECT @varKSWAY_CALC = WAY_CALC FROM dbo.PAYS WHERE LINK = @varKSRefPay

DECLARE @varKSPred table  
(
 TARIF TINYINT,	
 [PREDEL]  [numeric](15, 2), 
 [PERCENT] [numeric](8, 2),
 WAY_CALC TINYINT)

IF @varKSWAY_CALC<5
	
	IF @varKSFlagMS = 1
		INSERT INTO @varKSPred (TARIF, [PREDEL],[PERCENT])
		SELECT TARIF, [PREDEL],[PERCENT] FROM dbo.DICTIONARY_RANGE D
		WHERE
			(LINK_PAYS = @varKSRefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @varKSRefPay) AND DATE < @varKSDATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @varKSPred (TARIF, [PREDEL],[PERCENT])
		SELECT TOP 1 TARIF, [PREDEL] = 999999999999, [PERCENT] 
		FROM dbo.DICTIONARY_RANGE D
		WHERE 
			(LINK_PAYS = @varKSRefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @varKSRefPay) AND DATE < @varKSDATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
ELSE 
BEGIN	
		
	DECLARE @varKSSex 		[int], 
			  @varKSYearB 	[int], 
			  @varKSType 		[int]

	SELECT @varKSSex = SEX, @varKSYearB = CASE WHEN RESIDENT = 1 THEN ISNULL(YEAR(BIRTHDATE),0) 
												ELSE 1966 END -- иностранцы по тарифам как для 66 года и страрше
											FROM dbo.PERSON WHERE LINK =@varKSlinkFace
	SET 	@varKSType = (CASE WHEN (@varKSSex = 1 AND @varKSYearB < 1953) OR (@varKSSex = 2 AND @varKSYearB<1957) THEN 1
						WHEN (@varKSSex = 1 AND @varKSYearB BETWEEN 1953 AND 1966) OR (@varKSSex = 2 AND  @varKSYearB BETWEEN 1957 AND 1966) THEN 2 
						ELSE 3 END)
	
	IF @varKSFlagMS = 1 
		INSERT INTO @varKSPred (TARIF, [PREDEL],[PERCENT],WAY_CALC)
		SELECT
			TARIF,  
			[PREDEL],
			[PERCENT] = (CASE WHEN @varKSType = 1 THEN PERCENT1 WHEN @varKSType = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @varKSRefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND LINK_PAYS = @varKSRefPay AND DATE < @varKSDATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @varKSPred (TARIF, [PREDEL],[PERCENT],WAY_CALC)
		SELECT TOP 1
			TARIF, 
			[PREDEL] = 999999999999,
			[PERCENT] = (CASE WHEN @varKSType = 1 THEN PERCENT1 WHEN @varKSType = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @varKSRefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND LINK_PAYS = @varKSRefPay AND DATE < @varKSDATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
END

IF @varKSFlagShow = 1 
	select TARIF as [Тариф], Predel as [Предел], [Percent] as [Процент] from @varKSPred

DECLARE @varKSres TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2))

INSERT INTO @varKSres([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON])
SELECT T7.[NUM],T7.[SUMMA],T7.[SUMMA_M_VKR],T7.[PERC], CAST(0 as numeric(15,2)) AS SUM_MON
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 @varKSPred P WHERE B.TARIF = P.TARIF AND PREDEL > (SUMMA - MP + @SUM_DGH) ORDER BY PREDEL) T),0)
	 FROM @varKST2	B
	 UNION
	 SELECT DISTINCT
		[NUM] 			= ISNULL((SELECT MIN(NUM) FROM @varKST2 B1 WHERE B1.TARIF = B.TARIF AND (SUMMA-MP+@SUM_DGH) > PREDEL),12), 
		[SUMMA] 		= PREDEL - @SUM_DGH, 
		[SUMMA_M_VKR]= 0, 
		[PERC] 		= [PERCENT]  
 	 FROM 
 		@varKST2 B INNER JOIN @varKSPred T ON B.TARIF = T.TARIF
 	 WHERE 
 		PREDEL < (SELECT TOP 1 (SUMMA - MP + @SUM_DGH) FROM @varKST2 B1 WHERE B1.TARIF = B.TARIF ORDER BY 1 DESC)
 	) T7

DECLARE Curs CURSOR FAST_FORWARD FOR
SELECT NUM,SUMMA FROM @varKSres ORDER BY [NUM]  

DECLARE @varKSSumma [numeric] (19, 2), 
	@varKSsumma_prev [numeric] (19, 2), 
	@varKSnum1 [int]


SET @varKSsumma_prev = 0
OPEN Curs
FETCH NEXT FROM Curs INTO @varKSnum1, @varKSSumma
WHILE @@FETCH_STATUS = 0 BEGIN
	UPDATE @varKSres SET SUM_MON = @varKSSumma - @varKSsumma_prev WHERE NUM = @varKSnum1 AND SUMMA = @varKSSumma
	SET @varKSsumma_prev = @varKSSumma
  	FETCH NEXT FROM Curs INTO @varKSnum1, @varKSSumma
END
CLOSE Curs
DEALLOCATE Curs

DECLARE @varKSResult1 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))


INSERT INTO @varKSResult1 ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = dbo.is_min(T1.SUM_MON, ISNULL((SELECT INV FROM @varKST2 T4  WHERE T4.NUM = T1.NUM),0)  
						- ISNULL((SELECT SUM(T3.SUM_MON) FROM @varKSres 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 @varKST2 T2 WHERE T2.NUM = T1.NUM)
FROM @varKSres T1


DECLARE @varKSRESULT 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))


INSERT INTO @varKSRESULT ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = (CASE WHEN SKIDKA < 0 THEN 0 ELSE SKIDKA END),
		 [KOEF]
FROM @varKSResult1

DECLARE @varKSRazn 			[numeric](15, 2), 
	  @varKSNalCurr 	[numeric](15, 2),
	  @varKSSum1 		[numeric](15, 2)


--Расчет с копейками
SET @varKSNalCurr = (SELECT sum(ROUND((PERC * (COALESCE(SUM_MON,0) - COALESCE(SKIDKA,0))* COALESCE(KOEF,0)/100) * 100, 2) / 100) FROM @varKSRESULT )
--Сумма ранее начисленного взноса
SET @varKSSum1 = ISNULL((SELECT SUM(SJ.SUMMA) FROM dbo.S_J_C_Short SJ 
WHERE SJ.LINK_VKR = @varKSLinkVKR 
	--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 = @varKSRefPay 
	AND (SJ.LINK_FACE = @varKSlinkFace) 
	AND MONTH_BEGIN <= @varKSMonth 
	AND YEAR_BEGIN=@varKSYear 
	AND sj.LINK_DEP = @DEP_LINK),0)
	
SET @varKSRazn = @varKSNalCurr - @varKSSum1

DECLARE @varKSFLG INT
SELECT TOP 1 @varKSFLG = 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 @varKSRazn <0 AND @varKSFLG = 0
	SET @varKSRazn=0

SELECT [SUMMA] 		= ISNULL(SUMMA_VKR,0), 
	 [SUMMA_VKR] 	= ISNULL(SUMMA_M_VKR, 0),
	 [SUM_DED] 		= ISNULL((SELECT TOP 1 MP_VKR FROM @varKST2 WHERE NUM = @varKSMonth), 0),
	 [INV_M] 		= ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @varKSRESULT WHERE NUM = @varKSMonth),0),
	 [INV] 			= ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @varKSRESULT WHERE NUM <= @varKSMonth),0),
	 [DED_M] 		= ISNULL((SELECT TOP 1 MP_M_VKR FROM @varKST2 WHERE NUM = @varKSMonth), 0),
	 [NALOG] 		= @varKSNalCurr, 
	 [NAL_DED] 		= @varKSSum1, 
	 [NAL_CUR] 		= @varKSRazn
FROM @varKST1 WHERE NUM = @varKSMonth

SET NOCOUNT OFF




GO


GRANT EXECUTE ON dbo.[SALARY_FILL_DED_ESN_VKR] 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_TABLE_FHD_PRINT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_TABLE_FHD_PRINT]
GO




CREATE                PROCEDURE dbo.FB_TABLE_FHD_PRINT
	@varKSiLink		int,
	@varKSintSummaType	tinyint = 1,
	@varKSTypeKBK 		tinyint	= 0
	

AS
declare	@iTypePrint tinyint
if exists(select GP.LINK from dbo.G_PROV GP 
	  inner join dbo.S_OBJECTS SO on GP.OBJECT = SO.LINK and SO.CODE = 'FINANS_LIMIT' or SO.CODE = 'FINANS_LIMIT_SVOD' 
	  where GP.LINK = @varKSiLink)
	exec dbo.X_GET_OPTION 'FINANS_LIMIT_OPTIONS_UM', 0, @iTypePrint

set @iTypePrint = isnull(@iTypePrint,0)

DECLARE @varKSTempTable TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT, 
	P1	[numeric](28, 2) NULL,
	P2	[numeric](28, 2) NULL,
	P3	[numeric](28, 2) NULL,
	P4	[numeric](28, 2) NULL,
	P5	[numeric](28, 2) NULL,
	P6	[numeric](28, 2) NULL,
	P7	[numeric](28, 2) NULL,
	P8	[numeric](28, 2) NULL,
	P9	[numeric](28, 2) NULL,
	P10	[numeric](28, 2) NULL,
	P11	[numeric](28, 2) NULL,
	P12	[numeric](28, 2) NULL,
	ITOG 	[numeric](28, 2))

DECLARE @varKSTempTable1 TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	P1	[numeric](28, 2) NULL,
	P2	[numeric](28, 2) NULL,
	P3	[numeric](28, 2) NULL,
	P4	[numeric](28, 2) NULL,
	P5	[numeric](28, 2) NULL,
	P6	[numeric](28, 2) NULL,
	P7	[numeric](28, 2) NULL,
	P8	[numeric](28, 2) NULL,
	P9	[numeric](28, 2) NULL,
	P10	[numeric](28, 2) NULL,
	P11	[numeric](28, 2) NULL,
	P12	[numeric](28, 2) NULL,
	ITOG 	[numeric](28, 2) NULL,
	ITOG_Y 	[numeric](28, 2) NULL)

DECLARE @varKSTempTableGroup TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	IT		tinyint,	
	P1	[numeric](28, 2) NULL,
	P2	[numeric](28, 2) NULL,
	P3	[numeric](28, 2) NULL,
	P4	[numeric](28, 2) NULL,
	P5	[numeric](28, 2) NULL,
	P6	[numeric](28, 2) NULL,
	P7	[numeric](28, 2) NULL,
	P8	[numeric](28, 2) NULL,
	P9	[numeric](28, 2) NULL,
	P10	[numeric](28, 2) NULL,
	P11	[numeric](28, 2) NULL,
	P12	[numeric](28, 2) NULL,
	ITOG 	[numeric](28, 2) NULL,
	ITOG_Y 	[numeric](28, 2) NULL)

DECLARE @varKSTempTableDopEkr TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	IT		tinyint,	
	P1	[numeric](28, 2) NULL,
	P2	[numeric](28, 2) NULL,
	P3	[numeric](28, 2) NULL,
	P4	[numeric](28, 2) NULL,
	P5	[numeric](28, 2) NULL,
	P6	[numeric](28, 2) NULL,
	P7	[numeric](28, 2) NULL,
	P8	[numeric](28, 2) NULL,
	P9	[numeric](28, 2) NULL,
	P10	[numeric](28, 2) NULL,
	P11	[numeric](28, 2) NULL,
	P12	[numeric](28, 2) NULL,
	ITOG 	[numeric](28, 2) NULL,
	ITOG_Y 	[numeric](28, 2) NULL)

DECLARE @varKSTempTableDopEkr2 TABLE( 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	IT		tinyint,	
	P1	[numeric](28, 2) NULL,
	P2	[numeric](28, 2) NULL,
	P3	[numeric](28, 2) NULL,
	P4	[numeric](28, 2) NULL,
	P5	[numeric](28, 2) NULL,
	P6	[numeric](28, 2) NULL,
	P7	[numeric](28, 2) NULL,
	P8	[numeric](28, 2) NULL,
	P9	[numeric](28, 2) NULL,
	P10	[numeric](28, 2) NULL,
	P11	[numeric](28, 2) NULL,
	P12	[numeric](28, 2) NULL,
	ITOG 	[numeric](28, 2) NULL,
	ITOG_Y 	[numeric](28, 2) NULL,
	DOP_EKR	INT)

DECLARE	@varKSintLimType	tinyint,
	@varKSintLimPer		tinyint,
	@varKScObjCode		varchar(30),
	@varKSintDopEkr		tinyint,
	@varKSintAbs		tinyint,
	@varKSintFyear 		int, 
	@varKSdDate 		datetime, 
	@varKSintPer_num	int, 
	@varKScTypeBudg 	Char(1), 
	@varKScTypePer	 	TINYINT 

	

	
SELECT @varKSintDopEkr = FIN_DOP_EKR from workmode
SELECT @varKSintAbs 	= ISNULL((PARAM & 0x4),0) / 4,
	@varKSintFyear 	= FYEAR
FROM FINANSE_HEAD F 
WHERE LINK = @varKSiLink

SELECT @varKSdDate 	= DATE FROM G_PROV WHERE LINK = @varKSiLink

SELECT	@varKSintLimPer = max(FIN_SMETA_PER) FROM WorkMode
IF @varKSintSummaType = 2 
BEGIN 
	IF @varKSintLimPer = 1
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1),  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SUM(ITOG)
		FROM dbo.FINANS_TABLE_YEAR_1000 T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
	IF @varKSintLimPer = 2 
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1), 0, 0, 
				  sum(P4), 0, 0, 
				  sum(P7), 0, 0, 
				  sum(P10), 0, 0, SUM(ITOG)
		FROM dbo.FINANS_TABLE_QUARTERS_1000  T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
	IF @varKSintLimPer = 3
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1), sum(P2) , sum(P3), 
				  sum(P4), sum(P5), sum(P6), 
				  sum(P7), sum(P8), sum(P9), 
				  sum(P10), sum(P11), sum(P12), SUM(ITOG)
		FROM dbo.FINANS_TABLE_MONTHS_1000  T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
END
ELSE
BEGIN	
	IF @varKSintLimPer = 1
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SUM(ITOG)
		FROM dbo.FINANS_TABLE_YEAR  T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
	IF @varKSintLimPer = 2
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1), 0, 0, 
				  sum(P4), 0, 0, 
				  sum(P7), 0, 0, 
				  sum(P10), 0, 0, SUM(ITOG)
		FROM dbo.FINANS_TABLE_QUARTERS T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
	IF @varKSintLimPer = 3
		INSERT INTO @varKSTempTable (vkr, ekr, dop_cl, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG)
		SELECT  VKR, EKR, DOP_CL, sum(P1), sum(P2) , sum(P3), 
				  sum(P4), sum(P5), sum(P6), 
				  sum(P7), sum(P8), sum(P9), 
				  sum(P10), sum(P11), sum(P12), SUM(ITOG)
		FROM dbo.FINANS_TABLE_MONTHS  T
		inner join dbo.KOSGU EKR on EKR.LINK = T.EKR 
		inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
		WHERE LINK_UP = @varKSiLink  
			  and (KBK.[TYPE] = 1 and @varKSTypeKBK = 1 or KBK.[TYPE] = 2 and @varKSTypeKBK = 0 or KBK.[TYPE] > 2 and EKR.DB_KR = @varKSTypeKBK)
		GROUP BY VKR, EKR, DOP_CL
END

INSERT INTO @varKSTempTable1
SELECT F.VKR, F.EKR, F.DOP_CL, 
	F.P1 + isnull(FS.P1,0) AS P1, 
	F.P2 + isnull(FS.P2,0) AS P2, 
	F.P3 + isnull(FS.P3,0) AS P3, 
	F.P4 + isnull(FS.P4,0) AS P4, 
	F.P5 + isnull(FS.P5,0) AS P5, 
	F.P6 + isnull(FS.P6,0) AS P6, 
	F.P7 + isnull(FS.P7,0) AS P7, 
	F.P8 + isnull(FS.P8,0) AS P8, 
	F.P9 + isnull(FS.P9,0) AS P9, 
	F.P10 + isnull(FS.P10,0) AS P10, 
	F.P11 + isnull(FS.P11,0) AS P11, 
	F.P12 + isnull(FS.P12,0) AS P12, 
	F.ITOG + isnull(FS.P1 + FS.P2 + FS.P3 + FS.P4 + FS.P5 + FS.P6 + FS.P7 + FS.P8 + FS.P9 + FS.P10 + FS.P11 + FS.P12 ,0) AS ITOG,
	F.ITOG + isnull(FS1.P1,0) AS ITOG_Y

FROM @varKSTempTable F
LEFT JOIN dbo.FB_REST_FINANS(@varKSintFyear, @varKSdDate, @varKSintPer_num, @varKSintSummaType,@varKSiLink, @varKScObjCode, @varKScTypePer, @varKScTypeBudg,DEFAULT) FS 
	ON @varKSintAbs = 1 AND
		F.VKR = FS.VKR AND 
		F.EKR = FS.EKR AND 
		(F.DOP_CL = FS.DOP_CL OR  F.DOP_CL IS NULL AND FS.DOP_CL IS NULL)
LEFT JOIN dbo.FB_REST_FINANS(@varKSintFyear, @varKSdDate, 0, @varKSintSummaType,@varKSiLink, @varKScObjCode, 1, @varKScTypeBudg,DEFAULT) FS1 
	ON @iTypePrint = 1 AND
		F.VKR = FS1.VKR AND 
		F.EKR = FS1.EKR AND 
		(F.DOP_CL = FS1.DOP_CL OR  F.DOP_CL IS NULL AND FS1.DOP_CL IS NULL)

if exists(select * from workmode where FIN_TABLE_DOP_CL = 0)
	INSERT INTO @varKSTempTableGroup (vkr, ekr, dop_cl, IT, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG, ITOG_Y)
	SELECT  VKR, EKR, NULL, 0, sum(P1), sum(P2) , sum(P3), 
			  sum(P4), sum(P5), sum(P6), 
			  sum(P7), sum(P8), sum(P9), 
			  sum(P10), sum(P11), sum(P12), SUM(ITOG), SUM(ITOG_Y)
	FROM @varKSTempTable1
	GROUP BY VKR, EKR
else
	INSERT INTO @varKSTempTableGroup (vkr, ekr, dop_cl, IT, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, ITOG, ITOG_Y)
	SELECT  VKR, EKR, DOP_CL, 0, 
			  sum(P1), sum(P2) , sum(P3), 
			  sum(P4), sum(P5), sum(P6), 
			  sum(P7), sum(P8), sum(P9), 
			  sum(P10), sum(P11), sum(P12), SUM(ITOG), SUM(ITOG_Y)
	FROM @varKSTempTable1
	GROUP BY VKR, EKR, DOP_CL
	UNION 
	SELECT  VKR, EKR, NULL, case when (select count(*) from @varKSTempTable1 where F1.VKR = VKR and F1.EKR = EKR and DOP_CL is not null) > 0 then 1 else 0 end, 
			sum(P1), sum(P2) , sum(P3), 
			sum(P4), sum(P5), sum(P6), 
			sum(P7), sum(P8), sum(P9), 
			sum(P10), sum(P11), sum(P12), SUM(ITOG), SUM(ITOG_Y)
	FROM @varKSTempTable1  F1
	WHERE @varKSintDopEkr = 1
	GROUP BY VKR, EKR


INSERT INTO @varKSTempTableDopEkr
SELECT * FROM @varKSTempTableGroup UNION 
		SELECT F1.VKR, EKR2.LINK, null as dop_kl, 1,sum(P1) AS P1, sum(P2) AS P2, sum(P3) AS P3, 
					  sum(P4) AS P4, sum(P5) AS P5, sum(P6) AS P6, 
					  sum(P7) AS P7, sum(P8) AS P8, sum(P9) AS P9, 
					  sum(P10) AS P10, sum(P11) AS P11, sum(P12) AS P12, SUM(ITOG) AS ITOG, SUM(ITOG_Y) AS ITOG_Y
		FROM @varKSTempTableGroup F1 
		INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '0'
		INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '0' AND 
							EKR2.LINK NOT IN (SELECT EKR FROM @varKSTempTableGroup T1
										WHERE T1.VKR = F1.VKR)
		--WHERE @varKSintDopEkr = 1 and dop_cl is null  
		WHERE @varKSintDopEkr = 1 and IT = 0  
		GROUP BY F1.VKR,EKR2.LINK 


INSERT INTO @varKSTempTableDopEkr2
SELECT F.*, (CASE WHEN RIGHT(EKR5.CODE,2) = '00' THEN @varKSintDopEkr ELSE 0 END) 
	FROM @varKSTempTableDopEkr F
	INNER JOIN dbo.KOSGU EKR5 ON EKR5.LINK = F.EKR 		
	UNION 
SELECT F2.VKR, EKR4.LINK, null as dop_kl, 0, sum(P1) AS P1, sum(P2) AS P2, sum(P3) AS P3, 
				  sum(P4) AS P4, sum(P5) AS P5, sum(P6) AS P6, 
				  sum(P7) AS P7, sum(P8) AS P8, sum(P9) AS P9, 
				  sum(P10) AS P10, sum(P11) AS P11, sum(P12) AS P12, 
				  SUM(ITOG) AS ITOG, SUM(ITOG_Y) AS ITOG_Y, 1
	FROM @varKSTempTableDopEkr F2 
	INNER JOIN dbo.KOSGU EKR3 ON EKR3.LINK = F2.EKR /*AND RIGHT(EKR3.CODE,1) = '0'*/ and IT = 0
	INNER JOIN dbo.KOSGU EKR4 ON EKR4.CODE = LEFT(EKR3.CODE,1) + '00' AND 
						EKR4.LINK NOT IN (SELECT EKR FROM @varKSTempTableDopEkr T2 WHERE T2.VKR = F2.VKR)
	WHERE @varKSintDopEkr = 1 --and dop_cl is null and IT = 1  
	GROUP BY F2.VKR,EKR4.LINK

Select F.VKR, F.EKR, F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12, 
	IT.PI1, IT.PI2, IT.PI3, IT.PI4, IT.PI5, IT.PI6, IT.PI7, IT.PI8, IT.PI9, IT.PI10, IT.PI11, IT.PI12,
	SIT.PSI1, SIT.PSI2, SIT.PSI3, SIT.PSI4, SIT.PSI5, SIT.PSI6, SIT.PSI7, SIT.PSI8, SIT.PSI9, SIT.PSI10, SIT.PSI11, SIT.PSI12,
	[VKR_CODE] = VKR.CODE,
	[VKR_NAME] = VKR.NAME,
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = rtrim((case when F.DOP_CL is null then EKR.NAME else DCL.NAME end)) + case F.IT when 1 then '(Итого)' else '' end, --EKR.NAME
	[DOP_CODE] = DCL.CODE,
	--[DOP_NAME] = DCL.NAME,
	F.ITOG,IT.ITOGI, SIT.ITOGSI,
	F.ITOG_Y,IT.ITOGI_Y, SIT.ITOGSI_Y, F.DOP_EKR
	From @varKSTempTableDopEkr2 F  
	LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
	left outer JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
	left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
	left JOIN (SELECT VKR, sum(P1) AS PI1, sum(P2) AS PI2, sum(P3) AS PI3, 
					  sum(P4) AS PI4, sum(P5) AS PI5, sum(P6) AS PI6, 
					  sum(P7) AS PI7, sum(P8) AS PI8, sum(P9) AS PI9, 
					  sum(P10) AS PI10, sum(P11) AS PI11, sum(P12) AS PI12, SUM(ITOG) AS ITOGI, SUM(ITOG_Y) AS ITOGI_Y
		FROM @varKSTempTableDopEkr2
		where (@varKSintDopEkr = DOP_EKR)
		group by vkr) IT ON IT.VKR = F.VKR
	left JOIN (SELECT sum(P1) AS PSI1, sum(P2) AS PSI2, sum(P3) AS PSI3, 
					  sum(P4) AS PSI4, sum(P5) AS PSI5, sum(P6) AS PSI6, 
					  sum(P7) AS PSI7, sum(P8) AS PSI8, sum(P9) AS PSI9, 
					  sum(P10) AS PSI10, sum(P11) AS PSI11, sum(P12) AS PSI12, SUM(ITOG) AS ITOGSI, SUM(ITOG_Y) AS ITOGSI_Y
		FROM @varKSTempTableDopEkr2
		where (@varKSintDopEkr = DOP_EKR)) SIT ON 1 = 1 
	ORDER BY VKR.CODE,EKR.CODE, DCL.CODE, F.IT desc 

--select @varKSintDopEkr,* from @varKSTempTableDopEkr2
RETURN 1





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.FB_TABLE_FHD_PRINT to public
GO


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

GO

CREATE   PROCEDURE dbo.SZV4_PACHKA_PROVERKA (@result int output, @link int, @mode tinyint)
AS

if @mode = 0 
BEGIN
	Select @result = proverka from dbo.SZV4_PACHKA where link = @link
	RETURN 0
END

if @mode = 1
BEGIN
	set @result = 0

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
		@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9)--, @varKSRESULT INT

	SELECT 
		@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
		@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP
	FROM DICTIONARY_DEPARTMENT D 
	WHERE D.link = @DEP_LINK

	declare @year_begin int
	set @year_begin = (SELECT year_begin FROM dbo.SZV4_PACHKA WHERE LINK = @link)

--	EXEC SD_CHECK_INN @varKSINN, @varKSRESULT OUTPUT, 0

	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSKPP,'')))) = 0 THEN 'Не указан КПП организации;' else '' end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSKPP,'')))) = 0 
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSOKPO,'')))) = 0 THEN 'Не указан ОКПО организации;' else '' end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSOKPO,'')))) = 0 
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) = 0 THEN 'Не указан ИНН организации;' 
		else (case when LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) < 10  then 'Не верный ИНН организации ' + RTRIM(LTRIM(COALESCE(@varKSINN,''))) else '' end) end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) < 10  --or @varKSRESULT = -1
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) = 0 THEN 'Не указан номер регистрации организации в ПФР;' 
		else (case when LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) <> 14 then 'Не верный номер регистрации организации в ПФР ' + RTRIM(LTRIM(COALESCE(@varKSNOM_PF,''))) else '' end) end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) <> 14
	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' не указан(ы) атрибут(ы):' + 
		(case when coalesce(FM,'') = '' then ' Фамилия;' else '' end) + 
		(case when coalesce(IM,'') = '' then ' Имя;' else '' end) + 
		--(case when coalesce(OT,'') = '' then ' Отчество;' else '' end) + 
		(case when coalesce(PF_NUM,'') = '' then ' Страховой номер ПФ;' else '' end) + 
		(case when len(coalesce(ADDRESS2,'')) <= 9 then ' Адрес' else '' end)
	from dbo.sa_szv4_svedenia
	where	
		link = @link
		and (
		coalesce(FM,'') = ''
		or coalesce(IM,'') = ''
		--or coalesce(OT,'') = ''
		or coalesce(PF_NUM,'') = ''
		or len(coalesce(ADDRESS2,'')) <= 9
		)
	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' Ошибка:' + 
		+ (case when coalesce(dper_vn_m,0)>12 or coalesce(dper_oz_m,0)>12 then ' Кол-во месяцев не может быть больше 12;' else '' end)
		+ (case when coalesce(dper_vn_d,0)>=30 or coalesce(dper_oz_d,0)>=30 then ' Кол-во дней должно быть меньше 30;' else '' end)
		+ (case when (coalesce(dper_vn_m,0) + coalesce(dper_vn_d,0) / 30 + coalesce(dper_oz_m,0) + coalesce(dper_oz_d,0) / 30) > 12 then 
				' Сумма периодов по врем. нетрудосп. и отпуска без сохранения З/П не должна превышать 12 мес.;' else '' end)	

	from dbo.sa_szv4_svedenia
	where	
		link = @link
		and (
		coalesce(dper_vn_m,0)>12
		or coalesce(dper_vn_d,0)>=30
		or coalesce(dper_oz_m,0)>12
		or coalesce(dper_oz_d,0)>=30
		or (coalesce(dper_vn_m,0) + coalesce(dper_vn_d,0)/30 + coalesce(dper_oz_m,0) + coalesce(dper_oz_d,0)/30) > 12
		)

	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' Ошибка:' + 
		+ ' Пересекающиеся периоды в стаже!'
	from dbo.sa_szv4_svedenia SV
	where	
		link = @link
		and exists (select * from dbo.SZV4_stazh S1 inner join dbo.SZV4_stazh S2 on S1.link_up = S2.link_up and  S1.link <> S2.link
		where S1.link_up = SV.link1 and (S1.date1 between S2.date1 and S2.date2 or S1.date2 between S2.date1 and S2.date2)) 
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Задолженность на начало перирда за ' + convert(varchar(4),@year_begin-1) + ' может быть только положительной!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
		or
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
		or
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Задолженность на начало перирда за ' + convert(varchar(4),@year_begin) + ' может быть только отрицательной!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
		or
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
		or
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' страховых взносов должна быть равной задолженности за этот период!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_str) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_str) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' накопительных взносов должна быть равной задолженности за этот период!'
	where
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_nak) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_nak) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' взносов по доп.тарифу должна быть равной задолженности за этот период!'
	where
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_dop) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_dop) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION 
		/* не должно быть физлиц, по которым в данном периоде нет сумм и сведений о стаже */	
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' , но могут появиться перечисленные суммы после распределения. Если после операции распределения у этого сотрудника не появятся перечисленные суммы, то удалите его из списка.'
	from dbo.sa_szv4_svedenia S
	WHERE link = @LINK AND sum_doh = 0 AND INSUR = 0 AND GAIN = 0 AND DOP = 0 and sum_uplata_dolga_str = 0 and sum_uplata_dolga_nak = 0
	AND NOT EXISTS (SELECT * FROM dbo.SZV4_STAZH ST WHERE ST.LINK_UP = S.LINK1)
	Order by pachka, orders

	if @@ROWCOUNT = 0 
	BEGIN
		exec dbo.SZV4_NUMERATOR @link
		update dbo.szv4_pachka set proverka = 1 where link = @link
		set @result = 1
	END		


END

RETURN 0



GO


GRANT EXECUTE ON dbo.[SZV4_PACHKA_PROVERKA] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE [dbo].[RO_CHECK_033MBT_125]
AS
declare @link_sf     int,
		@link_f        int,
		@curr_form     varchar(50),
      @j             INT,
      @table         TINYINT,
      @iLink_Table   INT,
      @link_f_125    INT,
      @period_type   TINYINT,
      @period_number TINYINT,
      @period_date   DATETIME,
      @cGroupKS      VARCHAR(30),
      @cCODE_RULE    CHAR(9),
      @okato_org     VARCHAR(20),
      @cExecStr      VARCHAR(8000),
      @adm           CHAR(3),
      @nomErr        INT,
      @IS_GRBS       BIT ,
      @LinkOrg       INT,
      @Codeorg       VARCHAR(30) 

CREATE TABLE #mdks_125 ([CODE_RULE]       CHAR(9),
                        [KSBU]            CHAR(9),
                        [SIGN]            CHAR(2),
                        [FILTER]          VARCHAR(8000),
                        [ORDER_TABLE]     TINYINT,
                        [PART]           TINYINT,
                        [ORDER_COL] TINYINT,
                        [FO_GRBS]        TINYINT,
                        [LINK_FORM]        INT,
                        [CODE_ORG]        VARCHAR(10))
                        
CREATE TABLE #summand_reports_125([CODE_RULE]       CHAR(9),
                           [PART]            TINYINT,
                           [LSF]             INT,
                           [ORDER_TABLE]     TINYINT,
                           [ORDER_COL]           TINYINT,
                           [FO_GRBS]        TINYINT,                           
                           [SIGN]            CHAR(2),
                           [CODE_ORG]           VARCHAR(20))

CREATE TABLE #summand_125( [CODE_RULE]       CHAR(9),
                           [PART]            TINYINT,
                           [LSF]             INT,
                           [ORDER_TABLE]     TINYINT,
                           [ORDER_COL]       TINYINT,
                           [CODE]            VARCHAR(250),
                           [CODE_ROW]        VARCHAR(250),
                           [SIGN]            CHAR(2),
                           [VALUE]           NUMERIC(20,4),
                           [CODE_ORG]        VARCHAR(20),
                           [FO_GRBS]         TINYINT)

CREATE TABLE #Result_125 ([CODE_RULE]        CHAR(9),
                          [CODE]             VARCHAR(250),
                          [PART]             TINYINT,
                          [VALUE]            NUMERIC(20,2))                             

CREATE TABLE #Result_sr_125 ([CODE_RULE]        CHAR(9),
                             [CODE]             VARCHAR(250),
                             [LEFT_VALUE]       NUMERIC(20,4),
                             [RIGHT_VALUE]      NUMERIC(20,4)) 
                             
                            
SELECT TOP 1 @link_sf = lf.lsf,
       @cGroupKS = cGroupKS,
       @link_f = lf.linkForm,
       @adm = dbo.RN_GET_ATR_VALUE (lf.lsf ,'REPORTS_ATR_ADM')
FROM   #ListForms AS lf
WHERE  lf.linkForm IN (SELECT link_form
                       FROM   dbo.report_forms
                       WHERE  code = '033_МБТ')
                              
SELECT @link_f_125 = rf.[Link_Form]
FROM dbo.[REPORT_FORMS] rf
WHERE rf.code = '0503125M' AND rf.[Start_Date] = '20110101'  

set @IS_GRBS = 1
if @link_sf is null BEGIN
   SELECT TOP 1 @link_sf = lf.lsf,
          @cGroupKS = cGroupKS
   FROM   #ListForms AS lf
   WHERE  lf.linkForm = @link_f_125
   if @link_sf is NULL
   BEGIN    
	   select @nomErr=MAX(ORDERS) FROM #res 
	   insert #Res(orders, res, cdoc, ctable,cCol,cValue,ckod)	
	   select @nomErr+1,'-','Проверка отменена! Не найден сохраненный отчёт по ф.033_МБТ или ф.0503125М','','','',''
      RETURN
   END
   set @IS_GRBS = 0
   SELECT @link_f = link_form
   FROM   dbo.report_forms
   WHERE  code = '033_МБТ'  
END

SELECT @period_type = rsf.[Period_Type], @period_number = rsf.[Period_Number], @period_date = rsf.[Begin_Date], @LinkOrg = Link_Organization, @Codeorg = d.code    
FROM dbo.[REPORT_SAVED_FORMS] rsf 
   LEFT JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
WHERE rsf.[Link_Saved_Form] = @link_sf

SELECT @iLink_Table = LINK_TABLE 
FROM dbo.[REPORT_TABLES] rt
WHERE  rt.[Link_Form] = @link_f AND rt.[Orders] = 1


INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [ORDER_COL],
         [FO_GRBS],
         [LINK_FORM],
         [CODE_ORG])
SELECT   LTRIM(RTRIM(STR(rc.orders - 3))),
         '',
         '+',
         '',
         1,
         1,
         RC.[Orders],
         0, -- 1 - ФО, 0 - ГРБС
         @link_f,
         ''
FROM dbo.[REPORT_COLOUMNS] rc 
WHERE rc.[Orders] > 3 AND rc.[Link_Table] = @iLink_Table  
      AND (@IS_GRBS = 1 OR LEFT(rc.name,5) = @Codeorg)

INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [ORDER_COL],
         [FO_GRBS],
         [LINK_FORM],
         [CODE_ORG])
SELECT   LTRIM(RTRIM(STR(rc.orders - 3))),
         '120551660',
         '+',
         '',
         1,
         0,
         8,
         1, -- 1 - ФО, 0 - ГРБС
         @link_f_125,
         LEFT(rc.name,5) 
FROM dbo.[REPORT_COLOUMNS] rc 
WHERE rc.[Orders] > 3 AND rc.[Link_Table] = @iLink_Table  
      AND (@IS_GRBS = 1 OR LEFT(rc.name,5) = @Codeorg)

INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [ORDER_COL],
         [FO_GRBS],
         [LINK_FORM],
         [CODE_ORG])
SELECT   LTRIM(RTRIM(STR(rc.orders - 3))),
         '120551660',
         '-',
         '',
         1,
         0,
         7,
         1, -- 1 - ФО, 0 - ГРБС
         @link_f_125,
         LEFT(rc.name,5) 
FROM dbo.[REPORT_COLOUMNS] rc 
WHERE rc.[Orders] > 3 AND rc.[Link_Table] = @iLink_Table
      AND (@IS_GRBS = 1 OR LEFT(rc.name,5) = @Codeorg)  

INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [ORDER_COL],
         [FO_GRBS],
         [LINK_FORM],
         [CODE_ORG])
SELECT   LTRIM(RTRIM(STR(rc.orders - 3))),
         '120551560',
         '-',
         '',
         1,
         0,
         7,
         1, -- 1 - ФО, 0 - ГРБС
         @link_f_125,
         LEFT(rc.name,5)
FROM dbo.[REPORT_COLOUMNS] rc 
WHERE rc.[Orders] > 3 AND rc.[Link_Table] = @iLink_Table
      AND (@IS_GRBS = 1 OR LEFT(rc.name,5) = @Codeorg)

INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [ORDER_COL],
         [FO_GRBS],
         [LINK_FORM],
         [CODE_ORG])
SELECT   LTRIM(RTRIM(STR(rc.orders - 3))),
         '120551560',
         '+',
         '',
         1,
         0,
         8,
         1, -- 1 - ФО, 0 - ГРБС
         @link_f_125,
         LEFT(rc.name,5)
FROM dbo.[REPORT_COLOUMNS] rc 
WHERE rc.[Orders] > 3 AND rc.[Link_Table] = @iLink_Table    
      AND (@IS_GRBS = 1 OR LEFT(rc.name,5) = @Codeorg)
   
IF NOT EXISTS(SELECT TOP 1 * FROM #mdks_125) -- нет правил для данного КСБУ
   RETURN

IF @IS_GRBS = 1
BEGIN 
          INSERT #summand_reports_125  ([CODE_RULE],
                              [PART],
                              [LSF],
                              [ORDER_TABLE],
                              [ORDER_COL],
                              [FO_GRBS],
                              [SIGN],
                              [CODE_ORG])
          SELECT  M.[CODE_RULE],
                  M.[PART],
                  CASE WHEN [FO_GRBS] = 0 THEN @link_sf
                             ELSE  dbo.[RT_GET_LSF](   @link_f_125 /*@link_f*/,
			                                                            @period_type /*@period_type*/,
			                                                            @period_number /*@period_number*/,
			                                                            @period_date /*@period_date*/,
			                                                            /*'120505660'*/ [ksbu] /*@ksbu*/,
			                                                            0 /*@is_grbs*/,
			                                                            null /*@org_type*/,
			                                                            null /*@ppp*/,
			                                                            null /*@okato*/,
			                                                            d.[LINK]) END,
                  [ORDER_TABLE],
                  [ORDER_COL],
                  [FO_GRBS],
                  [SIGN],
                  [CODE_ORG]
          FROM #mdks_125 M
            LEFT JOIN dbo.[DEPARTMENTS] d ON d.[CODE] = M.[CODE_ORG]

      INSERT #summand_125([CODE_RULE],
                           [PART],
                           [LSF],
                           [ORDER_TABLE],
                           [ORDER_COL], -- 1 - дебет, 0 - кредит
                           [CODE],
                           [CODE_ROW],
                           [SIGN],
                           [VALUE],
                           [CODE_ORG],
                           [FO_GRBS])
       SELECT R.[CODE_RULE],
              R.[PART],
              R.[LSF],
              R.[ORDER_TABLE],
              R.[ORDER_COL],
              CASE WHEN R.[FO_GRBS] = 1 THEN SUBSTRING(D.[CODE_ROW],1,3) + SUBSTRING(D.[CODE_ROW],20,5) + SUBSTRING(D.[CODE_ROW],28,2) ELSE RTRIM(dbo.RN_GET_ATR_VALUE (r.lsf ,'REPORTS_ATR_ADM')) +  LEFT(D.[CODE_ROW], 5) + SUBSTRING(D.[CODE_ROW], 9,2) END ,
              D.[CODE_ROW],
              CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN CASE WHEN R.[SIGN] = '+' THEN '-' ELSE '+' END  ELSE R.[SIGN] END,
              [VALUE] = CASE WHEN R.[SIGN] = '+' THEN 
                                       CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN -D.[FLOAT_VAL] ELSE  D.[FLOAT_VAL] END 
                                       ELSE CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN D.[FLOAT_VAL] ELSE  -D.[FLOAT_VAL] END END,
              R.[CODE_ORG],
              R.[FO_GRBS]                                   
       FROM #summand_reports_125 R
            LEFT JOIN dbo.report_dinamics_all D ON R.[LSF] = D.[LINK_SF]
           JOIN dbo.report_coloumns C ON C.[LINK_COL] = D.[LINK_COL] AND C.[Col_Type] = 0 AND C.[Orders] = R.[ORDER_COL]
           JOIN dbo.[REPORT_TABLES] T ON T.[Link_Table] = C.[Link_Table] AND T.[Orders] = R.[ORDER_TABLE]
       WHERE  (R.[FO_GRBS] = 0 OR SUBSTRING(D.[CODE_ROW],1,3) = @adm) AND (R.[FO_GRBS] = 1 OR (D.Code_Row <> '20200000000000000' AND D.[CODE_ROW] NOT LIKE '202__000__0000151'))
                        
END
ELSE 
BEGIN
   CREATE TABLE #ppp (ppp CHAR(3))

 
   INSERT #ppp( ppp)
   SELECT DISTINCT LEFT(code_row,3)
   FROM dbo.report_dinamics rd
      JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Saved_Form] = rd.[Link_SF]
      JOIN dbo.report_coloumns rc ON rc.[Link_Col] = rd.[Link_Col]
      JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] AND rt.orders <> 4
   WHERE rsf.[Link_Form] = @link_f_125
               AND del = 0
               AND rsf.[Period_Type] = @period_type
               AND rsf.[Period_Number] = @period_number
               AND rsf.[Begin_Date] = @period_date
               AND rsf.link_organization = @LinkOrg
               AND substring(rsf.atr_code,22,9) IN (SELECT #mdks_125.[KSBU] FROM #mdks_125)
               AND rsf.[Version] = (SELECT MAX(rsf2.version)
                                    FROM dbo.report_saved_forms rsf2
                                    WHERE rsf.[Link_Form] = rsf2.[Link_Form]
                                          AND rsf.[Begin_Date] = rsf2.[Begin_Date]
                                          AND rsf.[Period_Type] = rsf2.[Period_Type]
                                          AND rsf.[Period_Number] = rsf2.[Period_Number]
                                          AND rsf.[atr_code] = rsf2.[atr_code]
                                          AND rsf2.[Del] = 0
                                          AND rsf2.[Link_Organization] = rsf.[Link_Organization]
                                          AND ISNULL(rsf2.[Link_Type_Svod], 0) = ISNULL(rsf.[Link_Type_Svod], 0)) 

          INSERT #summand_reports_125  ([CODE_RULE],
                              [PART],
                              [LSF],
                              [ORDER_TABLE],
                              [ORDER_COL],
                              [FO_GRBS],
                              [SIGN],
                              [CODE_ORG])
          SELECT  M.[CODE_RULE],
                  M.[PART],
                   dbo.[RT_GET_LSF](   @link_f_125 /*@link_f*/,
			                                                            @period_type /*@period_type*/,
			                                                            @period_number /*@period_number*/,
			                                                            @period_date /*@period_date*/,
			                                                            /*'120505660'*/ [ksbu] /*@ksbu*/,
			                                                            0 /*@is_grbs*/,
			                                                            null /*@org_type*/,
			                                                            null /*@ppp*/,
			                                                            null /*@okato*/,
			                                                            @LinkOrg),
                  [ORDER_TABLE],
                  [ORDER_COL],
                  [FO_GRBS],
                  [SIGN],
                  [CODE_ORG]
          FROM #mdks_125 M
          WHERE [FO_GRBS] = 1
    
          INSERT #summand_reports_125  ([CODE_RULE],
                              [PART],
                              [LSF],
                              [ORDER_TABLE],
                              [ORDER_COL],
                              [FO_GRBS],
                              [SIGN],
                              [CODE_ORG])
          SELECT  M.[CODE_RULE],
                  M.[PART],
                   rsf.[Link_Saved_Form],
                  [ORDER_TABLE],
                  [ORDER_COL],
                  [FO_GRBS],
                  [SIGN],
                  [CODE_ORG]
          FROM #mdks_125 M,
          dbo.report_saved_forms rsf
          LEFT JOIN dbo.[DICTIONARY_DEPARTMENT] dd ON rsf.[Link_Organization] = dd.[LINK]
          WHERE [FO_GRBS] = 0 and rsf.[Link_Form] = @link_f
               AND del = 0
               AND rsf.[Period_Type] = @period_type
               AND rsf.[Period_Number] = @period_number
               AND rsf.[Begin_Date] = @period_date
               AND dd.[VED] IN (SELECT ppp FROM #ppp)
               AND RTRIM(dbo.RN_GET_ATR_VALUE (rsf.link_saved_form ,'REPORTS_ATR_ADM')) IN (SELECT ppp FROM #ppp) 
               AND rsf.[Link_Type_Svod] = (SELECT link FROM dbo.[KL_BUDG_TYPE] kbt WHERE code = 'С')
               AND rsf.[Version] = (SELECT MAX(rsf2.version)
                                    FROM dbo.report_saved_forms rsf2
                                    WHERE rsf.[Link_Form] = rsf2.[Link_Form]
                                          AND rsf.[Begin_Date] = rsf2.[Begin_Date]
                                          AND rsf.[Period_Type] = rsf2.[Period_Type]
                                          AND rsf.[Period_Number] = rsf2.[Period_Number]
                                          AND rsf.[atr_code] = rsf2.[atr_code]
                                          AND rsf2.[Del] = 0
                                          AND rsf2.[Link_Organization] = rsf.[Link_Organization]
                                          AND ISNULL(rsf2.[Link_Type_Svod], 0) = ISNULL(rsf.[Link_Type_Svod], 0))
                                          

     DROP TABLE #ppp

      INSERT #summand_125([CODE_RULE],
                           [PART],
                           [LSF],
                           [ORDER_TABLE],
                           [ORDER_COL], -- 1 - дебет, 0 - кредит
                           [CODE],
                           [CODE_ROW],
                           [SIGN],
                           [VALUE],
                           [CODE_ORG],
                           [FO_GRBS])
       SELECT R.[CODE_RULE],
              R.[PART],
              R.[LSF],
              R.[ORDER_TABLE],
              R.[ORDER_COL],
              CASE WHEN R.[FO_GRBS] = 1 THEN SUBSTRING(D.[CODE_ROW],1,3) + SUBSTRING(D.[CODE_ROW],20,5) + SUBSTRING(D.[CODE_ROW],28,2) ELSE RTRIM(dbo.RN_GET_ATR_VALUE (r.lsf ,'REPORTS_ATR_ADM')) +  LEFT(D.[CODE_ROW], 5) + SUBSTRING(D.[CODE_ROW], 9,2) END ,
              D.[CODE_ROW],
              CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN CASE WHEN R.[SIGN] = '+' THEN '-' ELSE '+' END  ELSE R.[SIGN] END,
              [VALUE] = CASE WHEN R.[SIGN] = '+' THEN 
                                       CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN -D.[FLOAT_VAL] ELSE  D.[FLOAT_VAL] END 
                                       ELSE CASE WHEN R.[FO_GRBS] = 1 AND SUBSTRING(D.[CODE_ROW],20,5) LIKE '219%' THEN D.[FLOAT_VAL] ELSE  -D.[FLOAT_VAL] END END,
              R.[CODE_ORG],
              R.[FO_GRBS]                                   
       FROM #summand_reports_125 R
            LEFT JOIN dbo.report_dinamics_all D ON R.[LSF] = D.[LINK_SF]
           JOIN dbo.report_coloumns C ON C.[LINK_COL] = D.[LINK_COL] AND C.[Col_Type] = 0 AND C.[Orders] = R.[ORDER_COL]
           JOIN dbo.[REPORT_TABLES] T ON T.[Link_Table] = C.[Link_Table] AND T.[Orders] = R.[ORDER_TABLE]
       WHERE  (R.[FO_GRBS] = 1 OR (D.Code_Row <> '20200000000000000' AND D.[CODE_ROW] NOT LIKE '202__000__0000151'))
            
 END
 

 TRUNCATE TABLE #summand_reports_125


----------------
-- ФОРМИРОВАНИЕ ПРОТОКОЛА
INSERT #Result_125 ([CODE_RULE],
                    [CODE],
                    [PART],
                    [VALUE])
SELECT [CODE_RULE],
        [CODE],
        [PART],
        SUM([VALUE]) 
FROM #summand_125
GROUP BY [CODE_RULE],
         [CODE],
         [PART]   
         
         
                               
INSERT #Result_sr_125 ([CODE_RULE],
                    [CODE],
                    [LEFT_VALUE],
                    [RIGHT_VALUE])
SELECT ISNULL(L.[CODE_RULE], R.[CODE_RULE]),
        ISNULL(L.[CODE],R.[CODE]),
        ISNULL(L.[VALUE], 0),
        ISNULL(R.[VALUE], 0) 
FROM (select * from #Result_125 WHERE part = 1) L 
      FULL JOIN 
      (select * from #Result_125 WHERE part <> 1) R ON L.[CODE_RULE] = R.[CODE_RULE] AND R.[CODE] = L.[CODE]
WHERE abs(ISNULL(L.[VALUE], 0) - ISNULL(R.[VALUE], 0)) > 0.001

-- для ускорения протокола
declare @t table (orders int)
	insert @t values(1)
	insert @t values(3)
	insert @t values(6)
	insert @t values(7)
	insert @t values(8)
 insert #Res (orders, res, cDoc, cPeriod, cBudg, cKod, cTable, cCol, cValue)
select orders, isnull(res,''), isnull(cDoc,''), cPeriod, cBudg, isnull(cKod,''), isnull(cTable,''), isnull(cCol, ''), isnull(cValue, '') from
(select orders, case orders when 1 then '№' + [CODE_RULE] else '' end as Res,
	case orders when 1 then '033_МБТ  Бюджет субъекта = ФО: 0503125M КСБУ120551660 - ФО: 0503125M КСБУ= 120551560' when 6 then 'Результат слева' when 7 then 'Результат справа' when 8 then 'Отклонение' else '' end as cDoc, case orders when 1 then 'Группа: ' + isnull(@cGroupKS, '') else '' end as cPeriod, '' as cBudg,
	 case orders when 1 then '' when 3 then '=' else '' end as cKod, '' as cTable, '' as cCol, case orders when 6 then ltrim(dbo.[rn_convert_number]([LEFT_VALUE],2,' ')) when 7 then ltrim(dbo.[rn_convert_number]([RIGHT_VALUE],2,' ')) when 8 then '<font color="#ff0000">' + ltrim(dbo.[rn_convert_number]([LEFT_VALUE]-[RIGHT_VALUE],2, ' ')) else '' end as cValue, [CODE], [CODE_RULE], '' as OrderRow
from #Result_sr_125 S left join @t on 1 = 1
union all
select 2 + (1-part) * 2, '', isnull(rf.Code, '') + ' ' + RSF.[atr] + ' Организация: ' + dbo.GetDepName(rsf.[Link_Organization], rsf.[Begin_Date])  ,
       '' AS cPeriod, isnull(kbt.[Name],''), 
      CASE WHEN LEN(S.Code_Row) < 20 THEN S.Code_Row ELSE [sign] + 'ППП: ' + LEFT(S.Code_Row,3) + ' ОКАТО: ' + SUBSTRING(S.Code_Row,4, 11) + ' Элемент: ' + SUBSTRING(S.Code_Row, 15, 2) + ' КБК: ' + SUBSTRING(S.Code_Row, 17, 3) + ' ' + SUBSTRING(S.Code_Row, 20, 14) + ' Корр.счет: ' + SUBSTRING(S.Code_Row, 34, 9) END,  
      '№' + LTRIM(STR([ORDER_TABLE])), '№' + LTRIM(STR(S.[ORDER_COL])) + ' ' + isnull(rc.[Name], ''), ltrim(dbo.[rn_convert_number](S.[VALUE], 2, ' ')),  S.[CODE], S.[CODE_RULE], LTRIM(STR([PART])) 
from #summand_125 S inner join #Result_sr_125 R on S.[CODE_RULE] = R.[CODE_RULE] and isnull(S.[CODE], '') = isnull(R.[CODE], '')
LEFT JOIN dbo.[REPORT_COLOUMNS] rc ON rc.[Link_Table] = @iLink_Table AND rc.orders = S.[ORDER_COL]  AND S.FO_GRBS = 0
   left join dbo.report_saved_forms RSF ON RSF.[Link_Saved_Form] = S.[LSF]
   LEFT JOIN dbo.report_forms RF ON RF.[Link_Form] = RSF.[Link_Form]
   LEFT JOIN dbo.[KL_BUDG_TYPE] kbt ON kbt.[Link] = RSF.[Link_Type_Svod]) A
order by [CODE_RULE], [CODE], orders, OrderRow

select 0 

EXEC dbo.DropTempTable '#mdks_125'
                        
EXEC dbo.DropTempTable '#summand_reports_125'

EXEC dbo.DropTempTable '#summand_125'

EXEC dbo.DropTempTable '#Result_125'                             

EXEC dbo.DropTempTable '#Result_sr_125'
 
GO
GRANT EXECUTE ON [dbo].[RO_CHECK_033MBT_125] 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.[dd_rep2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[dd_rep2]

GO
CREATE  PROCEDURE [dbo].[dd_rep2] 
	@link_doc int
AS	
	declare @event varchar(100)
	
	set @event = 'WF_EVENT_TASK'
	
	select 	a.ord,
		[task] = ET.TASK_AUTH_NAME + char(10)+' ('+ convert(varchar(10),ET.TASK_DATE,104) +coalesce(' '+DT.[name],'')+')' + char(10) + a.task,
		et.link,
		[EXECUTOR_NAME] =  EE.EXECUTOR_NAME,
		[EXECUTOR_NAME_FULL]  = EE.EXECUTOR_NAME + char(10)+ '(срок ' + convert(varchar(10),EE.SROK_DATE,104) +
		   case isp when 1 then ', подтверждено '+ convert(varchar(10),EE.ISP_DATE,104) + ')' 
			    when 0 then ')' end,--dbo.sd_GetEmplName(EE.EXECUTOR)
		[EXECU_TEXT]     = case when EU.COMMENT is null or EU.COMMENT = '' then EE.EXECUTOR_NAME + char(10) + '(нет комментариев к исполнению)' else EE.EXECUTOR_NAME+ '(' + convert(varchar(10),EE.SROK_DATE,104)+')' + char(10) + EU.COMMENT end,
		[EXECU_DATE]	 = coalesce(convert(varchar(10),EU.EXECU_DATE,104),'')
	into #tmp_res
	from (select * from dbo.sa_show_executors_fn(@link_doc, 0) where [event] = ltrim(rtrim(@event)) OR @event IS NULL) a
	inner join event_links el on a.link = el.link
	inner join wf_event_task et on el.event_link = et.link
	INNER JOIN wf_EVENT_EXECUTOR EE ON EE.LINK_DOC = @link_doc  AND EE.CHECKED = 1
		and exists (select null from EVENT_TASK_REF where link_executors = EE.link AND link_TASK = ET.LINK )
	LEFT JOIN WF_EVENT_EXECUTE EU ON EU.LINK_DOC = @link_doc
		  	AND EU.LINK_EXECUTORS = EE.LINK
	LEFT JOIN wf_doctask DT on et.task_link = dt.link


	declare @tmp1 table  ([LINK] int , executors varchar(700))
	declare socur cursor local read_only
		for Select distinct link,EXECUTOR_NAME_FULL from #tmp_res

	declare @link int, @prev_link int, @exec_col varchar(700), @executor_name_full varchar(700)
	open socur
	FETCH NEXT FROM socur INTO @link, @executor_name_full
	select @prev_link = @link, @exec_col = ''
	set @exec_col = @exec_col + @executor_name_full + char(10)

	WHILE @@FETCH_STATUS = 0
	begin
		FETCH NEXT FROM socur INTO @link, @executor_name_full
		if @link <> @prev_link
		begin
			insert into @tmp1 (link,executors) values(@prev_link,@exec_col)
			set @exec_col = ''
			set @exec_col = @exec_col + rtrim(@executor_name_full) + char(10)
		end
		else 
			set @exec_col = @exec_col + @executor_name_full + char(10)

		set @prev_link = @link
	end
		insert into @tmp1 (link,executors) values(@prev_link,@exec_col)
--select t1.ord,t1.task,t2.executors,t1.execu_text,
select t1.ord,
	[docvid_par] = (select wf.[name] from documents d, wf_docvid wf where d.link = @link_doc and d.doc_vid = wf.link ),
	[ishnisp] = (select ishnisp from documents where link = @link_doc),
	[ishdisp]=(select ishdisp from documents where link = @link_doc),
	[docname] = (select [name] from documents where link = @link_doc),	
	[executors] = replace(t2.executors,char(13),''),	
	[task] = replace(t1.task,char(13),''),
	[execu_text] = replace(t1.execu_text,char(13),'')
from #tmp_res t1 inner join @tmp1 t2 on t1.link = t2.link





GO


GRANT EXECUTE ON dbo.[dd_rep2] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

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

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

CREATE PROCEDURE dbo.[RO_PRINT_RK_27C]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
	declare @table varchar(100), @RunStr varchar(8000), @vcCode VARCHAR(50), @vcName VARCHAR(2000), @i INT, @vcI VARCHAR(10), @vcCSR VARCHAR(100), @vcRzPR VARCHAR(1000)

	create table #table (COL1 varchar(2000), COL2 varchar(200), COL3 varchar(200), COL4 varchar(200), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2), COL16 NUMERIC(20,2), COL17 NUMERIC(20,2), COL18 NUMERIC(20,2), CODE varchar(50))
   CREATE TABLE #res(COL1 varchar(2000), COL2 varchar(200), COL3 varchar(200), COL4 varchar(200), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2), COL16 NUMERIC(20,2), COL17 NUMERIC(20,2), COL18 NUMERIC(20,2), CODE varchar(50), COL_RZPR VARCHAR(1000))
      
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18, CODE from ' + @table
	insert #table (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18, CODE) execute(@RunStr)
   
   INSERT #res (COL1, COL2,COL3,COL4, CODE)
   SELECT DISTINCT COL1,COL2,COL3,COL4, CODE
   FROM #table
   WHERE COL2 = '8888'
   
   UPDATE R
   SET COL5 = T.COL5,
      COL6 = T.COL6,
      COL7 = T.COL7,
      COL8 = T.COL8,
      COL9 = T.COL9,
      COL10 = T.COL10,
      COL11 = T.COL11,
      COL12 = T.COL12,
      COL13 = T.COL13,
      COL14 = T.COL14,
      COL15 = T.COL15,
      COL16 = T.COL16,
      COL17 = T.COL17,
      COL18 = T.COL18                 
   FROM #RES R JOIN #table T ON R.CODE = T.CODE AND T.COL2 = '8888'
   
   DECLARE cur CURSOR LOCAL STATIC 
      FOR SELECT DISTINCT COL3 FROM #RES WHERE COL3 <> '8888888'

   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcCSR
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
      SET @vcRzPR = ''
      
      SELECT @vcRzPR = @vcRzPR + RTRIM(COL2) + ', ' 
      FROM #table
      WHERE COL3 = @vcCSR
            and COL2 <> '8888'
      GROUP BY COL2

      UPDATE  #res
      SET COL_RZPR = SUBSTRING(@vcRzPR, 1, LEN(@vcRzPR) - 1)  
      WHERE COL3 = @vcCSR         
      
      FETCH NEXT FROM cur INTO @vcCSR
   END  
   
   CLOSE cur
   DEALLOCATE cur             
  
   DECLARE cur CURSOR LOCAL STATIC FOR SELECT DISTINCT COL2 FROM #table WHERE COL2 <> '8888' ORDER BY COL2
   
   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcCode
   
   SET @i = 1
   SET @vcI = LTRIM(RTRIM(STR(@i)))
   
   WHILE @@FETCH_STATUS = 0 
   BEGIN
      
      SELECT @vcName = Name
      FROM dbo.R_SPR_RZPR_2011
      WHERE [CODE] = @vcCode
      
      SET @RunStr = 'ALTER TABLE #res ADD COL_C_' + @vcI + ' VARCHAR(8000) ALTER TABLE #res ADD COL_N_' + @vcI + ' VARCHAR(8000) ALTER TABLE #res ADD COL_V_' + @vcI + ' VARCHAR(8000)'
      EXECUTE (@RunStr)
      
      SET @RunStr = 'UPDATE R ' + 
      'SET COL_C_' + @vcI + ' = ''' + RTRIM(@vcCode) + ''',
            COL_N_' + @vcI + ' = ''' + RTRIM(@vcName) + ''',
         COL_V_' + @vcI + ' = LTRIM(STR(T.COL8,20,2)) + ''#'' + LTRIM(STR(T.COL9,20,2)) + ''#'' + LTRIM(STR(T.COL10,20,2)) + ''#'' + LTRIM(STR(T.COL11,20,2)) + ''#'' + LTRIM(STR(T.COL12,20,2)) + ''#'' + LTRIM(STR(T.COL13,20,2)) + ''#'' + LTRIM(STR(T.COL14,20,2)) + ''#'' + LTRIM(STR(T.COL15,20,2)) + ''#'' + LTRIM(STR(T.COL16,20,2)) ' + 
      'FROM #Res R JOIN #table T ON R.COL3 = T.COL3 and R.COL4 = T.COL4 AND T.COL2 = ''' + @vcCode +''''
      EXECUTE (@RunStr)     

      SET @i = @i + 1
      SET @vcI = LTRIM(RTRIM(STR(@i)))
      
      FETCH NEXT FROM cur INTO  @vcCode
   END

   SELECT * FROM #res ORDER BY case when COL3 = '8888888' THEN '0000000' ELSE COL3 END, case when COL4 = '888' THEN '000' ELSE COL4 END 

   TRUNCATE TABLE #table
   DEALLOCATE cur
   
   DROP TABLE #table
   DROP TABLE #res
  
       

GO
GRANT ALL ON dbo.[RO_PRINT_RK_27C] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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
		  @varKSLinkGrType int,
		  @varKSMonth int,
		  @varKSYear int
AS		 
DECLARE @varKSDateX datetime,
		  @varKSHoliday tinyint,	
		  @varKSDaysInWeek int,
		  @varKSDaysInMonth int,
		  @varKSFirstDay datetime,
		  @varKSLastDay datetime,
		  @varKSDay int,
		  @varKSDayInGraph int,
		  @varKSCurDay datetime,
		  --для вычисления дня недели с которого перенесли день
		  @varKSCurDay2 datetime, 
		  ---
		  @varKSDayInWeek int,
		  @varKSHolidayType int,
		  @varKSHolidaySymb	varchar(5),
		  @varKSHolidayName	varchar(254),
		  @varKSHolidayHour numeric(10,2),			
		  @varKSHolType int,
		  @varKSHolSymb	varchar(5),
		  @varKSHolName	varchar(254),
		  @varKSHolHour 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 @varKSDay = 1

SELECT @varKSDateX = DATE_BEG,@varKSHoliday = HOLIDAY FROM GRAPH_VID WHERE LINK = @varKSLinkGrType


SELECT @varKSDaysInWeek = COUNT(DISTINCT NUMBER) FROM GRAPH_VID_TABLE WHERE LINK_UP = @varKSLinkGrType


SELECT * INTO #TmpDays FROM KD_GRAPH_VID_TABLE WHERE LINK = @varKSLinkGrType


SELECT @varKSFirstDay = CONVERT(DATETIME,'01.'+LTRIM(RTRIM(STR(@varKSMonth)))+'.'+LTRIM(RTRIM(STR(@varKSYear))),104)

SELECT @varKSLastDay = dbo.DateEndOfMonth(@varKSFirstDay)

SELECT @varKSDaysInMonth  = DATEDIFF(d,@varKSFirstDay,@varKSLastDay)+1

SELECT TOP 1 @varKSHolidayType =  LINK,@varKSHolidayHour = HOUR,@varKSHolidaySymb = SYMB, @varKSHolidayName = [Name] FROM KD_TYP_DAYS WHERE WORK_D = 11
IF @varKSHolidayType IS NULL 
BEGIN	
	RAISERROR ('В справочнике типы дней неправильно заполнен тип дня - выходной !',11,1)
	RETURN 111
END
WHILE @varKSDay <= @varKSDaysInMonth
BEGIN

	SET @varKSCurDay = DATEADD(d,@varKSDay,@varKSFirstDay)-1

	--Обработка ситуации, при которой день является перенесенным с другого числа
	SET @varKSCurDay2 = (
							SELECT TOP 1 CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY1)))+'.'+LTRIM(RTRIM(STR(MONTH1)))+'.'+LTRIM(RTRIM(STR(@varKSYear))),104) 
								FROM dbo.HOLIDAYS 
								WHERE ([MONTH] * 100 + [DAY]) <> ([MONTH1] * 100 + [DAY1]) AND CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(@varKSYear))),104) = @varKSCurDay
						)		
	IF @varKSDaysInWeek > 0
		IF ISNULL(@varKSCurDay2,@varKSCurDay) >= @varKSDateX
			SELECT @varKSDayInWeek = DATEDIFF(d,@varKSDateX,ISNULL(@varKSCurDay2,@varKSCurDay))%@varKSDaysInWeek+1		
		ELSE 
			SELECT @varKSDayInWeek = (@varKSDaysInWeek - DATEDIFF(d,ISNULL(@varKSCurDay2,@varKSCurDay),@varKSDateX)%@varKSDaysInWeek)%@varKSDaysInWeek +1		
	ELSE
		SELECT @varKSDayInWeek = 0		

	IF @varKSCurDay IN (SELECT CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(@varKSYear))),104) FROM KD_HOLIDAYS) AND @varKSHoliday = 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(@varKSYear))),104) = @varKSCurDay) 				
				BEGIN
					SELECT TOP 1 @varKSHolType =  LINK,@varKSHolHour = HOUR,@varKSHolSymb = SYMB, @varKSHolName = [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(@varKSYear))),104) = @varKSCurDay)

					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME, PRIORITET)
					VALUES(0,0,@varKSDay,@varKSHolHour,@varKSHolType,@varKSHolSymb,@varKSHolName,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(@varKSYear))),104) = @varKSCurDay) 				
				BEGIN
					SELECT TOP 1 @varKSHolType =  LINK, @varKSHolSymb = SYMB, @varKSHolName = [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(@varKSYear))),104) = @varKSCurDay)

					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME,PRIORITET)
					SELECT 0 AS UPD,0 AS DEL, @varKSDay AS DAY, (CASE WHEN (HOURS-1) >= 0 THEN (HOURS-1) ELSE 0 END) AS HOUR, @varKSHolType, @varKSHolSymb, @varKSHolName, 0 as PRIORITET
					FROM #TmpDays  WHERE NUMBER = @varKSDayInWeek
				END
				ELSE		
				BEGIN
					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME,PRIORITET)
					VALUES(0,0,@varKSDay,@varKSHolidayHour,@varKSHolidayType,@varKSHolidaySymb,@varKSHolidayName,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, @varKSDay AS DAY, HOURS AS HOUR,TD_LINK, TD_CODE, TD_NAME, 0 as PRIORITET
		FROM #TmpDays  WHERE NUMBER = @varKSDayInWeek
	SET @varKSDay = @varKSDay + 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].[FB_CREATE_PROV_PLAN_FHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_CREATE_PROV_PLAN_FHD]
GO

CREATE	PROCEDURE FB_CREATE_PROV_PLAN_FHD
	@varKSnLINK_DOC INT,
	@varKSnDEL	TINYINT = 0	
AS

DECLARE @varKSnTYP_LINK INT,
	@varKSnLink INT,
	@varKSnLINK_UP INT,
	@varKScNAME_OPER VARCHAR(250),
	@varKSnSumma NUMERIC(28,2),
	@varKSnKBK INT,
	@varKSnSGU INT, 
	@varKSnEKR INT, 
	@varKSnDOP_CL INT, 
	@varKSnDEP INT, 
	@varKSnDEP_ACC INT, 
	@varKSnLINK_GP1 INT,
	@varKSnORDERS INT,
	@varKSdCALC_DATE DATETIME,
	@varKSxRet	INT,
	@varKScSOU_CODE CHAR(1),
	@varKScErrTxt VARCHAR(60),
	@varKSdDATEB DATETIME,
	@varKSintYear INT,
	@varKScCodeObj VARCHAR(60),
	@varKSIs_RBS	tinyint,
	@varKScG2_NAME VARCHAR(254),
 	@varKScTypeBudg char(1),
	@varKSnDEP_POL INT,
	@varKSnACC_POL INT,
	@iYearNum	tinyint
	


SELECT 	@varKSintYear 	= FH.Fyear, 
		@varKSnDEP  	= GP.DEP, 
		@varKSnDEP_ACC  = GP.ACC,
		@varKSnDEP_POL  = DA.LINK_UP, 
		@varKSnACC_POL  = FH.ACCOUNT
FROM FINANSE_HEAD FH, G_PROV GP, department_accounts da
WHERE FH.LINK = @varKSnLINK_DOC and FH.LINK = GP.LINK and fh.ACCOUNT = DA.LINK 


DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT T.LINK,T.LINK_UP, T.VKR, T.EKR, T.DOP_CL, T.DATEB, T.ITOG, T.NAME_OPER, T.NYEAR, G1.LINK, G1.NAME_OPER, T.SOURCE_CODE
	FROM  FB_FINANS_TABLE(@varKSnLINK_DOC,1,@varKSintYear,0) T 
	inner join dbo.KOSGU SGU on SGU.LINK = T.EKR
	inner join dbo.KL_KBK KBK on KBK.LINK = T.VKR
	inner join dbo.FB_PLAN_FHD_OPTIONS O on 1 = 1
	inner join dbo.G_PROV1 G1 on G1.LINK = case when (KBK.[TYPE] = 1 or KBK.[TYPE] > 2 and SGU.DB_KR = 1) then O.TYP_LINK else O.TYP_LINK_D end
	WHERE T.ITOG <> 0

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

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

SELECT @varKSdCALC_DATE = DATE + 1 FROM G_PROV WHERE LINK = @varKSnLINK_DOC


SET @varKSnORDERS = 0

OPEN GRID_CUR
FETCH NEXT FROM GRID_CUR INTO @varKSnLink, @varKSnLINK_UP, @varKSnKBK, @varKSnEKR, @varKSnDOP_CL,/* @varKSnSGU,*/ @varKSdDATEB, @varKSnSumma, @varKScG2_NAME, @iYearNum, @varKSnTYP_LINK, @varKScNAME_OPER, @varKScTypeBudg
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSnORDERS = @varKSnORDERS + 1
	SET @varKSnLINK_GP1 = NULL
	EXEC X_UPDATE_G_PROV1 @varKSnLINK_GP1 OUTPUT, @varKSnLINK_DOC, @varKSnTYP_LINK,
			@varKScNAME_OPER, @varKSnORDERS

	IF @varKSnLINK_GP1 IS NULL
		RETURN -3	
	EXEC @varKSxRet = FB_SAVE_G_PROV2_AP_LIMIT @varKSnLINK_GP1, @varKSnTYP_LINK, @varKSnSumma, @varKSdCALC_DATE, @varKSnKBK, @varKSnEKR,  @varKSnDOP_CL,@varKSdDATEB, @varKSnDEP, @varKSnDEP_ACC, @varKScG2_NAME, @varKScTypeBudg,@varKSnDEP_POL, @varKSnACC_POL, null, @iYearNum
	select @varKSxRet
	IF @varKSxRet <> 0
	  BEGIN
	    	SET @varKScErrTxt = CASE @varKSxRet
				WHEN -1 THEN '"Не задан линк операции"'
	
			   END
	    	PRINT 'Ошибка при записи проводки по Финансированию: '
		RETURN @varKSxRet
	 END
	FETCH NEXT FROM GRID_CUR INTO @varKSnLink, @varKSnLINK_UP, @varKSnKBK, @varKSnEKR, @varKSnDOP_CL,/* @varKSnSGU,*/ @varKSdDATEB, @varKSnSumma, @varKScG2_NAME, @iYearNum, @varKSnTYP_LINK, @varKScNAME_OPER, @varKScTypeBudg
END

CLOSE GRID_CUR
DEALLOCATE GRID_CUR

EXEC X_SALDO_COMMITCHANGES	


RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/* --- ФОРМИРОВАНИЕ КО (ЕСЛИ ОСТАТОК > 0, ТО ПКО, ЕСЛИ ОСТАТОК < 0, ТО РКО???) ИЗ АО --- */
CREATE PROCEDURE BK_SAVE_KO_FROM_AO
	@parm_intLINK_AO	INT,
	@parm_intCreatePKO	BIT,
	@parm_intCreateRKO	BIT,
	@parm_intTO_PKO		INT,
	@parm_intTO_RKO		INT
	

AS
BEGIN
	DECLARE
		@intOBJ_REF_PKO	INT,
		@intOBJ_REF_RKO	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		@intLINK_EMPL	INT,
		@intLINK_SUB	INT,
		@intLINK_KBK	INT,
		@strKO_NUMBER	VARCHAR (25),
		@dDATE_KO	DATETIME,
		@nSUMMA_KO	NUMERIC (19,4),
		@strBUH_NAME	VARCHAR (100),
		@strKAS_NAME	VARCHAR (100),
		@strRUK_NAME	VARCHAR (100),
		@intLINK_TO	INT,
		@intLINK_PKO	INT,
		@intLINK_RKO	INT,

	/* -- 20070317 -- */
		@intREST_ACCT	INT,
		@cREST_SOUCE	CHAR (1),
		@cREST_ANALIT	CHAR (2),
		@cREST_USER	CHAR (4),
		@intREST_EKR	INT,
		@nREST_SUM	NUMERIC (28,4),
		@cSINTH_BY_TO	CHAR (3),
		@cANALIT_BY_TO CHAR (3),
		@intOPT_AO	INT,
		@intOPT_TO_KO	INT,
		@intPERS_LINK	INT,
		@intPERS_NAME	CHAR (25),

	/* --- РАБОТА С G_PROV1 --- */
		@intLINK_G1	INT,
		@strNAME_OPER	VARCHAR (254),
		@intORDERS	INT,
		@intLINK_KO	INT,

	/* --- РАБОТА С G_PROV2 --- */
		@intLINK_G2	INT,
		@intECON_OPER	INT,
		@intSTORNO	INT,
		@strNAME_OPER2	VARCHAR (254),
		@intLINK_G2_TO	INT,
	
	/* --- РАБОТА С G_PROV_AP --- */
		@intSGU		INT,
		@intACCOUNT	INT,
		@intEKR		INT,
		@intKAU		INT
		
	EXEC @intOBJ_REF_PKO = dbo.X_GET_OBJ_LINK 'BV_DOC_AO_KO_LINK_PKO'
	EXEC @intOBJ_REF_RKO = dbo.X_GET_OBJ_LINK 'BV_DOC_AO_KO_LINK_RKO'

	/* -- ДАННЫЕ ИЗ АО -- */
	SELECT 	@intLINK_EMPL	=	AO.EMP_LINK,
		@intLINK_SUB	=	AO.OTDEL_LINK,
		@dDATE_KO	=	AO.DATE,
		@intLINK_KBK	=	AO.KBK_LINK,
		@intDEP_LINK	=	G.DEP, 
		@intACC_LINK	=	G.ACC,
		@nSUMMA_KO	=	AO.ITOG_SUM - AO.SUMMA,
		@intOPT_AO	=	AO.[OPTION]
	FROM dbo.BV_DOC_AVANSE_REP AO
	INNER JOIN dbo.G_PROV	G ON (G.LINK = AO.LINK)
	WHERE AO.LINK = @parm_intLINK_AO

	IF @intOPT_AO = 2	-- физ.лицо
	BEGIN
		SET @intOPT_TO_KO = 4
		SET @intPERS_LINK = @intLINK_EMPL
		SET @intLINK_EMPL = NULL
		SET @intPERS_NAME = CONVERT (CHAR (25), dbo.BK_GetPersonName (@intPERS_LINK))
	END
	ELSE			-- сотрудник
		SELECT @intOPT_TO_KO = 1
	
--	SELECT @dDATE_KO = dbo.DateBeginOfDay (WORKDATE) FROM dbo.USER_INFO
	
/*
	IF @nSUMMA_KO > 0
		SET @strKO_OBJ_CODE = 'DOCUMENTS_PKO'
	ELSE
		SET @strKO_OBJ_CODE = 'DOCUMENTS_RKO'

	exec dbo.X_DOCUMENT_GET_MAX_NUMBER @strKO_OBJ_CODE, @strKO_NUMBER output, @intDEP_LINK
	if @strKO_NUMBER is null 
		set @strKO_NUMBER='1'
	else 
		set @strKO_NUMBER = convert(varchar(10),convert(int, @strKO_NUMBER)+1)

*/
	/* --- ФОРМИРОВАНИЕ КАССОВЫХ ОРДЕРОВ --- */
	SELECT @strBUH_NAME = FACE_NAME
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @intDEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT @strKAS_NAME = FACE_NAME
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @intDEP_LINK
		AND [NAME] = 'Кассир'

	SELECT @strRUK_NAME = FACE_NAME
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @intDEP_LINK
		AND [NAME] = 'Руководитель'

/*
	SET @parm_intLINK_KO = dbo.BK_GetKOLinkByAO (@parm_intLINK_AO)
	SET @intLINK_TO = (SELECT LINK FROM dbo.G_PROV1 WHERE LINK = @parm_intTO)
--		@intCur_Obj_KO

	IF @strKO_OBJ_CODE = 'DOCUMENTS_PKO' 
	BEGIN
		EXEC dbo.X_SAVE_DOCUMENTS_PKO @parm_intLINK_KO OUTPUT, @strKO_NUMBER, @dDATE_KO, DEFAULT,
			@nSUMMA_KO, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, 1, 
			@intACC_LINK, DEFAULT, DEFAULT, DEFAULT, @strBUH_NAME, @strKAS_NAME,
			DEFAULT, DEFAULT

		IF @intLINK_TO IS NULL
			SELECT @intLINK_TO = P_TYP_LINK FROM dbo.BV_DOC_AO_OPTIONS
	END
	ELSE
	BEGIN
		SET @nSUMMA_KO = ABS (@nSUMMA_KO)
		EXEC dbo.X_SAVE_DOCUMENTS_RKO @parm_intLINK_KO OUTPUT, @strKO_NUMBER, @dDATE_KO, DEFAULT,
			@nSUMMA_KO, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, 1,
			@intACC_LINK, DEFAULT, DEFAULT, DEFAULT, @strRUK_NAME, @strBUH_NAME, @strKAS_NAME,
			DEFAULT, DEFAULT, DEFAULT, DEFAULT

		IF @intLINK_TO IS NULL
			SELECT @intLINK_TO = R_TYP_LINK FROM dbo.BV_DOC_AO_OPTIONS
	END

	EXEC dbo.X_UPDATE_G_PROV_REF @parm_intLINK_AO, @intOBJ_REF, @parm_intLINK_KO
*/
	--- Создание приходного кассового ордера ---
	IF @parm_intCreatePKO = CONVERT (BIT, 1)
	BEGIN
		EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PKO', @strKO_NUMBER output, @intDEP_LINK
--		IF @strKO_NUMBER is null 
--			SET @strKO_NUMBER = '1'
--		ELSE 
--			SET @strKO_NUMBER = CONVERT(VARCHAR(15),CONVERT(BIGINT, @strKO_NUMBER)+1)

		EXEC dbo.X_SAVE_DOCUMENTS_PKO @intLINK_PKO OUTPUT, @strKO_NUMBER, @dDATE_KO, DEFAULT,
--			@nSUMMA_KO, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, 1, 
			0, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, @intOPT_TO_KO, 
			@intACC_LINK, DEFAULT, DEFAULT, DEFAULT, @strBUH_NAME, @strKAS_NAME,
			@intPERS_LINK, @intPERS_NAME

		EXEC dbo.X_UPDATE_G_PROV_REF @parm_intLINK_AO, @intOBJ_REF_PKO, @intLINK_PKO

		SET @parm_intTO_PKO = (SELECT LINK FROM dbo.G_PROV1 WHERE LINK = @parm_intTO_PKO)
	END

	--- Создание расходного кассового ордера ---
	IF @parm_intCreateRKO = CONVERT (BIT, 1)
	BEGIN
		SET @strKO_NUMBER = NULL
		EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_RKO', @strKO_NUMBER output, @intDEP_LINK
--		IF @strKO_NUMBER is null 
--			SET @strKO_NUMBER = '1'
--		ELSE 
--			SET @strKO_NUMBER = CONVERT(VARCHAR(10),CONVERT(INT, @strKO_NUMBER)+1)

		EXEC dbo.X_SAVE_DOCUMENTS_RKO @intLINK_RKO OUTPUT, @strKO_NUMBER, @dDATE_KO, DEFAULT,
--			@nSUMMA_KO, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, 1,
			0, DEFAULT, @intDEP_LINK, @intLINK_SUB, @intLINK_EMPL, @intOPT_TO_KO,
			@intACC_LINK, DEFAULT, DEFAULT, DEFAULT, @strRUK_NAME, @strBUH_NAME, @strKAS_NAME,
			DEFAULT, DEFAULT, @intPERS_LINK, @intPERS_NAME

		EXEC dbo.X_UPDATE_G_PROV_REF @parm_intLINK_AO, @intOBJ_REF_RKO, @intLINK_RKO
		SET @parm_intTO_RKO = (SELECT LINK FROM dbo.G_PROV1 WHERE LINK = @parm_intTO_RKO)
	END

-- select @strKO_NUMBER, @intDEP_LINK

	/* --- !!!СОХРАНЯЕМ ПРОВОДКИ!!! --- */
	-- Остатки по данному АО --
	DECLARE #REST CURSOR LOCAL STATIC	
		FOR SELECT ACCOUNT,
				cSOURCE,
				cANALIT,
				cUSER,
				EKR,
				SUMMA
			FROM dbo.BK_AO_GetTableRest (@parm_intLINK_AO)
			WHERE (@parm_intCreatePKO = CONVERT (BIT, 1) AND TYPE_SUM = 1)
				OR (@parm_intCreateRKO = CONVERT (BIT, 1) AND TYPE_SUM = -1)
	OPEN #REST
	FETCH FROM #REST
		INTO @intREST_ACCT, @cREST_SOUCE, @cREST_ANALIT, @cREST_USER,
			@intREST_EKR, @nREST_SUM
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @nREST_SUM > 0	-- для формирования проводки в ПКО
			SELECT @intLINK_TO = @parm_intTO_PKO, @intLINK_KO = @intLINK_PKO
		ELSE
			SELECT @intLINK_TO = @parm_intTO_RKO, @intLINK_KO = @intLINK_RKO

		IF @intLINK_TO IS NULL  OR @intLINK_KO IS NULL
		BEGIN
			FETCH NEXT FROM #REST
				INTO @intREST_ACCT, @cREST_SOUCE, @cREST_ANALIT, @cREST_USER,
					@intREST_EKR, @nREST_SUM
			CONTINUE
		END

		-- ЗАПИСЬ В G_PROV1 --
		SELECT	@strNAME_OPER = NAME_OPER FROM dbo.G_PROV1 WHERE LINK = @intLINK_TO
		SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS) FROM G_PROV1 WHERE LINK_UP = @intLINK_KO), 0) + 1
		
		SET @intLINK_G1 = NULL
		EXEC dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @intLINK_KO, @intLINK_TO, @strNAME_OPER, @intORDERS
		IF @intLINK_G1 IS NULL
		BEGIN
			FETCH NEXT FROM #REST
				INTO @intREST_ACCT, @cREST_SOUCE, @cREST_ANALIT, @cREST_USER,
					@intREST_EKR, @nREST_SUM
			CONTINUE
		END


		-- ЗАПИСЬ G_PROV2 --
		DECLARE #CURSOR_G2 CURSOR STATIC LOCAL
			FOR SELECT LINK, STORNO, [NAME], ORDERS, ECON_OPER
				FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_TO
	
		OPEN #CURSOR_G2
		FETCH NEXT FROM #CURSOR_G2
			INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @strNAME_OPER2 = CASE
							WHEN ISNULL (@strNAME_OPER2, '') = '' THEN ISNULL (@strNAME_OPER, '')
							ELSE @strNAME_OPER2
						END
			SET @nREST_SUM = ABS (@nREST_SUM)
			SET @intLINK_G2 = NULL
			EXEC dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
				@nREST_SUM, 0, @intSTORNO, @strNAME_OPER2, @intECON_OPER, @intORDERS
			IF @intLINK_G2 IS NULL
			BEGIN
				FETCH NEXT FROM #CURSOR_G2
					INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
				CONTINUE
			END

			-- Аналитика в проводках (Дебет) --
			SELECT @intACCOUNT = ACCOUNT,
				@intSGU	= SGU,
				@cSINTH_BY_TO = SA.cSINTH,
				@cANALIT_BY_TO = SA.cANALIT
			FROM dbo.G_PROV_AP GAP
			INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = GAP.ACCOUNT)
			WHERE LINK_UP = @intLINK_G2_TO
				AND DB_KR = 0
			
			IF @cSINTH_BY_TO = '208'
				SET @intACCOUNT = @intREST_ACCT
			ELSE
				SET @intACCOUNT = dbo.BK_GetDBKTAccount (@intREST_ACCT, @cSINTH_BY_TO, @cANALIT_BY_TO, DEFAULT)
	
			IF @intSGU IS NULL 
				EXEC dbo.BA_CORRECT_SGU
					@intSGU	OUTPUT,
					@intACCOUNT,
					0

			EXEC dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 0, @intACCOUNT, @intLINK_KBK, @intREST_EKR, @intDEP_LINK,
				@intLINK_SUB, @intLINK_EMPL, NULL, NULL, @intKAU, @intACC_LINK, 
				NULL, NULL, NULL, NULL, NULL, @intSGU

			-- Аналитика в проводках (Кредит) --
			SELECT @intACCOUNT = ACCOUNT,
				@intSGU	= SGU,
				@cSINTH_BY_TO = SA.cSINTH,
				@cANALIT_BY_TO = SA.cANALIT
			FROM dbo.G_PROV_AP GAP
			INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = GAP.ACCOUNT)
			WHERE LINK_UP = @intLINK_G2_TO
				AND DB_KR = 1

			IF @cSINTH_BY_TO = '208'
				SET @intACCOUNT = @intREST_ACCT
			ELSE
				SET @intACCOUNT = dbo.BK_GetDBKTAccount (@intREST_ACCT, @cSINTH_BY_TO, @cANALIT_BY_TO, DEFAULT)
	
			IF @intSGU IS NULL 
				EXEC dbo.BA_CORRECT_SGU
					@intSGU	OUTPUT,
					@intACCOUNT,
					1

			EXEC dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 1, @intACCOUNT, @intLINK_KBK, @intREST_EKR, @intDEP_LINK,
				@intLINK_SUB, @intLINK_EMPL, NULL, NULL, @intKAU, @intACC_LINK, 
				NULL, NULL, NULL, NULL, NULL, @intSGU
	
			FETCH NEXT FROM #CURSOR_G2
				INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
		END
	
		CLOSE #CURSOR_G2
		DEALLOCATE #CURSOR_G2

		FETCH NEXT FROM #REST
			INTO @intREST_ACCT, @cREST_SOUCE, @cREST_ANALIT, @cREST_USER,
				@intREST_EKR, @nREST_SUM
	END	-- #REST

	CLOSE #REST
	DEALLOCATE #REST

	UPDATE dbo.G_PROV SET SUMMA = ISNULL(dbo.CalcDocSumma(LINK), SUMMA)
	WHERE LINK = @intLINK_PKO

	UPDATE dbo.G_PROV SET SUMMA = ISNULL(dbo.CalcDocSumma(LINK), SUMMA)
	WHERE LINK = @intLINK_RKO
RETURN 0

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].[rn_save_data_from_excel_client]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[rn_save_data_from_excel_client]
GO

/*
c Кейсистемс (Keysystems), 2006
*/
--сохранение данных с excel -клиента
CREATE        PROCEDURE dbo.rn_save_data_from_excel_client
	@tmp_table    varchar(100), --имя временной таблички с данными
    @over         int=0,              --1- перезаписывать отчет , 0 - нет
    @result       varchar(8000) OUTPUT, --результат 
    @bCheckKS     BIT = 0
AS

create table #tmp_data(orders int,crow varchar(8000))
declare @cstr varchar(4000),@version varchar(10),@user varchar(100),@dep_code varchar(100),@code_form varchar(50),@date_form varchar(40),@budg varchar(100),@year int,@period int,@period_num int,@sid varbinary(85),
      @dep_link int,@link_budg int,@uid int ,@link_form int,@ires int,@lsf int,@note as varchar(1000),@begin_date datetime,@dep_name varchar(255),@budg_name varchar(255),@version_form varchar(10),@ver int
DECLARE @iTOrders	tinyint,@iLCol		int,@iCOrders	tinyint,@iCType		tinyint,@iTType		tinyint,@iLCodeCol	int,@isSvod int,@crow varchar(500),@ord INT, @varKSLink_Task INT, @varKSEventStr VARCHAR(8000)
CREATE TABLE #t_Result_ec(TXT varchar(1000), error bit)

set @cstr='insert #tmp_data select orders,data from '+@tmp_table+' drop table '+@tmp_table
--  set @cstr='insert #tmp_data (orders,crow) select orders,data from '+@tmp_table
set @result=''
--print @cstr
execute(@cstr)

Create index #IX_tmp_data on #tmp_data (orders)
--select * from #tmp_data

--найдем версию файла


set @version=''
select @version=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'VERSION=%'
IF @version=''
    begin
        set @result='Неверный заголовок. Не найдена версия файла.'
        return
    end
IF @version not in ('1.2')
    begin
        set @result='Неверный заголовок. Используется Excel-клиент: v'+@version+char(10)+'Необходим Excel-клиент v1.2'
        return
    end

--crc
declare @no_crc varchar(100)
set @no_crc=''
set @cstr=''
select @cstr=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'CRC=%'
IF @cstr<>''
    begin
		--вычислим crc
		--orders,crow
		declare @imin int,@imax int,@crow_crc varchar(8000),@crc int
		set @imin=1 
		set @crc=0
		select @imax=max(orders) from #tmp_data
		while @imin<=@imax
			begin	
				select @crow_crc=rtrim(crow) from #tmp_data where orders=@imin
				IF @crow_crc like 'ROW%'
					begin
						set @crc=dbo.RA_GET_CRC(@crow_crc,@crc)
--						insert ##aaa (txt) select @crow_crc
					end
--				IF @crow_crc not like 'CRC=%'
--					set @crc=dbo.RA_GET_CRC(@crow_crc+char(13)+char(10),@crc)

				set @imin=@imin+1
			end

		if cast(@cstr as integer)<>@crc
			begin
				set @result='Ошибка! Неверная контрольная сумма. Отчет не сохранен. '+ltrim(str(@crc))+'#'+@cstr
				return
			end
    end
else
	set @no_crc='Контрольная сумма в отчете отсутствует.'+char(13)+char(10)


update #tmp_data 
set crow=replace(replace(replace(replace(replace(crow,char(13),''''),char(10),''''),'#plus#','+'),'#C13#',char(13)),'#C10#',char(10)) from #tmp_data

set @period_num=CAST(@cstr as int)


--пользователь
set @user=''
select @user=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'USER=%'
IF @user=''
    begin
        set @result='Неверный заголовок. Не найден логин пользователя.'
        return
    end

set @version_form=''
select @version_form=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'VERSION_FORM=%'

--организация
set @dep_code=''
select @dep_code=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'DEP_CODE=%'
IF @dep_code=''
    begin
        set @result='Неверный заголовок. Не найден код бюджетополучателя.'
        return
    end

--код программы
declare @code_prg varchar(100)
set @code_prg=''
select @code_prg=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'PROGRAM=%'


--код формы
set @code_form=''
select @code_form=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'CODE_FORM=%'
IF @code_form=''
    begin
        set @result='Неверный заголовок. Не найден код формы.'
        return
    end
IF @code_form like '050307[45]%' and @code_prg<>'Свод-КС'
    begin
        set @result='Форма '+@code_form+' не подерживается Excel-клиентом'
        return
    end


--код формы
set @date_form=''
select @date_form=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'DATE_FORM=%'
IF @date_form=''
    begin
        set @result='Неверный заголовок. Не найдена дата формы.'
        return
    end

--линк формы
set @link_form=0


/*SELECT @link_form=[A].[LINK_FORM]
FROM dbo.[REPORT_FORMS] [A]
WHERE [A].[START_DATE] = (SELECT MAX([B].[START_DATE])
                          FROM dbo.[REPORT_FORMS] [B]
                          WHERE [A].[CODE] = [B].[CODE]) and CODE=@code_form
*/

select @link_form=link_form from report_forms where code=rtrim(@code_form) and start_date=convert(datetime,@date_form,104)

IF @link_form=0
    begin
        set @result='Не найдена форма с кодом '+@code_form+' и датой='+@date_form
        return
    end


--бюджет
set @cstr=''
select @cstr=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'BUDG=%'
IF @cstr=''
    begin
        set @result='Неверный заголовок. Не найден бюджет.'
        return
    end
set @budg=@cstr

--год
set @cstr=''
select @cstr=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'YEAR=%'
IF @cstr=''
    begin
        set @result='Неверный заголовок. Не найдена дата отчета.'
        return
    end
set @year=CAST(@cstr as int)

--период
set @cstr=''
select @cstr=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'PERIOD=%'
IF @cstr=''
    begin
        set @result='Неверный заголовок. Не найдена дата отчета.'
        return
    end
set @period=CAST(@cstr as int)


IF (select periodic from report_forms where link_form=@link_form)&@period=0
    begin
        set @result='Форма не может быть сохранена для периода: '+case when @period=1 then 'Год' when @period=2 then 'Квартал' else 'Месяц' end
        return
    end

--год
set @cstr=''
select @cstr=rtrim(dbo.rn_getwordnum(crow,2,'=')) from #tmp_data where crow like 'PERIOD_NUM=%'
IF @cstr=''
    begin
        set @result='Неверный заголовок. Не найдена дата отчета.'
        return
    end
set @period_num=CAST(@cstr as int)


IF @period=1
	set @period_num=1

set @dep_link=0
select @dep_link=link,@dep_name=name from departments where BUDG=@dep_code
if @dep_link=0
    begin
        set @result='Не найдена организация с кодом БП = '+@dep_code
        return
    end

set @link_budg=0
select @link_budg=link,@budg_name=name from BI_DICTION_BUDG_TYPE where OUTCODE=@budg
if @link_budg=0
    begin
		select @link_budg=link,@budg_name=name from BI_DICTION_BUDG_TYPE where CODE=@budg
		if @link_budg=0
			begin
				set @result='Не найден бюджет с кодом ='+@budg
				return	
			end
    end

--проверим есть ли доступ к организации
select @sid=sid,@uid=uid from sysusers where name=@user

if @sid is null 
    begin
        set @result='Не найден SID пользователя: '+@user
        return
    end
--CREATE    FUNCTION dbo.RO_ACCESS_SAVED_FORM (@varKSLSF	int, @WEB bit)


IF not exists(select * from dbo.user_form_access where sid=@sid and dep_link=@dep_link and budg_link=@link_budg and access=1)
 AND IS_MEMBER('db_owner')=0 AND IS_MEMBER('Главный бухгалтер')=0 AND isnull(IS_MEMBER('Начальник отдела кадров'),0)=0 
    begin
        set @result='Пользователь '+@user+' не имеет доступ к организации c КБП='+@dep_code+', Бюджет= '+@budg_name
        return
    end

IF dbo.ReportObjectAccessByLink(@link_form)&2=0
    begin
        set @result='Пользователь '+@user+' не имеет доступ к форме с кодом '+@code_form+' и датой='+@date_form+char(13)+
        'Доступ='+ltrim(str((select dbo.ReportObjectAccessByLink(@link_form))))+' '+(select name from dbo.sysusers where sid=(user_sid()))+' lf='+ltrim(str(@link_form))
        return
    end

--новая форма
if exists(select * from #tmp_data where crow like 'NEW_VERSION=1')
	set @over=0

declare @set_status int
set @set_status=0
if exists(select * from #tmp_data where crow like 'SET_STATUS=1')
	set @set_status=1

IF @dep_code=''
    begin
        set @result='Неверный заголовок. Не найден код бюджетополучателя.'
        return
    end


--Атрибуты 
declare @atr varchar(200),@str_val varchar(250),@catr_val varchar(1000)
set @ord=0
set @catr_val=''
select @ord=orders from #tmp_data where cRow='[ATRIBUTS]'
IF @ord>0
    begin
        set @ord=@ord+1
        select @ord=orders,@crow=crow from #tmp_data where orders=@ord
        while @crow<>'##'
            begin
--                set @atr=dbo.RN_GETWORDNUM(@crow,1,'=')
--                set @str_val=SUBSTRING(@crow,len(@atr)+1,len(@crow))
                set @catr_val=@catr_val+case when @catr_val<>'' then ',' else '' end+ @crow
                set @ord=@ord+1
                select @ord=orders,@crow=crow from #tmp_data where orders=@ord

            end
    end


--проверим, существует ли форма, если нет - создадим ее
set @begin_date=convert(datetime,ltrim(str(@year))+'0101')

SELECT @begin_date = ISNULL(dbo.[RA_GET_BEGIN_DATE](YEAR(@begin_date),@period,@period_num),@begin_date)

IF @version_form<>''
    set @ver=cast(@version_form as int)
else
    set @ver=0

set @lsf=0
if exists(select top 1 * from report_saved_forms where Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg 
	and isRO in (4)
    and isnull(atr_code,'')=isnull(@catr_val,''))
	begin -- нет прав удалить отчеты
		 set @result='Невозможно перезаписать отчет! Отчет имеет статус - Утвержден!'
 		 RETURN 0 
	end
if exists(select top 1 * from report_saved_forms where Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg 
	and isRO in (2)
    and isnull(atr_code,'')=isnull(@catr_val,''))
	begin -- нет прав удалить отчеты
		 set @result='Невозможно перезаписать отчет! Отчет имеет статус - Включен в свод!'
 		 RETURN 0 
	end


    set @lsf=0
    select top 1 @LSF=link_saved_form from report_saved_forms where Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg 
--    and dbo.rn_get_atr_val(link_saved_form,0,1)=@catr_val  order by version desc --=@ver
    and isnull(atr_code,'')=isnull(@catr_val,'')  order by version desc --=@ver

--	delete report_saved_forms
--	where Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 > 0



if @over = 1 -- отчет перезаписываем
begin

if exists(select top 1 * from report_saved_forms where del = 0 and Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg and 
(dbo.RO_ACCESS_SAVED_FORM(Link_saved_form, 1) & 2 = 0 )
-- (dbo.GET_WEB_OBJ_REPORT_ACCESS('',Link_saved_form)<>255) 
--	and version=@ver
--    and dbo.rn_get_atr_val(link_saved_form,0,1)=@catr_val)
    and isnull(atr_code,'')=isnull(@catr_val,''))
	begin -- нет прав удалить отчеты
		 set @result='Невозможно перезаписать отчет! Нет доступа!'
		RETURN 0 
	end
    set @lsf=0
    select top 1 @LSF=link_saved_form from report_saved_forms where del = 0 and Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg 
--    and dbo.rn_get_atr_val(link_saved_form,0,1)=@catr_val  order by version desc --=@ver
    and isnull(atr_code,'')=isnull(@catr_val,'')  order by version desc --=@ver

--	delete report_saved_forms
--	where Link_Form = @link_form and Begin_Date = @begin_date and period_type = @period and period_number = @period_num and Link_Organization = @dep_link and Link_Type_Svod = @link_budg and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 > 0
END
ELSE
	set	@LSF=0


IF @LSF=0 
    begin
        --вычисляем isSvod
        set @isSvod=0
        IF (select top 1 childrens from ro_svod_tree where link_report_org=@dep_link and link_report_budg=@link_budg)=0
            set @isSvod=1
        EXEC @iRes = I_REPORT_SAVE_FORM @LSF output, @link_form, @ver,@begin_date, @period, @period_num, @dep_link, @isSvod, default, default, default, default, 0, @Note, 0, @link_budg,0, 1,0,@catr_val
	end
	else
		begin
			EXEC @iRes = I_REPORT_SAVE_FORM @LSF output, @link_form, @ver,@begin_date, @period, @period_num, @dep_link, 0, default, default, default, default, 0, @Note, 0, @link_budg,0, 1,1,@catr_val
         
         IF EXISTS(SELECT * FROM DBO.[REPORT_SIGN] rs WHERE rs.[lsf] = @LSF) AND ISNULL((SELECT Val_Int FROM dbo.report_options WHERE [Razdel] = 'ECP' AND [Code] = 'ReportReadOnly'), 0) = 1
         BEGIN
	         set @result='Такой отчет уже подписан! Запрещено редактировать отчет с подписью!'
	         RETURN 0 --Ошибка сохранения заголовка формы
         END                               
		end

--select @link_form
if @iRes = 11000 -- возникает только тогда когда стоит настройка
begin
	set @result='Такой отчет уже существует! Запрещено создавать новую версию отчета!'
	RETURN 0 --Ошибка сохранения заголовка формы
end
if @iRes = 11001 
begin
	set @result='Ошибка сохранения документа: Срок действия формы не входит в сохраняемый период.'+
	(select ' Период действия формы: c '+rtrim(convert(varchar(20),start_date,104))+case when end_date is null then '' else ' до '+rtrim(convert(varchar(20),end_date,104)) end from REPORT_FORMS where link_form=@Link_form)
	RETURN 0 --Ошибка сохранения заголовка формы
end



--удаляем данные
select link_col into #tmp_col from report_saved_forms_permissions where lsf=@LSF

-------------- перед затиранием удаляем в корзину
EXEC dbo.RO_RECYCLE_SAVE @LSF

delete report_dinamics where link_sf=@LSF and link_col not in (select link_col from #tmp_col)
delete report_summa where link_saved_form=@LSF and link_col not in (select link_col from #tmp_col)
delete report_string where link_saved_form=@LSF and link_col not in (select link_col from #tmp_col)

--Сохраняем Атрибуты 
set @ord=0
set @catr_val=''
select @ord=orders from #tmp_data where cRow='[ATRIBUTS]'
IF @ord>0
    begin
        set @ord=@ord+1
        select @ord=orders,@crow=crow from #tmp_data where orders=@ord
        while @crow<>'##'
            begin
                set @atr=dbo.RN_GETWORDNUM(@crow,1,'=')
                set @str_val=SUBSTRING(@crow,len(@atr)+2,len(@crow))
                exec RN_SAVE_ATRIBUT_VALUES    @LSF,@atr,@str_val
                set @ord=@ord+1
                select @ord=orders,@crow=crow from #tmp_data where orders=@ord
            end
    end

IF @set_status>0
	begin
		update report_saved_forms
		set IsRO = @set_status
		where link_saved_form=@lsf
	end

set @result=@no_crc+'Отчет '+@code_form+' успешно сохранен. '+char(13)+'Организация:'+RTRIM(@dep_name)+char(13)+'Бюджет:'+RTRIM(@budg_name)+char(13)+'Дата отчета:'+convert(varchar(50),@begin_date,104)+'. Версия: '+ltrim(str((select version from report_saved_forms where link_saved_form=@LSF)))
select @str_val=left(dbo.rn_get_atr_val(@lsf,0,0),250)
IF @str_val<>''
set @result=@result+'  '+char(13)+'Атрибуты:'+@str_val+char(13)

IF @set_status>0
	set @result=@result+'  '+char(13)+'У отчета установлен статус - "Готов к проверке"'+char(13)

print 'данные'
--данные
create table #table (link_table int,orders int,val_type int,link_code_col int)
insert #table (link_table,orders,val_type,link_code_col)
select link_table,orders,val_type,link_code_col from report_tables (nolock) where link_form=@link_form
create table #cols(link_col int,orders int,val_len int,col_type int,property int)


create table #tmp_data_excel (link_col int,link_row int,code_row varchar(50),str_val varchar(250),summa numeric(18,4),del bit)
create table #row_code (link_row int,code varchar(50))
create table #zapret_cells (link_row int,link_col int)
create table #code (code varchar(200))
create table #data (ord int identity (1,1),code varchar(50),link_row int,
col1 varchar(2500),
col2 varchar(2500),
col3 varchar(2500),
col4 varchar(2500),
col5 varchar(2500),
col6 varchar(2500),
col7 varchar(2500),
col8 varchar(2500),
col9 varchar(2500),
col10 varchar(2500),
col11 varchar(2500),
col12 varchar(2500),
col13 varchar(2500),
col14 varchar(2500),
col15 varchar(2500),
col16 varchar(2500),
col17 varchar(2500),
col18 varchar(2500),
col19 varchar(2500),
col20 varchar(2500),
col21 varchar(2500),
col22 varchar(2500),
col23 varchar(2500),
col24 varchar(2500),
col25 varchar(2500),
col26 varchar(2500),
col27 varchar(2500),
col28 varchar(2500),
col29 varchar(2500),
col30 varchar(2500),
col31 varchar(2500),
col32 varchar(2500),
col33 varchar(2500),
col34 varchar(2500),
col35 varchar(2500),
col36 varchar(2500),
col37 varchar(2500),
col38 varchar(2500),
col39 varchar(2500),
col40 varchar(2500),
col41 varchar(2500),
col42 varchar(2500),
col43 varchar(2500),
col44 varchar(2500),
col45 varchar(2500),
col46 varchar(2500),
col47 varchar(2500),
col48 varchar(2500),
col49 varchar(2500),
col50 varchar(2500),
col51 varchar(2500),
col52 varchar(2500),
col53 varchar(2500),
col54 varchar(2500),
col55 varchar(2500),
col56 varchar(2500),
col57 varchar(2500),
col58 varchar(2500),
col59 varchar(2500),
col60 varchar(2500),
col61 varchar(2500),
col62 varchar(2500),
col63 varchar(2500),
col64 varchar(2500),
col65 varchar(2500),
col66 varchar(2500),
col67 varchar(2500),
col68 varchar(2500),
col69 varchar(2500),
col70 varchar(2500))

declare @orders int,@link_table int,@val_type int,@code_col int,@row varchar(8000),@order_data int,@code_orders int,@code varchar(50),@i int,
        @count_col int,@col_str varchar(300),@link_col int,@col_type int,@val_len int,@summa numeric(20,4),@count_row int,@link_row int,@key varchar(5000),@ii int,@key_const varchar(5000),
        @key_add varchar(5000),@cExecIns varchar(8000),@cExecSel varchar(8000),@cRunStr varchar(8000),@max_Row int 
    

set ansi_warnings OFF
SET ARITHABORT OFF
SET ARITHIGNORE OFF

update #tmp_data set crow=REPLACE(REPLACE(crow,'||','| |'),'||','| |')  where crow like 'ROW%' and crow like '%||%'

EXEC dbo.DropTempTable '#REP_HEAD'
CREATE TABLE #REP_HEAD (link_saved_form INT)
INSERT #REP_HEAD([link_saved_form]) VALUES(@lsf)

set @count_row=0
while exists(select * from #table)
    begin
		create table #save_web_form (link_col int,link_row int,code_row varchar(50),str_val varchar(4000),summa numeric(20,4),del bit)

        delete #cols
        delete #data
        select top 1 @orders=orders,@link_table=link_table,@val_type=val_type,@code_col=link_code_col  from #table order by orders
        insert #cols (link_col,orders,val_len,col_type,property) select link_col,orders,val_len,col_type,property from report_coloumns where link_table=@link_table
        select @code_orders=orders from #cols where link_col=@code_col
        select @count_col=count(*) from #cols
        delete #tmp_data_excel
        delete #row_code
        delete #zapret_cells
       
		--для 14 формы своё
		IF @code_form like '0503074%' OR @code_form like '0503075%' 
			set @val_type=1

        --ключевой столбец
        insert #row_code
        SELECT RR.LINK_ROW,RSV.Formula code 
        FROM Report_Rows RR LEFT JOIN 
        	Report_Formula RSV 
        		ON  link_col =@code_col
                AND RSV.link_row=RR.link_row
        where link_table=@link_table

        insert #zapret_cells 
        SELECT RR.LINK_ROW,RSV.link_col 
        FROM Report_Rows RR LEFT JOIN 
        	Report_Formula RSV ON 
                RSV.link_row=RR.link_row
        where formula like'%ЗАПРЕТ(%' and 
         link_table=@link_table

        set @key=''
        exec rn_get_formula_code_row @link_table,'KEY_WEB=',@key output

      --заполняем #data
        set @ii=1
        set @cExecIns='Insert #data ('
        set @cExecSel=' select '
  
       while @ii<=@count_col
            begin
                set @cExecIns=@cExecIns+'COL'+ltrim(str(@ii))+case when @ii<@count_col then ',' else ')' end
                set @cExecSel=@cExecSel+case when @ii=1 then 'replace(' else '' end+               
                'RTRIM(dbo.rn_getwordnum(crow,'+ltrim(str(@ii))+',''|''))'
                +case when @ii=1 then ',''ROW'+ltrim(str(@orders))+'='','''')' else '' end+  
                +case when @ii<@count_col then ',' else '' end
                set @ii=@ii+1
            end        
        set @cExecSel=@cExecSel+ 'from #tmp_data where rtrim(crow) like ''ROW'+ltrim(str(@orders))+'=%'''
        print @cExecIns
        print @cExecSel
        exec(@cExecIns+@cExecSel)

        --для статической таблицы вычислим link_row
        IF @val_type=0 
            begin
                select @cRunStr='UPDATE #DATA SET Link_Row=B.link_row FROM #DATA A LEFT JOIN #row_code B ON A.col'+ltrim(str(@code_orders))+'=B.code'
                select @cRunStr =@cRunStr + ' delete #data where link_row is null'
                PRINT @cRunStr
                exec (@cRunStr)
            end
        --проверка на правильные числа. 
       set @ii=1
       while @ii<=@count_col
            begin
                select @col_type=col_type from #cols where orders=@ii
                IF @col_type=0 --число               
                    begin
                       --символы в числовых колонках
                       select @cRunStr = 'update #DATA SET COL'+ltrim(str(@ii))+'=''0'' WHERE patindex(''%[a-Яa-Z`!@#$%^&*()\?;"]%'',upper(COL'+ltrim(str(@ii))+'))>0'
                       --заменяем , на . 
                       select @cRunStr =@cRunStr + ' update #DATA SET COL'+ltrim(str(@ii))+'=replace(COL'+ltrim(str(@ii))+','','',''.'') where patindex(''%[,]%'',COL'+ltrim(str(@ii))+')>0'
                       select @cRunStr =@cRunStr + ' update #DATA SET COL'+ltrim(str(@ii))+'=replace(COL'+ltrim(str(@ii))+','' '','''') where patindex(''%[ ]%'',COL'+ltrim(str(@ii))+')>0'
                       select @cRunStr =@cRunStr + ' update #DATA SET COL'+ltrim(str(@ii))+'=''0'' where COL'+ltrim(str(@ii))+'='''''
                       print @cRunStr
               		   exec (@cRunStr)

                    end
                set @ii=@ii+1
            END
        --сохраним
        IF @key<>'' and @val_type=1
            begin
        		select @cRunStr = 'update #DATA SET code = '+REPLACE(@key, '#REP_TABLE_1', '#DATA')
				print @cRunStr
        		exec (@cRunStr)
            end
        IF @key='' and @val_type=1
            begin
        		select @cRunStr = 'update #DATA SET code = col'+ltrim(str(@code_orders))
				print @cRunStr
        		exec (@cRunStr)
            end
        set @iTType=@val_type
    	DECLARE col_cursor CURSOR FOR
    	select link_col, orders, col_type from report_coloumns where link_table = @link_table and isEdited=1
    	OPEN col_cursor 
    	FETCH NEXT FROM col_cursor INTO @iLCol, @iCOrders, @iCType


	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @cRunStr=''
		IF @iCType = 0 AND @iTType = 0 -- Стандартный числовой столбец
		BEGIN
--проверим доступ к колонке
			if dbo.RO_AccessColByLink(@iLCol) > 0 and (not exists(select * from #tmp_col where link_col=@iLCol))
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@iLCol) + ', link_row,'''','''',convert(numeric(20,4),col' + ltrim(convert(char(2),@iCOrders)) + '),0 from #DATA'
			else
				set @result=left(@result+'Нет доступа к колонке №'+ltrim(str(@iCOrders))+char(13),8000)
/*
			delete from report_summa 
			where link_saved_form=@LSF and link_col=@iLCol
			SET @cRunStr = 'insert into report_summa (link_saved_form, link_col, link_row, summa) 
        	select ' + convert(varchar(9),@LSF) + ', ' + convert(varchar(9),@ilcol) + ', link_row,convert(numeric(20,4),col' + ltrim(convert(char(2),@iCOrders)) +') summa from #DATA where col' + ltrim(convert(char(2),@iCOrders))+'<>''0'''
*/
		END
  
		IF @iCType = 0 AND @iTType <> 0 -- Динамический числовой столбец
		BEGIN
			if dbo.RO_AccessColByLink(@iLCol) > 0 and (not exists(select * from #tmp_col where link_col=@iLCol))
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@iLCol) + ', 0,code,'''',sum(isnull(convert(numeric(20,4),col' + ltrim(convert(char(2),@iCOrders)) + '),0)),0 from #DATA
				group by code'
			else
				set @result=left(@result+'Нет доступа к колонке №'+ltrim(str(@iCOrders))+char(13),8000)

/*
			delete from report_dinamics
			where link_sf=@LSF and link_col=@iLCol
			SET @cRunStr = 'insert into report_dinamics (link_sf, link_col, code_row, float_val, str_val) 
        	select ' + convert(varchar(9),@LSF) + ', ' + convert(varchar(9),@ilcol) + ',
        	 code, isnull(sum(convert(numeric(20,4),col' + ltrim(convert(char(2),@iCOrders)) + ')),0), '''' from #DATA group by code '--having isnull(sum(convert(numeric(20,4),col' + ltrim(convert(char(2),@iCOrders)) + ')),0)<>0'
*/
		END
		IF @iCType <> 0 AND @iTType = 0 -- Стандартный текстовый столбец
		BEGIN
			if dbo.RO_AccessColByLink(@iLCol) > 0 and (not exists(select * from #tmp_col where link_col=@iLCol))
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@iLCol) + ', link_row, '''',isnull(col' + ltrim(convert(char(2),@iCOrders)) + ',''''),0,0 from #DATA'
			else
				set @result=left(@result+'Нет доступа к колонке №'+ltrim(str(@iCOrders))+char(13),8000)

/*			delete from report_string 
			where link_saved_form=@LSF and link_col=@iLCol
			SET @cRunStr = 'insert into report_string (link_saved_form, link_col, link_row, str_val) 
        	select ' + convert(varchar(9),@LSF) + ', ' + convert(varchar(9),@ilcol) + ', link_row, LEFT(isnull(col' + ltrim(convert(char(2),@iCOrders)) + ', ''''),250) from #DATA'
*/		END
		IF @iCType <> 0 AND @iTType <> 0 -- Динамический текстовый столбец
		BEGIN
			if dbo.RO_AccessColByLink(@iLCol) > 0 and (not exists(select * from #tmp_col where link_col=@iLCol))
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@iLCol) + ', 0, code,isnull(col' + ltrim(convert(char(2),@iCOrders)) + ',''''),0,0 from #DATA'
			else
				set @result=left(@result+'Нет доступа к колонке №'+ltrim(str(@iCOrders))+char(13),8000)


/*			delete from report_dinamics
			where link_sf=@LSF and link_col=@iLCol
			SET @cRunStr = 'insert into report_dinamics (link_sf, link_col, code_row, float_val, str_val) 
        	select ' + convert(varchar(9),@LSF) + ', ' + convert(varchar(9),@ilcol) + ', code, 0, LEFT(max(isnull(col' + ltrim(convert(char(2),@iCOrders)) + ', '''')),250) from #DATA group by code'
*/
		END
		print @cRunStr
		execute(@cRunStr)

		FETCH NEXT FROM col_cursor INTO @iLCol, @iCOrders, @iCType
	END

	CLOSE col_cursor
	DEALLOCATE col_cursor
	IF @code_form like '0503074%' OR @code_form like '0503075%' 
		begin
			insert report_dinamics (link_sf,code_row,link_col,float_val)
			select @LSF,code_row,link_col,summa from #save_web_form
			drop table #save_web_form
		end
	else
   BEGIN
			exec RN_SAVE_SUMMA @LSF,@Link_Table,'#save_web_form',1
		end

    --удаление из данных из запрещенных строк
    IF @val_type=0
        begin
            delete report_summa from report_summa A,#zapret_cells B where A.link_saved_form=@lsf and A.link_row=B.link_row and A.link_col=B.link_col
            delete report_string from  report_summa A,#zapret_cells B where A.link_saved_form=@lsf and A.link_row=B.link_row and A.link_col=B.link_col
        END
  
    -- округление 
    UPDATE A
    SET FLOAT_VAL  = ROUND(FLOAT_VAL,0) 
    FROM REPORT_DINAMICS A 
    INNER JOIN REPORT_COLOUMNS B ON A.Link_Col = B.Link_Col 
    WHERE B.Link_Table = @link_table AND B.Col_Type = 0 AND VAL_LEN = 0 
     AND A.Link_SF = @lsf

    UPDATE A
    SET SUMMA  = ROUND(SUMMA,0) 
    FROM REPORT_SUMMA A 
    INNER JOIN REPORT_COLOUMNS B ON A.Link_Col = B.Link_Col 
    WHERE B.Link_Table = @link_table AND B.Col_Type = 0 AND VAL_LEN = 0 
    AND A.Link_Saved_Form = @lsf


      
		EXEC dbo.[RO_IMPORT_WITH_DICT] @LSF, @orders -- данные подгружаем из справочника

      
   delete #table where orders=@orders        


    --заполним наименования
--    exec rn_fill_with_dict_all @LSF,@link_form,@orders
  end

IF @code_form in ('0503160M','0503360M')
 delete report_dinamics where link_sf=@LSF and str_val=code_row

insert report_sign(sid, lsf, date, sign)
select suser_sid(dbo.rn_getwordnum(crow,1,'==][==')), @LSF, convert(datetime, dbo.rn_getwordnum(crow,3,'==][=='),121) ,dbo.rn_getwordnum(crow,2,'==][==')
from #tmp_data
where orders > (select orders from #tmp_data where crow = 'SIGNATURE=')
	and orders < (select orders from #tmp_data where crow = '=SIGNATURE')

SELECT @result = @result + CHAR(13) + CHAR(10) + TXT
FROM #t_Result_ec
WHERE ERROR = 1 


exec dbo.RN_SPLIT_CODE_ROW @LSF

IF @bCheckKS = 1
BEGIN
   EXEC dbo.RO_CHECK_KS @LSF
END

exec RT_POST_RECEIVE @LSF


		select @varKSLink_Task = link_task from user_info
		select @varKSEventStr = 'для Отчета: ' + rtrim(RF.code) + ' ' + atr + ' Период: ' + 
			convert(char(4),year(BEGIN_DATE)) + ' год ' + 
			case period_Type when 2 then convert(char(1),period_number) + ' квартал'
				when 4 then convert(char(2),period_number) + ' месяц'
			ELSE '' end + ' Версия:' +  convert(char(3),RSF.version) + ' Организация: ' + D.Code + ' Бюджет: ' + B.Name																					
		from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
			left join departments D on D.link = RSF.link_organization 
			left join kl_budg_type B on B.link = RSF.link_type_svod
		where link_saved_form = @LSF

		exec RO_GENERATEEVENT 'Импорт из excel-клиента', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @LSF



--  set @result=@result+char(13)+char(10)+'Число обработанных строк:'+ltrim(str(@count_row))
set ansi_warnings ON
SET ARITHABORT ON
SET ARITHIGNORE ON

RETURN



GO
GRANT ALL ON dbo.[rn_save_data_from_excel_client] 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.[KIR_EXEC_SALARY_ESN_REPORT1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KIR_EXEC_SALARY_ESN_REPORT1]

GO
CREATE PROCEDURE [dbo].[KIR_EXEC_SALARY_ESN_REPORT1]

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

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

AS 
BEGIN

	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT

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

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

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

	DECLARE @WAY TABLE (WAY_CALC TINYINT) 
	INSERT INTO @WAY(WAY_CALC)
	SELECT T4.way_calc
	FROM 
		dbo.DICTIONARY_MROT_TABLE4 t4
	WHERE
		t4.link_minrot = (SELECT TOP 1 link FROM dbo.DICTIONARY_MROT ss WHERE ss.period <= @DATE1 ORDER BY ss.period DESC)
	
	--
	CREATE TABLE #T1 (LINK_VKR INT, MONTH_BASE NUMERIC(18,2), SUMMA_BASE NUMERIC(18,2), DED_M NUMERIC(18,2), INV_M NUMERIC(18,2), SUMMA NUMERIC(18,2), WAY_CALC TINYINT, REF_PHYS_PERS INT, DGH TINYINT)
	
	INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH)
	SELECT 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 0 
	FROM DBO.SA_ESN_VIEW(@Y, @MAX_M, @LINK_DEP, 0) 
	WHERE MONTH_BASE >= @MIN_M
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND LINK_VKR IN (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @nOTBORLINK3))

	--	
	DECLARE @CUR1 CURSOR
	SET @CUR1 = CURSOR FORWARD_ONLY

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

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

		END
	
		FETCH NEXT FROM @CUR1 INTO @Y, @MIN_M, @MAX_M
	END
	
	CLOSE @CUR1
	DEALLOCATE @CUR1

	---Суммы по договорникам
	IF @DGH = 1
		INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH)
		SELECT
			LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN GT.LINK_VKR ELSE 0 END), 
			MONTH(G.[DATE]) AS MONTH_BASE, 
			GT.SUMMA_BASE, 
			DED_M = 0, 
			INV_M = 0, 
			GT.SUMMA, P.WAY_CALC, GT.PERS_LINK, 1
		FROM 
			dbo.SDOC G
			INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
			INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
			INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
		WHERE
			G.[OBJECT] =(SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
			AND GT.[OBJECT] = 3
			AND FLAG_JC = 1
			AND P.[OBJECT] = 3
			AND YEAR(G.[DATE]) = @Y
			AND MONTH(G.[DATE]) BETWEEN @MIN_M AND @MAX_M
			AND LINK_DEP = @LINK_DEP
			AND (@cVAL3 = '' OR @cVAL3 <> '' AND GT.LINK_VKR IN (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @nOTBORLINK3))


	--справочник баз для расчёта отчислений
	CREATE TABLE #BASE_PAYS (WAY_CALC TINYINT, LINK_PAYS INT)
	INSERT INTO #BASE_PAYS (P.WAY_CALC, LINK_PAYS)
	SELECT DISTINCT P.WAY_CALC, R.LINK_PAYS
	FROM 
		dbo.PAYS P INNER JOIN dbo.TAX_REF R ON R.link_tax = P.LINK 
	WHERE
		P.[OBJECT] = 3
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )

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

	--Начисленные суммы по лицам за период
	CREATE TABLE #CALC_OPER (PERS_LINK INT, LINK_PAYS INT, Y INT, M TINYINT, LINK_VKR INT, DGH TINYINT, SUMMA_ALL NUMERIC(18,2))
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL)
	--Сотрудники
	SELECT 
		E.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin), 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 0,
		SUMMA_ALL = SUM(CJ.SUMMA)
	FROM 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	WHERE 	
		Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND LINK_VKR IN (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @nOTBORLINK3))
	GROUP BY
		E.PERS_LINK, cj.LINK_PAYS, period_begin, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)
	
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL)
	--Договорники
	SELECT 
		CJ.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin),
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 1,
		SUMMA_ALL = SUM(CJ.SUMMA)
	FROM 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	WHERE
		@DGH = 1
		AND CJ.PERS_LINK IS NOT NULL
		AND Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND LINK_VKR IN (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @nOTBORLINK3))
	GROUP BY
		CJ.PERS_LINK, cj.LINK_PAYS, period_begin, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)

	-----------
	CREATE TABLE #CALC_OPER_W(PERS_LINK INT, LINK_PAYS INT, Y INT, M INT, LINK_VKR INT, DGH TINYINT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT, WAY_NAME VARCHAR(50))
	INSERT INTO #CALC_OPER_W (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA, WAY_CALC, WAY_NAME)
	SELECT PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL, WC.CODE, WC.NAME
	FROM #CALC_OPER CO INNER JOIN dbo.WAY_CALC WC ON 1=1
	WHERE WC.[TYPE] = 2 --AND WC.CODE <> 5 AND (YEAR(@DATE1)<2010 OR YEAR(@DATE1)>=2010 AND WC.CODE >= 2)
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = WC.CODE )

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

	-----------
	DELETE FROM #CALC_OPER_W
	WHERE 
		DGH = 1 AND EXISTS
			(SELECT * FROM #DGH_FAKT_BASE D 
				WHERE
					D.PERS_LINK = #CALC_OPER_W.PERS_LINK
					AND D.WAY_CALC = #CALC_OPER_W.WAY_CALC
					AND D.LINK_PAY = #CALC_OPER_W.LINK_PAYS
					AND D.Y = #CALC_OPER_W.Y
					AND D.M = #CALC_OPER_W.M
					AND D.LINK_VKR = #CALC_OPER_W.LINK_VKR
			)
	
	----------------------------------------------------------------------------------------
	CREATE TABLE #FACT_SUMMA (LINK_PERS INT, LINK_SFIN INT, SUMMA NUMERIC(18,2), DGH TINYINT)
	INSERT INTO #FACT_SUMMA (LINK_PERS, LINK_SFIN, SUMMA, DGH)
	SELECT PERS_LINK, LINK_VKR, SUMMA_ALL = SUM(SUMMA_ALL), DGH
	FROM 
		#CALC_OPER 
	GROUP BY 
		PERS_LINK, DGH, LINK_VKR

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

	INSERT INTO #PERS (LINK_PERS, LINK_SFIN, DGH)
	SELECT DISTINCT LINK_PERS, LINK_SFIN, DGH
	FROM
	(
		SELECT LINK_PERS = REF_PHYS_PERS, LINK_SFIN = LINK_VKR, DGH FROM #T1
		UNION 
		SELECT LINK_PERS, LINK_SFIN, DGH FROM #FACT_SUMMA
	) T	
	--------------------------------------------------------------

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

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

	--
	DECLARE @LIMIT NUMERIC(18,2)

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

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

	UPDATE #PREDEL
	SET LIMIT = 0
	WHERE LIMIT IS NULL

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

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

	---
	CREATE TABLE #T2 (REF_PHYS_PERS INT, DGH INT, MONTH_BASE TINYINT, WAY_CALC INT, SUMMA_BASE NUMERIC(18,2))
	
	INSERT INTO #T2(REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE)
	SELECT REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE = SUM(SUMMA_BASE) 
	FROM #T1
	GROUP BY REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC

	---	
	--- всвязи с изменениями , переделываем таблицу из статической в динамическую
	SELECT  	
		[LINK_FACE1] = T3.REF_PHYS_PERS,
		T2.DGH,
		LINK_SFIN1 = LINK_VKR,
		[WAY_NAME]  = W.NAME,  
		T2.WAY_CALC,
		SS= SUM(CASE WHEN T2.WAY_CALC = 2 THEN T2.SUMMA_BASE ELSE 0 END),

	 	[PAY] = SUM(T3.SUMMA_BASE),
	 	[DED] = SUM(T3.DED_M),
	 	[INV] = SUM(T3.INV_M),
	 	[LIM] = CONVERT(NUMERIC(18,2), 
	 					MAX(isnull(CONVERT(NUMERIC(20,8),L.SUMMA),0))
	 				*	(CASE WHEN SUM(T2.SUMMA_BASE) > 0 AND SUM(T3.SUMMA_BASE) > 0
	 						THEN SUM(T3.SUMMA_BASE)/ SUM(T2.SUMMA_BASE)
	 						ELSE 0
	 					END)
	 				),
	 	[TAX] = SUM(T3.SUMMA)		
	 	
	INTO #ESN 
	FROM 
		#T2 T2
		INNER JOIN dbo.WAY_CALC W ON W.CODE = T2.WAY_CALC AND W.[TYPE] = 2
		INNER JOIN #T1 T3 ON T2.REF_PHYS_PERS = T3.REF_PHYS_PERS AND T2.DGH = T3.DGH AND T2.MONTH_BASE = T3.MONTH_BASE AND T2.WAY_CALC = T3.WAY_CALC
		LEFT JOIN #SPR_ESN2 L ON L.REF_PHYS_PERS = T3.REF_PHYS_PERS AND T2.DGH = T3.DGH AND L.WAY_CALC = T3.WAY_CALC
	GROUP BY 
		T3.REF_PHYS_PERS, T2.WAY_CALC,  W.NAME  , T2.DGH, T3.LINK_VKR

	---
--<<<<<**********************
	--- переворачиваем поля в таблице 

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

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

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

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

		EXEC (@SQLS1)

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

		EXEC (@SQLS1)

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

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

		EXEC (@SQLS1)				

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

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

	-- приведение к нормальному виду и выборка данных из перевернутой  
	
	DECLARE @SQL NVARCHAR(4000), @ParmDefinition NVARCHAR(500)

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

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

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

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

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

	SET @SQL = @SQL	+ ' ,P.LINK_PERS, p.DGH   , O.LINK_FACE1 , o.DGH '
	
	IF @DETAL_FIO = 1
		/*<code begin>  Шорков И.А. 10.10.2011 добавление в первую страницу поля Возрастная группа , добавление в группировку  */
		SET @SQL = @SQL	+ ' , P.REF_EMPL ,  P.TAB_NUMER, P.NAME_EMPL, P.POL, P.YEAR_B, P.TYPE1/*, O.LINK_FACE1*/  '
		/* <coide end> Шорков И.А.*/
	
	SET @SQL = @SQL
			+ '
		ORDER BY 
			' 
	+ CASE @ORDERBY 
		WHEN 1 THEN 'SUMMA'
		WHEN 2 then ' TNum '
		WHEN 3 then 'FIO'
		ELSE 'NAME_SUB'
	END
	+ CASE WHEN @DETAL_SOURCE = 1 THEN ',F.CODE' ELSE '' END	
	
	PRINT   (@SQL)

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

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


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

	DROP TABLE #T1
	DROP TABLE #PERS_INFO
	DROP TABLE #ESN
	DROP TABLE #FACT_SUMMA
	
	DECLARE @TABLE VARCHAR(100)
	EXEC X_GET_TABLE_NAME @TABLE OUTPUT
	DECLARE @CNT INT
	SELECT @CNT = COUNT(DISTINCT WAY_CALC) FROM #CALC_OPER_W
	
	EXEC M_CROSS_TABLE
		'PERS_LINK, LINK_PAYS, LINK_VKR, Y, M', 
		'WAY_NAME', 'VARCHAR(50)', 
		'SUMMA', 'NUMERIC(20,2)', 'SUM(SUMMA) AS SUMMA',
		'#CALC_OPER_W', @TABLE

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

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

		EXEC (@SQLS)

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

		EXEC (@SQLS)

		SET @I=@I+1
	END			

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








GO


GRANT EXECUTE ON dbo.[KIR_EXEC_SALARY_ESN_REPORT1] TO PUBLIC

GO




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

GO

CREATE PROCEDURE [dbo].SA_SZV4_PACHKA_RASPIL (@link INT, @SPOSOB INT = 2)
AS

DECLARE @PERIOD_BEG DATETIME, @PERIOD_END DATETIME, @DEP_LINK INT, @Y INT, @M TINYINT, @PER TINYINT, @LINK_SELF2 INT, @Y_PREV INT
DECLARE @SUM_UPLATA_DOLGA_STR NUMERIC(18,2), @SUM_UPLATA_DOLGA_NAK NUMERIC(18,2)

SELECT @DEP_LINK = LINK_DEP, @Y = YEAR_BEGIN, @M = MONTH_END, @PER = PER, 
		@PERIOD_BEG = DBO.ConvertDMY2Date(1,1,YEAR_BEGIN), @PERIOD_END = DATE, @LINK_SELF2 = LINK_SELF2, @Y_PREV = YEAR_BEGIN-1,
		@SUM_UPLATA_DOLGA_STR = ISNULL(SUM_UPLATA_DOLGA_STR,0), @SUM_UPLATA_DOLGA_NAK = ISNULL(SUM_UPLATA_DOLGA_NAK,0)
FROM DBO.SZV4_PACHKA 
WHERE LINK = @LINK


DECLARE @PERIOD_END2 DATETIME
SET @PERIOD_END2 = DBO.DATEENDOFMONTH(DBO.ConvertDMY2Date(1,@M,@Y))

---1. Определить, из каких пачек брать сведения о начисленных и перечисленных суммах
CREATE TABLE #PACHKI (LINK INT)
INSERT INTO #PACHKI(LINK)
VALUES(@LINK)

WHILE EXISTS(
			SELECT P.LINK_SELF
			FROM 
				DBO.SZV4_PACHKA P 
				INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF
			WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
				AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
				AND P2.YEAR_BEGIN = @Y AND P2.MONTH_END < @M
			)
BEGIN			

	INSERT INTO #PACHKI(LINK)
	SELECT P.LINK_SELF
	FROM 
		DBO.SZV4_PACHKA P 
		INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF
	WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
		AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
		AND P2.YEAR_BEGIN = @Y AND P2.MONTH_END < @M
END

--- 2.Перечисленные суммы всего по платёжкам текущего отчёта по каждому месяцу
CREATE TABLE #UPLATA_ALL (LINK_UP INT, MON TINYINT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
INSERT INTO #UPLATA_ALL (LINK_UP, MON, SUM_STR, SUM_NAK)
SELECT 
	S.LINK_UP, S.MON, SUM(S.SUM_STR), SUM(S.SUM_NAK) 
FROM
	DBO.SZV4_PLAT S 
WHERE 
	LINK_UP = @LINK
GROUP BY
	S.LINK_UP, S.MON

---3. Определить суммы начисленные и перечисленные по каждому месяцу
CREATE TABLE #PERIOD (M INT, Y INT)

INSERT INTO #PERIOD (M,Y)
SELECT M, Y FROM DBO.months_ex(@PERIOD_BEG, @PERIOD_END2)

--- начисленные и перечисленные суммы из пачек по каждому в разрезе категорий
CREATE TABLE #NACHISL (
	LINK_UP INT, NUM_Q TINYINT, LINK INT,  
	n_sum_str NUMERIC(18,2), n_sum_nak NUMERIC(18,2), 
	p_sum_str NUMERIC(18,2), p_sum_nak NUMERIC(18,2),
	p_sum_str_new NUMERIC(18,2), p_sum_nak_new NUMERIC(18,2))

---	
INSERT INTO #NACHISL (LINK_UP, NUM_Q, LINK, n_sum_str, n_sum_nak, p_sum_str, p_sum_nak)
SELECT 
	link_up, PER, S.LINK, sum_doh, sum_nak, sum_str, sum_dop
FROM 
	#PACHKI P 
	INNER JOIN dbo.SZV4_PACHKA H ON H.LINK = P.LINK
	INNER JOIN dbo.SZV4_SVEDENIA S ON P.LINK = S.LINK_UP

---
CREATE TABLE #QUARTER (NUM_Q TINYINT, MON_BEG TINYINT, MON_END TINYINT)
INSERT INTO #QUARTER (NUM_Q, MON_BEG, MON_END)
SELECT 
	CASE M 
		WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1
		WHEN 4 THEN 2 WHEN 5 THEN 2 WHEN 6 THEN 2
		WHEN 7 THEN 3 WHEN 8 THEN 3 WHEN 9 THEN 3				
		ELSE 4
	END,
	MIN(M), MAX(M) 
FROM DBO.months_ex(@PERIOD_BEG, @PERIOD_END2)
GROUP BY
	(CASE M 
		WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1
		WHEN 4 THEN 2 WHEN 5 THEN 2 WHEN 6 THEN 2
		WHEN 7 THEN 3 WHEN 8 THEN 3 WHEN 9 THEN 3				
		ELSE 4
	END)	

---Перечислено по кварталам
CREATE TABLE #UPLATA_Q (NUM TINYINT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
INSERT INTO #UPLATA_Q (NUM, SUM_STR, SUM_NAK)
SELECT 
	Q.NUM_Q, P_SUM_STR = SUM(P.SUM_STR), P_SUM_NAK = SUM(P.SUM_NAK)
FROM 
	#QUARTER Q
	INNER JOIN #UPLATA_ALL P ON P.MON BETWEEN Q.MON_BEG AND Q.MON_END
GROUP BY
	Q.NUM_Q

---Начислено по кварталам	
CREATE TABLE #NACHISL_Q (NUM TINYINT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
INSERT INTO #NACHISL_Q (NUM, SUM_STR, SUM_NAK)
SELECT 
	N.NUM_Q,
	N_SUM_STR = SUM(N.N_SUM_STR), N_SUM_NAK = SUM(N.N_SUM_NAK)
FROM 
	#NACHISL N
GROUP BY
	N.NUM_Q


DECLARE @UPLATA_STR NUMERIC(18,2), @UPLATA_NAK NUMERIC(18,2)
CREATE TABLE #UPLATA_QY (NUM TINYINT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
DECLARE @Cur1 CURSOR, @NUM TINYINT

IF @SPOSOB = 2
BEGIN
	---В СЛУЧАЕ РАСПРЕДЕЛЕНИЯ СУММЫ, УПЛОЧЕННОЙ С НАЧАЛА ГОДА
	SET @UPLATA_STR = ISNULL((SELECT SUM(SUM_STR) FROM #UPLATA_Q),0)
	SET @UPLATA_NAK = ISNULL((SELECT SUM(SUM_NAK) FROM #UPLATA_Q),0)

	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT NUM_Q FROM #QUARTER ORDER BY NUM_Q

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

			INSERT INTO #UPLATA_QY (NUM, SUM_STR, SUM_NAK)
			SELECT 
				NUM,
				CASE WHEN SUM_STR <= @UPLATA_STR THEN SUM_STR ELSE @UPLATA_STR END,
				CASE WHEN SUM_NAK <= @UPLATA_NAK THEN SUM_NAK ELSE @UPLATA_NAK END
			FROM #NACHISL_Q 
			WHERE NUM = @NUM

			SET @UPLATA_STR = @UPLATA_STR - ISNULL((SELECT SUM(SUM_STR) FROM #UPLATA_QY WHERE NUM = @NUM),0)
			SET @UPLATA_NAK = @UPLATA_NAK - ISNULL((SELECT SUM(SUM_NAK) FROM #UPLATA_QY WHERE NUM = @NUM),0)		
	
		END

		FETCH NEXT FROM @Cur1 INTO @NUM
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1

	DELETE FROM #UPLATA_Q
	INSERT INTO #UPLATA_Q(NUM, SUM_STR, SUM_NAK)
	SELECT NUM, SUM_STR, SUM_NAK FROM #UPLATA_QY
	
END

--IF @SPOSOB = 3
--BEGIN
--	---В СЛУЧАЕ РАСПРЕДЕЛЕНИЯ СУММЫ, ТОЛЬКО ЗА ДАННЫЙ КВАРТАЛ
--	DELETE FROM #UPLATA_Q WHERE NUM <> @PER	
--END		

---
CREATE TABLE #KOEF_UPL (NUM_Q TINYINT, KU_STR NUMERIC(18,16), KU_NAK NUMERIC(18,16))	
INSERT INTO #KOEF_UPL (NUM_Q, KU_STR, KU_NAK)
SELECT 
	Q.NUM, 
	KU_STR = ISNULL(CONVERT(NUMERIC(18,16),
			CASE WHEN (CASE WHEN ISNULL(N.SUM_STR,0) > 0 THEN ISNULL(P.SUM_STR,0) / ISNULL(N.SUM_STR,0) ELSE 0 END) < 1 OR @SPOSOB = 3 THEN
				CASE WHEN ISNULL(N.SUM_STR,0) > 0 THEN ISNULL(P.SUM_STR,0) / ISNULL(N.SUM_STR,0) ELSE 0 END
			ELSE 1 END),0), 
	KU_NAK =ISNULL(CONVERT(NUMERIC(18,16), 
			CASE WHEN (CASE WHEN ISNULL(N.SUM_NAK,0) > 0 THEN ISNULL(P.SUM_NAK,0) / ISNULL(N.SUM_NAK,0) ELSE 0 END) < 1 OR @SPOSOB = 3  THEN
				CASE WHEN ISNULL(N.SUM_NAK,0) > 0 THEN ISNULL(P.SUM_NAK,0) / ISNULL(N.SUM_NAK,0) ELSE 0 END
			ELSE 1 END),0)		
FROM
	(SELECT DISTINCT NUM = NUM_Q FROM #QUARTER) Q
	LEFT JOIN #UPLATA_Q P ON P.NUM = Q.NUM
	LEFT JOIN #NACHISL_Q N ON N.NUM = Q.NUM

IF @SPOSOB = 3
	---В СЛУЧАЕ РАСПРЕДЕЛЕНИЯ СУММЫ, ТОЛЬКО ЗА ДАННЫЙ КВАРТАЛ
	UPDATE #KOEF_UPL SET KU_STR = 1, KU_NAK = 1 WHERE NUM_Q <> @PER	

-- Пересчёт старых уплаченных сумм с учётом коэф. уплаты
UPDATE N SET
	p_sum_str = CASE WHEN @PER = N.NUM_Q THEN 0 ELSE p_sum_str END,
	p_sum_nak = CASE WHEN @PER = N.NUM_Q THEN 0 ELSE p_sum_nak END,
	p_sum_str_new = N_SUM_STR * K.KU_STR, --(CASE WHEN N_SUM_STR > 0 THEN K.KU_STR ELSE 1 END),
	p_sum_nak_new = N_SUM_NAK * K.KU_NAK --(CASE WHEN N_SUM_NAK > 0 THEN K.KU_NAK ELSE 1 END)
FROM
	#NACHISL N
	INNER JOIN #KOEF_UPL K ON N.NUM_Q = K.NUM_Q

--За текущий период проставляются перечисленные суммы
UPDATE SV SET 
	SV.SUM_STR = ISNULL(N.P_SUM_STR_NEW,0),
	SV.SUM_DOP = ISNULL(N.P_SUM_NAK_NEW,0)
FROM 
	SZV4_SVEDENIA SV
	INNER JOIN #NACHISL N ON N.LINK = SV.LINK
WHERE
	SV.LINK_UP = @LINK

--Всего за прошлые перечислено по каждому
CREATE TABLE #UPLATA_PREV (LINK_PERS INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
IF @SPOSOB <> 3 
BEGIN

	INSERT INTO #UPLATA_PREV (LINK_PERS, SUM_STR, SUM_NAK)
	SELECT 
		SV.LINK_PERS, SUM_STR = SUM(P_SUM_STR_NEW - P_SUM_STR), SUM_NAK = SUM(P_SUM_NAK_NEW - P_SUM_NAK)
	FROM 
		dbo.SZV4_SVEDENIA SV
		INNER JOIN #NACHISL N ON N.LINK = SV.LINK
	WHERE
		SV.LINK_UP <> @LINK
	GROUP BY
		SV.LINK_PERS

	UPDATE S SET 
		S.SUM_STR = S.SUM_STR + P.SUM_STR,
		S.SUM_DOP = S.SUM_DOP + P.SUM_NAK
	FROM 
		dbo.SZV4_SVEDENIA S
		INNER JOIN (SELECT LINK_PERS, LINK = MIN(LINK) FROM dbo.SZV4_SVEDENIA WHERE LINK_UP = @LINK GROUP BY LINK_PERS) S1 ON S.LINK_PERS = S1.LINK_PERS AND S.LINK = S1.LINK
		INNER JOIN #UPLATA_PREV P ON P.LINK_PERS = S.LINK_PERS
END		

--Находим суммы переплаты с начала года по сотрудникам
CREATE TABLE #PEREPLATA (LINK_PERS INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
INSERT INTO #PEREPLATA (LINK_PERS, SUM_STR, SUM_NAK)
SELECT 
	LINK_PERS, 
	SUM_STR = CASE WHEN SUM(SUM_STR) - SUM(SUM_DOH) > 0 THEN SUM(SUM_STR) - SUM(SUM_DOH) ELSE 0 END, 
	SUM_NAK = CASE WHEN SUM(SUM_DOP) - SUM(SUM_NAK) > 0 THEN SUM(SUM_DOP) - SUM(SUM_NAK) ELSE 0 END
from
	#PACHKI p
	INNER JOIN dbo.SZV4_SVEDENIA SV ON SV.LINK_UP = P.LINK
	INNER JOIN #NACHISL N ON N.LINK = SV.LINK
GROUP BY
	LINK_PERS
HAVING
	SUM(SUM_STR) - SUM(SUM_DOH) > 0 OR SUM(SUM_DOP) - SUM(SUM_NAK) > 0

--Убираем суммы переплаты
UPDATE SV SET 
	SV.SUM_STR = ISNULL(SV.SUM_STR,0) - ISNULL(P.SUM_STR,0),
	SV.SUM_DOP = ISNULL(SV.SUM_DOP,0) - ISNULL(P.SUM_NAK,0)
FROM 
	SZV4_SVEDENIA SV
	INNER JOIN #PEREPLATA P ON P.LINK_PERS = SV.LINK_PERS
WHERE
	SV.LINK_UP = @LINK	

--Находим суммы недоплаты переплаты с начала года по сотрудникам
CREATE TABLE #NEDOPLATA (LINK_PERS INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
INSERT INTO #NEDOPLATA (LINK_PERS, SUM_STR, SUM_NAK)
SELECT 
	LINK_PERS, 
	SUM_STR = CASE WHEN SUM(SUM_DOH) - SUM(SUM_STR) > 0 THEN SUM(SUM_DOH) - SUM(SUM_STR) ELSE 0 END, 
	SUM_NAK = CASE WHEN SUM(SUM_NAK) - SUM(SUM_DOP) > 0 THEN SUM(SUM_NAK) - SUM(SUM_DOP) ELSE 0 END
from
	#PACHKI p
	INNER JOIN dbo.SZV4_SVEDENIA SV ON SV.LINK_UP = P.LINK
	INNER JOIN #NACHISL N ON N.LINK = SV.LINK
GROUP BY
	LINK_PERS
HAVING
	SUM(SUM_DOH) - SUM(SUM_STR) > 0 OR SUM(SUM_NAK) - SUM(SUM_DOP) > 0
	
--Переплату распределяем остальным
DECLARE @PEREPLATA_SUM_STR NUMERIC(18,2), @PEREPLATA_SUM_NAK NUMERIC(18,2)
DECLARE @NEDOPLATA_SUM_STR NUMERIC(18,2), @NEDOPLATA_SUM_NAK NUMERIC(18,2)
DECLARE @LINK_PERSON INT

SET @PEREPLATA_SUM_STR = ISNULL((SELECT SUM(SUM_STR) FROM #PEREPLATA),0)
SET @PEREPLATA_SUM_NAK = ISNULL((SELECT SUM(SUM_NAK) FROM #PEREPLATA),0)


DECLARE @Cur2 CURSOR

SET @Cur2 = CURSOR FORWARD_ONLY

FOR SELECT DISTINCT LINK_PERS FROM #NEDOPLATA

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

		UPDATE #NEDOPLATA
		SET 
			SUM_STR = CASE WHEN @PEREPLATA_SUM_STR > 0 THEN 
							CASE WHEN SUM_STR > @PEREPLATA_SUM_STR THEN @PEREPLATA_SUM_STR ELSE SUM_STR END
						ELSE 0 END,
			SUM_NAK = CASE WHEN @PEREPLATA_SUM_NAK > 0 THEN 
							CASE WHEN SUM_NAK > @PEREPLATA_SUM_NAK THEN @PEREPLATA_SUM_NAK ELSE SUM_NAK END
						ELSE 0 END
		WHERE
			LINK_PERS = @LINK_PERSON
			
		SET @PEREPLATA_SUM_STR = @PEREPLATA_SUM_STR - ISNULL((SELECT SUM(SUM_STR) FROM #NEDOPLATA WHERE LINK_PERS = @LINK_PERSON),0)
		SET @PEREPLATA_SUM_NAK = @PEREPLATA_SUM_NAK - ISNULL((SELECT SUM(SUM_NAK) FROM #NEDOPLATA WHERE LINK_PERS = @LINK_PERSON),0)			

	END

	FETCH NEXT FROM @Cur2 INTO @LINK_PERSON
END

CLOSE @Cur2
DEALLOCATE @Cur2

--Убираем суммы недоплаты
UPDATE SV SET 
	SV.SUM_STR = ISNULL(SV.SUM_STR,0) + ISNULL(N.SUM_STR,0),
	SV.SUM_DOP = ISNULL(SV.SUM_DOP,0) + ISNULL(N.SUM_NAK,0)
FROM 
	SZV4_SVEDENIA SV
	INNER JOIN #NEDOPLATA N ON N.LINK_PERS = SV.LINK_PERS
WHERE
	SV.LINK_UP = @LINK
	
/*РАСПРЕДЕЛЕНИЕ КОПЕЕК, РАЗНИЦА НА КОТОРЫЕ ВОЗНИКЛА В СЛЕДСТВИИ ОКРУГЛЕНИЯ*/
DECLARE @KOP_STR_PERSON NUMERIC(18,2), @KOP_NAK_PERSON NUMERIC(18,2)
--Уплоченные суммы по физлицам
SELECT @KOP_STR_PERSON = SUM(SUM_STR), @KOP_NAK_PERSON = SUM(SUM_DOP)
FROM 
	SZV4_SVEDENIA SV
	INNER JOIN #PACHKI P ON P.LINK = SV.LINK_UP
--Уплоченные суммы из сведений о платежах	
DECLARE @KOP_STR NUMERIC(18,2), @KOP_NAK NUMERIC(18,2), @LINK_SV INT
SELECT @KOP_STR = SUM(SUM_STR), @KOP_NAK = SUM(SUM_NAK)
FROM #UPLATA_ALL

SET @KOP_STR = ISNULL(@KOP_STR,0) - ISNULL(@KOP_STR_PERSON,0) -- ошибки округления
SET @KOP_NAK = ISNULL(@KOP_NAK,0) - ISNULL(@KOP_NAK_PERSON,0) -- ошибки округления


--Отдельно страховая
SET @LINK_SV = 
		( SELECT TOP 1 SV.LINK
			FROM SZV4_SVEDENIA SV
			WHERE SV.LINK_UP = @LINK 
					AND (
							ISNULL(SUM_DOH,0) > ISNULL(SUM_STR,0) AND ISNULL(SUM_DOH,0) - ISNULL(SUM_STR,0) > @KOP_STR 
						)
		)				

IF ISNULL(@LINK_SV,0) > 0
	UPDATE SZV4_SVEDENIA SET 
		SUM_STR = ISNULL(SUM_STR,0) + @KOP_STR
	WHERE LINK = @LINK_SV

--Отдельно накопительная
SET @LINK_SV = 
		( SELECT TOP 1 SV.LINK
			FROM SZV4_SVEDENIA SV
			WHERE SV.LINK_UP = @LINK 
					AND (
							ISNULL(SUM_NAK,0) > ISNULL(SUM_DOP,0) AND ISNULL(SUM_NAK,0) - ISNULL(SUM_DOP,0) > @KOP_STR
						)
		)				

IF ISNULL(@LINK_SV,0) > 0
	UPDATE SZV4_SVEDENIA SET 
		SUM_DOP = ISNULL(SUM_DOP,0) + @KOP_NAK
	WHERE LINK = @LINK_SV	


IF ISNULL(@LINK_SELF2,0) > 0 BEGIN
	
	--Расчёт остатка долга за прошлый год по физлицам

	--1. Остаток долга на начало текущего года			
	CREATE TABLE #DOLG_PREV_YEAR (
		LINK_PERS INT, 
		FIO VARCHAR(100), 
		BIRTH DATETIME, 
		INSUR_NUM VARCHAR(14), 
		AGE_TYPE TINYINT, 
		SUM_STR NUMERIC(18,2), 
		SUM_STR_P NUMERIC(18,2), 
		SUM_NAK NUMERIC(18,2), 
		SUM_NAK_P NUMERIC(18,2)
	)
	
	INSERT INTO #DOLG_PREV_YEAR(LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, SUM_STR, SUM_STR_P, SUM_NAK, SUM_NAK_P)
	EXECUTE [dbo].[SA_PF_REPORT] @Y_PREV, 12, @LINK_SELF2

	--2. Уплата долга в текущем году за прошлый год
	INSERT INTO #DOLG_PREV_YEAR(LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, SUM_STR_P, SUM_NAK_P)
	EXECUTE [dbo].[SA_PF_REPORT2] @Y_PREV, 12, @LINK
	
	DECLARE @SUM_STR NUMERIC(18,2), @SUM_NAK NUMERIC(18,2)
	
	SET @SUM_STR= ISNULL((SELECT SUM(SUM_STR) FROM #DOLG_PREV_YEAR),0) - ISNULL((SELECT SUM(SUM_STR_P) FROM #DOLG_PREV_YEAR),0)
	SET @SUM_NAK= ISNULL((SELECT SUM(SUM_NAK) FROM #DOLG_PREV_YEAR),0) - ISNULL((SELECT SUM(SUM_NAK_P) FROM #DOLG_PREV_YEAR),0)

	DECLARE @LINK_OZOI INT, @PeriodBegin DATETIME, @PeriodEnd DATETIME, @MONTH_BEG INT, @MONTH_END INT
	SET @LINK_OZOI = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 3 AND @Y BETWEEN YBEG AND YEND),1)
	SET @MONTH_END = @M 

	IF @Y > 2010
	BEGIN
		SET @MONTH_BEG = (CASE @PER WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 WHEN 4 THEN 10 END)
		SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)
	END
	
	SELECT @PeriodBegin = dbo.ConvertDMY2Date(1,@MONTH_BEG,@Y), @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH_END,@Y))

	------	у кого была инвалидность в заданном периоде
	SELECT PERS_LINK, DATE_BEGIN = MIN(ISNULL(I.DATE_BEGIN,@PeriodBegin)), DATE_END = MAX(ISNULL(I.DATE_END,@PeriodEnd))
	INTO #PERS_INV
	FROM dbo.PERS_INVALID I
	WHERE ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin
	GROUP BY PERS_LINK	


	CREATE TABLE #DOLG_PREV(
		LINK_PERS INT, 
		LINK_KATEG INT,
		FIO VARCHAR(100), 
		BIRTH DATETIME, 
		INSUR_NUM VARCHAR(14), 
		AGE_TYPE TINYINT, 
		SUM_STR NUMERIC(18,2), 
		SUM_STR_P NUMERIC(18,2), 
		SUM_NAK NUMERIC(18,2), 
		SUM_NAK_P NUMERIC(18,2)
		)

	INSERT INTO #DOLG_PREV(LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, SUM_STR, SUM_NAK, LINK_KATEG)
	SELECT
		LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, 
		DOLG_STR = SUM(ISNULL(SUM_STR,0)- ISNULL(SUM_STR_P,0)), 
		DOLG_NAK = SUM(ISNULL(SUM_NAK,0) - ISNULL(SUM_NAK_P,0)),
		LINK_KATEG = (CASE WHEN EXISTS (SELECT * FROM #PERS_INV I WHERE I.PERS_LINK = D.LINK_PERS AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin) THEN @LINK_OZOI ELSE 1 END)
	FROM
		#DOLG_PREV_YEAR D
	GROUP BY
		LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE
	HAVING
		SUM(ISNULL(SUM_STR,0)- ISNULL(SUM_STR_P,0)) <> 0
		OR
		SUM(ISNULL(SUM_NAK,0) - ISNULL(SUM_NAK_P,0)) <> 0

	DROP TABLE #DOLG_PREV_YEAR

	--Добавить новые записи
	INSERT INTO [dbo].[SZV4_SVEDENIA] (
		[LINK_UP], [PACHKA], [ORDERS], [FORMA],
		[LINK_PERS], [SUM_DOH], [SUM_STR], [SUM_NAK], [SUM_DOP],
		[DPER_VN_M], [DPER_VN_D], [DPER_OZ_M], [DPER_OZ_D], [ISUM_STR], [ISUM_NAK], 
		[LINK_KATEG], [SUM_DOLG_STR], [SUM_UPLATA_DOLGA_STR], [SUM_DOLG_NAK], [SUM_UPLATA_DOLGA_NAK])
	SELECT 
		@LINK, PACHKA =0, ORDERS =0, forma =2, D.LINK_PERS, SUM_DOH =0, SUM_STR =0, SUM_NAK =0, SUM_DOP =0,
		DPER_VN_M =0, DPER_VN_D =0, DPER_OZ_M =0, DPER_OZ_D =0, ISUM_STR =0, ISUM_NAK =0, 
		LINK_KATEG,
		SUM_DOLG_STR = d.sum_str, SUM_UPLATA_DOLGA_STR =0, SUM_DOLG_NAK = d.sum_str, SUM_UPLATA_DOLGA_NAK =0 
	FROM 
		#DOLG_PREV D
	WHERE
		NOT EXISTS (
		SELECT *
		FROM
			dbo.SZV4_PACHKA P
			INNER JOIN dbo.SZV4_svedenia S ON S.LINK_UP = P.LINK
		WHERE
			P.LINK = @LINK
			AND
			S.LINK_PERS = D.LINK_PERS 	
		) 
	
	IF @@ROWCOUNT > 0	
		exec dbo.SZV4_NUMERATOR @LINK	

	--Обновить долги в старых
	UPDATE S SET
		S.SUM_DOLG_STR = D.SUM_STR, S.SUM_DOLG_NAK = D.SUM_NAK
	FROM 
		dbo.SZV4_PACHKA P
		INNER JOIN dbo.SZV4_svedenia S ON S.LINK_UP = P.LINK
		INNER JOIN #DOLG_PREV D ON S.LINK_PERS = D.LINK_PERS AND S.LINK_KATEG = D.LINK_KATEG
	WHERE
		P.LINK = @LINK

	--Распределить уплату долга пропорционально сумме долга
	IF @SUM_UPLATA_DOLGA_STR <> 0 OR @SUM_UPLATA_DOLGA_NAK <> 0
	BEGIN
		
		DECLARE @SUM_UPLATA_DOLGA_STR_PERS NUMERIC(18,2), @SUM_UPLATA_DOLGA_NAK_PERS NUMERIC(18,2)
		SELECT @SUM_UPLATA_DOLGA_STR_PERS = SUM(SUM_STR), @SUM_UPLATA_DOLGA_NAK_PERS = SUM(SUM_NAK) FROM #DOLG_PREV
		SELECT @SUM_UPLATA_DOLGA_STR_PERS = ISNULL(@SUM_UPLATA_DOLGA_STR_PERS,0), @SUM_UPLATA_DOLGA_NAK_PERS = ISNULL(@SUM_UPLATA_DOLGA_NAK_PERS,0) 

		IF @SUM_UPLATA_DOLGA_STR_PERS <> 0 OR @SUM_UPLATA_DOLGA_NAK_PERS <> 0
			UPDATE S SET
				S.SUM_UPLATA_DOLGA_STR = (CASE WHEN @SUM_UPLATA_DOLGA_STR_PERS <> 0 THEN @SUM_UPLATA_DOLGA_STR * S.SUM_DOLG_STR / @SUM_UPLATA_DOLGA_STR_PERS ELSE 0 END), 
				S.SUM_UPLATA_DOLGA_NAK = (CASE WHEN @SUM_UPLATA_DOLGA_NAK_PERS <> 0 THEN @SUM_UPLATA_DOLGA_NAK * S.SUM_DOLG_NAK / @SUM_UPLATA_DOLGA_NAK_PERS ELSE 0 END)
			FROM 
				dbo.SZV4_PACHKA P
				INNER JOIN dbo.SZV4_svedenia S ON S.LINK_UP = P.LINK
			WHERE
				P.LINK = @LINK

	END --IF @SUM_UPLATA_DOLGA_STR <> 0 OR @SUM_UPLATA_DOLGA_NAK <> 0	

END


UPDATE DBO.SZV4_PACHKA SET PROVERKA = 0
WHERE LINK = @LINK	

DROP TABLE #PACHKI
DROP TABLE #UPLATA_ALL
DROP TABLE #PERIOD
DROP TABLE #NACHISL
DROP TABLE #QUARTER
DROP TABLE #UPLATA_Q
DROP TABLE #NACHISL_Q
DROP TABLE #KOEF_UPL
DROP TABLE #UPLATA_PREV	
	
RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_RASPIL] TO PUBLIC

GO

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




/*
	Процедура формирования скелет для любой таблицы
	на вход: код формы и номер таблицы
	на выходе: курсор для данной таблицы с заданным количеством колонок
	Курсор берется на основании справочника, который подключен к ключевому столбцу
*/


CREATE     PROCEDURE dbo.RO_CALC_SKELET
	@CodeForm char(20)='', -- код формы
	@OrderTable tinyint=0, -- порядковый номер таблицы
	@start_date datetime=null,
	@link_table int=null,
	@table_name varchar(100)='',
	@LSF int=0,
	@For_excel_klient int=0
AS

declare @LF int, @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), @DictWhere VARCHAR(254),
	@ExecStr varchar(8000), @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @col_type tinyint, @orders_col tinyint,@ExecStrTmp varchar(8000),@cstrWeb varchar(8000),@cstrWebInto varchar(8000),@Upd_mask varchar(50),@max_Col int, @split varchar(1000)

select @LF = Link_Form from report_forms where Code = @CodeForm and Start_Date = (select max(Start_Date) from report_forms where Code = @CodeForm)


select @LF = Link_Form from report_forms where Code = @CodeForm and Start_Date = case when @start_date is null then 
(select max(Start_Date) from report_forms where Code = @CodeForm) else @start_date end



if @LF is NULL and @link_table is null
begin
	IF @table_name=''
		return -1
	else
	begin
			set @ExecStr='select * from '+@table_name+' order by orders,code'
			execute(@ExecStr)
	end
end
IF @link_table is not null
	begin
		select @LC = Link_Code_Col, @LT = Link_Table from report_tables where link_table=@link_table
		IF OBJECT_ID('tempdb..#REPORT_DINAMICS') IS NULL select * into #report_dinamics from report_dinamics where 1=0
		IF OBJECT_ID('tempdb..##TMP_SKELET_RGB') IS NOT NULL drop table ##TMP_SKELET_RGB
	end
else
	select @LC = Link_Code_Col, @LT = Link_Table from report_tables where orders = @OrderTable and Link_Form = @LF


		select @max_col=count(*)
		from report_coloumns RC
		where Link_Table = @LT 
		set @upd_mask=replicate('0',@max_col)

if @LC is NULL
begin
	IF @table_name=''
		return -2
	else
	begin
			set @ExecStr='select * from '+@table_name+' order by orders,code'
			execute(@ExecStr)
	end
end

select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List), @DictWhere = RTRIM(ISNULL([Dictionary_Where],''))
  from report_coloumns where Link_Col = @LC

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] = @LSF

IF not exists(select * from dbo.report_saved_forms where link_saved_form = @LSF)
BEGIN
   IF (SELECT code FROM dbo.report_forms WHERE [Link_Form] = @LF) LIKE '%G%'
      SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', '0'), '%link_budg%', '0'), '%date%', '''' + CONVERT(VARCHAR(10),  DATEADD(MONTH, -3, GETDATE()+10), 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  


if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
begin
	IF @table_name=''
		return 0
	else
	begin
			set @ExecStr='select * from '+@table_name+' order by orders,code'
			execute(@ExecStr)
	end
end

create table #t_ColDict (orders tinyint)
create table #t_Col (orders tinyint, Col_Type tinyint,val_len int, order_split int)

set @Cols = ''
set @Field =''
set @Fields = ''
set @Col = ''

set @ExecStr = ''
set @cstrWeb=''
set @cstrWebInto=''

set @ExecStrTmp = ''

exec dbo.rn_get_formula_code_row @LT, 'SPLIT=', @split output

while @DictField <> '' and @DictCol <> ''
begin
	exec dbo.RO_FORMULA_FUNCTIONS 1, @DictField output, @Field output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @DictCol output, @Col output, ','
	set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
	if @i = @OrderCol
	begin
		set @CodeCol = @Col    -- ключевой столбец
		set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
	end
	if CHARINDEX(RTRIM(@Col) + '=', @split) = 0
	begin
		set @ExecStr = @ExecStr + ',
	[' + @Col + ']='+@Field

		set @upd_mask=STUFF(@upd_mask,@i,1,'1')

		set @cstrWebInto=@cstrWebInto+','+@Col

		insert #t_ColDict (orders)
			values(@i)
	end
end


set @cstrWeb='CODE'+@ExecStr
set @cstrWebInto='CODE'+@cstrWebInto	
IF OBJECT_ID('tempdb..#REPORT_DINAMICS') IS NOT NULL
		begin		
			select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List) from report_coloumns where Link_Col = @LC
			while @DictField <> '' and @DictCol <> ''
			begin
				exec dbo.RO_FORMULA_FUNCTIONS 1, @DictField output, @Field output, ','
				exec dbo.RO_FORMULA_FUNCTIONS 1, @DictCol output, @Col output, ','
				set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
				select @LinkCol=link_col from report_coloumns where link_table=@LT and orders=@i
				set @ExecStrTmp = 'insert #REPORT_DINAMICS (link_sf,link_col,str_val,code_row,float_val) 
				select '+str(@lsf)+' as link_sf,'+str(@linkCol)+' as link_col, max('+@Field+') as str_val, '+@FieldCol+' as code_row,0 as float_val from '+@Dict + CASE WHEN @DictWhere = '' THEN '' ELSE ' where ' + @DictWhere END + ' group by '+@FieldCol 
				print @ExecStrTmp
				execute(@ExecStrTmp)
			end
		end


set @ExecStr = 'select [CODE] = ' + @FieldCol + @ExecStr


declare @val_len int
set @split = isnull(REPLACE(REPLACE(REPLACE(@split, '#', ','), 'Code_Row', @FieldCol),' ',''),'')
if @split <> ''
begin
	set @ExecStr = @ExecStr + ',' + @split
	set @cstrWeb = @cstrWeb + ',' + @split
end

insert #t_Col (orders, Col_Type,val_len, order_split)
	select orders, col_type,val_len, case when CHARINDEX('COL' + LTRIM(RTRIM(STR(orders))), @split) = 0 then 10000 + orders else CHARINDEX('COL' + LTRIM(RTRIM(STR(orders))), @split) end
	from report_coloumns RC
	where Link_Table = @LT and not exists(select top 1 * from #t_ColDict CD where CD.orders = RC.orders)  -- чтобы не было повторяющихся колонок



while exists(select top 1 * from #t_Col)
begin
	select top 1 @orders_col = orders, @col_type = col_type,@val_len=val_len  from #t_Col order by order_split
	if CHARINDEX('COL' + LTRIM(RTRIM(STR(@orders_col))) + '=', @split) = 0
	begin
		if @col_type = 0
		begin
			set @ExecStr = @ExecStr + ',
		[COL'+LTRIM(STR(@orders_col)) + ']=cast(0 as numeric(20,'+ltrim(str(@val_len))+'))'
			set @cstrWeb=@cstrWeb+',cast(0 as numeric(20,'+ltrim(str(@val_len))+'))'
			set @cstrWebInto=@cstrWebInto+',COL'+LTRIM(STR(@orders_col))
		end
		else begin
			set @ExecStr = @ExecStr + ',
		[COL'+LTRIM(STR(@orders_col)) + ']=cast('''' as varchar('+ltrim(str(@val_len))+'))'
			set @cstrWeb=@cstrWeb+',cast('''' as varchar('+ltrim(str(@val_len))+'))'
			set @cstrWebInto=@cstrWebInto+',COL'+LTRIM(STR(@orders_col))
		end
	end
	else begin
		set @upd_mask=STUFF(@upd_mask,@orders_col,1,'1')
		set @cstrWebInto = @cstrWebInto +',COL'+LTRIM(STR(@orders_col))
	end
	delete #t_Col where orders = @orders_col
end
declare @key varchar(1000),@iTType int,@iLCodeCol int,@cRunStr varchar(8000),@cDopExec varchar(8000)

IF @table_name=''
	begin
		set @ExecStr = @ExecStr + '
		from ' + @Dict +  CASE WHEN @DictWhere = '' THEN '' ELSE ' where ' + @DictWhere END +' order by code'
		print @ExecStr
		execute(@ExecStr)
	end
	else
	begin
		IF @for_excel_klient=1
		begin
			set @ExecStr = @ExecStr + '
			,0 as orders  into '+@table_name+' from ' + @Dict +  CASE WHEN @DictWhere = '' THEN '' ELSE ' where ' + @DictWhere END +' order by code'
			execute(@ExecStr)
			print @ExecStr
			RETURN 

		end


		delete #t_col
		insert #t_Col (orders, Col_Type)
		select orders, col_type
		from report_coloumns RC
		where Link_Table = @LT 

		set @cDopExec=''
		while exists(select top 1 * from #t_Col)
			begin
				select top 1 @orders_col = orders, @col_type = col_type from #t_Col
				set @cDopExec = @cDopExec + ',RGB'+LTRIM(STR(@orders_col)) +' DOP_COL'+LTRIM(STR(@orders_col))  
				set @cstrWebInto=@cstrWebInto+','+' DOP_COL'+LTRIM(STR(@orders_col))  
				delete #t_Col where orders = @orders_col
			end

		exec rn_get_formula_code_row @link_table,'KEY_WEB=',@key output
		select @iTType = val_type, @iLCodeCol = Link_Code_Col from report_tables where Link_Table = @link_table
		IF @iTType <> 0
			BEGIN
				select @cRunStr = 'update '+@table_name+ ' SET code = isnull(col' + rtrim(convert(varchar(10),orders)) + ','''')'
				from report_coloumns where link_col = @iLCodeCol
				exec (@cRunStr)
--				select @cRunStr
			END

		IF @key<>''
			BEGIN
			   select @cRunStr = 'update '+@table_name + ' SET code = '+@key
            IF OBJECT_ID('tempdb..#REP_HEAD') IS NULL
            BEGIN
               CREATE TABLE #REP_HEAD (link_saved_form INT)
				   exec (@cRunStr)
               DROP TABLE #REP_HEAD
            END 
            ELSE BEGIN
				   exec (@cRunStr)
            END             
		    end
			exec RO_TOTAL_CELLS       @link_table,@LSF,'RGB',2,1,'#REPORT_DINAMICS','##TMP_SKELET_RGB',default,1
			set @ExecStr = '
			insert '+@table_name+'(orders,upd_cells_mask,checked,upd,del,'+@cstrWebInto+')
			select 0,'''+@upd_mask+''',0,0,0,'+@cstrWeb+@cDopExec+' from ' + @Dict+' A,##TMP_SKELET_RGB C'+
			' where A.'+@FieldCol+'=C.cod '  +  CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END + ' 
			and not exists(select * from '+@table_name+' B where B.code=A.code and B.del=0)'+
			' order by code 
			select * from '+@table_name+' order by orders,code drop table '+@table_name

			print @ExecStr
--			print len(@ExecStr)
			execute(@ExecStr)
	end

	IF OBJECT_ID('tempdb..##TMP_SKELET_RGB') IS NOT NULL drop table ##TMP_SKELET_RGB
GO
GRANT ALL ON dbo.[RO_CALC_SKELET] 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.[BK_UPDATE_KL_COUNTRY]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_UPDATE_KL_COUNTRY]

GO
CREATE PROCEDURE dbo.BK_UPDATE_KL_COUNTRY
	(@intLINK	INT OUTPUT,
	@CODE1		VARCHAR(5),
	@CODE2		VARCHAR(5),
	@CODE3		VARCHAR(5),
	@NAME		VARCHAR(254),
	@FULL_NAME	VARCHAR(254))
AS
BEGIN
	Declare
		@varKSERROR	int,
		@varKSRowCount	int,
		@varKStrancount	int,
		@varKSObjectLink int,
		@varKSEventText	varchar (254)

	IF ISNULL (@CODE1, '') = '' OR ISNULL (@NAME, '') = ''
		RETURN 5
		
	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	IF ISNULL (@intLINK, 0) = 0
	BEGIN
		INSERT INTO dbo.KL_COUNTRY
			(CODE1,
			CODE2,	
			CODE3,
			[NAME],
			FULL_NAME)
		VALUES (@CODE1,
			@CODE2,
			@CODE3,
			@NAME,
			@FULL_NAME)

		SELECT @varKSERROR = @@ERROR,
			@intLINK = SCOPE_IDENTITY ()
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE dbo.KL_COUNTRY
		SET CODE1 = @CODE1,
			CODE2 = @CODE2,
			CODE3 = @CODE3,
			[NAME] = @NAME,
			FULL_NAME = @FULL_NAME
		WHERE LINK = @intLINK
		SELECT @varKSERROR = @@ERROR,
			@varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

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



GO


GRANT EXECUTE ON dbo.[BK_UPDATE_KL_COUNTRY] TO PUBLIC

GO


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


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

GO

CREATE procedure dbo.SA_UPDATE_NORM_HOURS 
/*
Конвертирование времени из формата часы.доли часов в формат часы.минуты и обратно в зависимости от настройки TABEL_OPT10
*/
as

DECLARE @MINUTE TINYINT
SET @MINUTE = COALESCE(dbo.sa_get_option_by_code('TABEL_OPT10'),1)

	UPDATE dbo.GRAPH_VID_TABLE
	SET HOURS = dbo.minutes_to_num(dbo.num_to_minutes(HOURS,(@MINUTE+1)%2),@MINUTE)

	UPDATE dbo.GRAPHIC_DAYS
	SET HOURS = dbo.minutes_to_num(dbo.num_to_minutes(HOURS,(@MINUTE+1)%2),@MINUTE)

	UPDATE [GR]
	SET hour_norm = GD.HR
	from 
		dbo.GRAPHICS GR INNER JOIN 
		(Select LINK_UP, HR = dbo.minutes_to_num(sum(dbo.num_to_minutes(HOURS,@MINUTE)),@MINUTE) from dbo.GRAPHIC_DAYS GROUP BY LINK_UP) GD ON GR.LINK = GD.LINK_UP


	UPDATE dbo.TABELS_W
	SET 
		D1 = dbo.minutes_to_num(dbo.num_to_minutes(D1,(@MINUTE+1)%2),@MINUTE),
		D2 = dbo.minutes_to_num(dbo.num_to_minutes(D2,(@MINUTE+1)%2),@MINUTE),
		D3 = dbo.minutes_to_num(dbo.num_to_minutes(D3,(@MINUTE+1)%2),@MINUTE),
		D4 = dbo.minutes_to_num(dbo.num_to_minutes(D4,(@MINUTE+1)%2),@MINUTE),
		D5 = dbo.minutes_to_num(dbo.num_to_minutes(D5,(@MINUTE+1)%2),@MINUTE),
		D6 = dbo.minutes_to_num(dbo.num_to_minutes(D6,(@MINUTE+1)%2),@MINUTE),
		D7 = dbo.minutes_to_num(dbo.num_to_minutes(D7,(@MINUTE+1)%2),@MINUTE),
		D8 = dbo.minutes_to_num(dbo.num_to_minutes(D8,(@MINUTE+1)%2),@MINUTE),
		D9 = dbo.minutes_to_num(dbo.num_to_minutes(D9,(@MINUTE+1)%2),@MINUTE),
		D10 = dbo.minutes_to_num(dbo.num_to_minutes(D10,(@MINUTE+1)%2),@MINUTE),
		D11 = dbo.minutes_to_num(dbo.num_to_minutes(D11,(@MINUTE+1)%2),@MINUTE),
		D12 = dbo.minutes_to_num(dbo.num_to_minutes(D12,(@MINUTE+1)%2),@MINUTE),
		D13 = dbo.minutes_to_num(dbo.num_to_minutes(D13,(@MINUTE+1)%2),@MINUTE),
		D14 = dbo.minutes_to_num(dbo.num_to_minutes(D14,(@MINUTE+1)%2),@MINUTE),
		D15 = dbo.minutes_to_num(dbo.num_to_minutes(D15,(@MINUTE+1)%2),@MINUTE),
		D16 = dbo.minutes_to_num(dbo.num_to_minutes(D16,(@MINUTE+1)%2),@MINUTE),
		D17 = dbo.minutes_to_num(dbo.num_to_minutes(D17,(@MINUTE+1)%2),@MINUTE),
		D18 = dbo.minutes_to_num(dbo.num_to_minutes(D18,(@MINUTE+1)%2),@MINUTE),
		D19 = dbo.minutes_to_num(dbo.num_to_minutes(D19,(@MINUTE+1)%2),@MINUTE),
		D20 = dbo.minutes_to_num(dbo.num_to_minutes(D20,(@MINUTE+1)%2),@MINUTE),
		D21 = dbo.minutes_to_num(dbo.num_to_minutes(D21,(@MINUTE+1)%2),@MINUTE),
		D22 = dbo.minutes_to_num(dbo.num_to_minutes(D22,(@MINUTE+1)%2),@MINUTE),
		D23 = dbo.minutes_to_num(dbo.num_to_minutes(D23,(@MINUTE+1)%2),@MINUTE),
		D24 = dbo.minutes_to_num(dbo.num_to_minutes(D24,(@MINUTE+1)%2),@MINUTE),
		D25 = dbo.minutes_to_num(dbo.num_to_minutes(D25,(@MINUTE+1)%2),@MINUTE),
		D26 = dbo.minutes_to_num(dbo.num_to_minutes(D26,(@MINUTE+1)%2),@MINUTE),
		D27 = dbo.minutes_to_num(dbo.num_to_minutes(D27,(@MINUTE+1)%2),@MINUTE),
		D28 = dbo.minutes_to_num(dbo.num_to_minutes(D28,(@MINUTE+1)%2),@MINUTE),
		D29 = dbo.minutes_to_num(dbo.num_to_minutes(D29,(@MINUTE+1)%2),@MINUTE),
		D30 = dbo.minutes_to_num(dbo.num_to_minutes(D30,(@MINUTE+1)%2),@MINUTE),
		D31 = dbo.minutes_to_num(dbo.num_to_minutes(D31,(@MINUTE+1)%2),@MINUTE)

RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_UPDATE_NORM_HOURS] TO PUBLIC

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

	c Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE dbo.[RB_CALC_FORM_0503127G09]
	@LSF		INT,
	@tTable	   TINYINT  = 2,
	@dCALC_DATE	DATETIME = NULL,
	@iDEP_LINK	INT      = NULL
AS
-- exec xa_watchi 'vovan', @iDEP_LINK
-- exec xa_watchd

DECLARE @liOwnDepLink INT,
		@ldEnd        DATETIME,
		@ldBegin      DATETIME,
		@liYear       INT,
		@lbIS_RBS     BIT,
		@lbKBK_FILTER     BIT,
		@varKSaccount50301	INT,
		@ADM_CODE	CHAR(3),
		@cFInSource	CHAR(1)



select @liOwnDepLink = Link_Organization, @dCALC_DATE = Begin_Date, @liYear = YEAR(Begin_Date)
from dbo.REPORT_SAVED_FORMS
where Link_Saved_Form = @LSF

SELECT @ldEnd = @dCALC_DATE + 1,
@ldBegin = LTRIM(RTRIM(STR(@liYear))) + '0101',
@lbIS_RBS = dbo.[FB_GetDepIS_RBS](@liOwnDepLink, DEFAULT)

SET @ADM_CODE = Null
IF @liOwnDepLink is not null
	SELECT @ADM_CODE = LEFT(LTRIM(dbo.rn_get_atr_value(@LSF, 'REPORTS_ATR_ADM')),3)

IF @ADM_CODE = '' OR @ADM_CODE = '000'
	SET @ADM_CODE = Null

SET @cFInSource = Null
SELECT @cFInSource = LEFT(LTRIM(dbo.rn_get_atr_value(@LSF, 'REPORTS_ATR_VIDDEYAT')),1)
IF @cFInSource = ''
	SET @cFInSource = '1'

IF @cFInSource = '0'
	SET @cFInSource = NULL


SELECT TOP 1 @varKSaccount50301 = Link From S_ACCOUNTS WHere cSource = '1' and cSinth = '503' and cAnalit = '01' ORDER BY cUser

DECLARE @tabCOL5 TABLE ([KBK]    INT,
[EKR]    INT,
[SUMMA5] FLOAT)

DECLARE @tabCOL6 TABLE ([KBK]    INT,
[EKR]    INT,
[SUMMA6] FLOAT)

DECLARE @tabCOL7 TABLE ([KBK]    INT,
[EKR]    INT,
[SUMMA7] FLOAT)

DECLARE @tabCOL8 TABLE ([KBK]    INT,
[EKR]    INT,
[SUMMA8] FLOAT)


IF EXISTS(Select LINK FROM rn_get_filter(@LSF,'REPORTS_FILTER_KBK'))
	set @lbKBK_FILTER = 1
else
	set @lbKBK_FILTER = 0

DECLARE @AdmFilter table (LINK int)
insert into @AdmFilter
Select LINK FROM rn_get_filter(@LSF,'REPORTS_FILTER_KBK')


IF @tTable = 1
BEGIN
-- 010
	declare @tabCOL4 table (	KBK		int,
								EKR		int,
								SUMMA4	float)

	-- Графа 4
		INSERT @tabCOL4
		SELECT	KBK = FT.VKR,
				EKR = FT.EKR,
				SUMMA4 = ISNULL(SUM(FT.SUMMA), 0)
		FROM G_PROV G
		inner join FINANSE_PLAN_SUMM FT on FT.LINK_UP = G.LINK
		inner join S_OBJECTS SO on G.OBJECT = SO.LINK and SO.CODE = 'FB_NAZN_127D'
		where DATE_PROV <= @dCALC_DATE and YEAR(DATE_PROV) = @liYear 
				and	G.DEP = @liOwnDepLink
				AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = FT.VKR))
				AND (@lbKBK_FILTER=0 OR (FT.VKR is not NULL AND FT.VKR IN (Select LINK FROM @AdmFilter)))
		group by FT.VKR, FT.EKR

-- Графа 5.
	EXEC dbo.[BufferClear] 'BUDJ_DOH_LS'
	
	INSERT dbo.BUFFER(LINK, ID)
	SELECT LINK, 'BUDJ_DOH_LS' FROM dbo.S_ACCOUNTS WHERE (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) AND cSinth = '210' AND cAnalit = '02'

	INSERT @tabCOL5	
	SELECT	[KBK],
			[EKR],
			[SUMMA5] = ISNULL(SUM([D_SUMMA]), 0) - ISNULL(SUM([K_SUMMA]), 0)
	FROM	dbo.[ARestTableByDateAccounts](@ldEnd, 'BUDJ_DOH_LS')
	WHERE	[DEP_LINK] = @liOwnDepLink AND
			[SGU] IN (SELECT [LINK] FROM dbo.[KOSGU] WHERE CODE IN ('110','120','130','140','151','152','153','160','180','410','420','430','440'))
			AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = [KBK]))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY [KBK], [EKR]

	EXEC dbo.[BufferClear] 'BUDJ_DOH_LS'


-- Графа 6.
	EXEC dbo.[BufferClear] 'BUDJ_DOH_2010[1,7]'
	
	INSERT dbo.BUFFER(LINK, ID)
	SELECT	LINK, 'BUDJ_DOH_2010[1,7]' FROM dbo.S_ACCOUNTS WHERE (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) AND cSinth = '201' AND (cAnalit = '21' OR cAnalit = '23' OR cAnalit = '27' ) AND ZABALANS = 0

	INSERT @tabCOL6
	SELECT [KBK], [EKR], [SUMMA6] = SUM(D_SUMMA)
	FROM dbo.ARestPackedOborotByAccounts(@ldBegin, @dCALC_DATE, 'BUDJ_DOH_2010[1,7]')
	WHERE	[DEP_LINK] = @liOwnDepLink AND
			[SGU] IN (SELECT [LINK] FROM dbo.[KOSGU] WHERE DB_KR = 0)
			AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = [KBK]))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY [KBK], [EKR]

	EXEC dbo.[BufferClear] 'BUDJ_DOH_2010[1,7]'

-- Графа 7.
/*	EXEC dbo.[BufferClear] 'BUDJ_DOH_20103'
	
	INSERT dbo.BUFFER(LINK, ID)
	SELECT	LINK, 'BUDJ_DOH_20103' FROM dbo.S_ACCOUNTS WHERE (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) AND cSinth = '201' AND cAnalit = '03' AND ZABALANS = 0

	INSERT @tabCOL7
	SELECT [KBK], [EKR], [SUMMA7] = SUM(D_SUMMA)
	FROM dbo.ARestPackedOborotByAccounts(@ldBegin, @dCALC_DATE, 'BUDJ_DOH_20103')
	WHERE [DEP_LINK] = @liOwnDepLink
			AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = [KBK]))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY [KBK], [EKR]

	EXEC dbo.[BufferClear] 'BUDJ_DOH_20103'
*/

-- Сборка

	SELECT SUBSTRING(ISNULL(REPLACE(RTRIM([K].[CODE]), '.', ''), REPLICATE('0',17)),4,250) + ISNULL([S].[CODE], '000'),
			ISNULL([D].[NAME], ' '),
			'010',
			SUBSTRING(ISNULL(REPLACE(RTRIM([K].[CODE]), '.', ''), REPLICATE('0',17)),4,250) + ISNULL([S].[CODE], '000'),
			ISNULL([SUMMA4], 0),
			ISNULL([SUMMA5], 0),
			ISNULL([SUMMA6], 0),
			ISNULL([SUMMA7], 0),
				  ISNULL([SUMMA5], 0) + ISNULL([SUMMA6], 0) + ISNULL([SUMMA7], 0) ,
			0
	FROM (select KBK, EKR from @tabCOL4 where SUMMA4 <> 0 union
		  select KBK, EKR from @tabCOL5 where SUMMA5 <> 0 union
		  select KBK, EKR from @tabCOL6 where SUMMA6 <> 0 union
		  select KBK, EKR from @tabCOL7 where SUMMA7 <> 0) T
	LEFT JOIN @tabCOL4        [C4] ON T.KBK = C4.KBK AND T.EKR = C4.EKR
	LEFT JOIN @tabCOL5        [C5] ON T.KBK = C5.KBK AND T.EKR = C5.EKR
	LEFT JOIN @tabCOL6        [C6] ON T.KBK = C6.KBK AND T.EKR = C6.EKR
	LEFT JOIN @tabCOL7        [C7] ON T.KBK = C7.KBK AND T.EKR = C7.EKR

	LEFT JOIN dbo.[KL_KBK]    [K] ON T.KBK = K.LINK		-- COALESCE(A.KBK, B.KBK, E.KBK) = K.LINK
	LEFT JOIN dbo.[KL_KBK_KD] [C] ON T.KBK = C.LINK_KBK	-- COALESCE(A.KBK, B.KBK, E.KBK) = C.LINK_KBK
	LEFT JOIN dbo.[KL_KD]     [D] ON [D].[LINK] = [C].[LINK_KD]
	LEFT JOIN dbo.[KOSGU]     [S] ON T.EKR = S.LINK		-- COALESCE([A].[EKR], [B].[EKR], [E].[EKR]) = [S].[LINK]
	ORDER BY SUBSTRING(ISNULL(REPLACE(RTRIM([K].[CODE]), '.', ''), REPLICATE('0',17)),4,250) + ISNULL([S].[CODE], '000')


END

IF @tTable = 2
BEGIN

-- Графa 4
	DECLARE @tabCOL4R TABLE ([KBK]    INT,
							[EKR]    INT,
							[SUMMA4] FLOAT)

	INSERT @tabCOL4R
	SELECT	R.VKR,
			R.EKR,
			SUM(R.P1)
	FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_ASSIGN',11,'1',1) R
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC and DA.LINK_UP = @iDEP_LINK 
	left join dbo.KL_KBK KBK on KBK.LINK = R.VKR
	WHERE (@ADM_CODE IS Null OR @ADM_CODE is not null and @ADM_CODE = LEFT(LTRIM(KBK.CODE),3)) and
		@lbKBK_FILTER=0 OR R.VKR is not NULL AND R.VKR IN (Select LINK FROM @AdmFilter)
	GROUP BY R.VKR, R.EKR 
	
	INSERT @tabCOL4R
	SELECT	R.VKR,
			R.EKR,
			SUM(R.P1)
	FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_ASSIGN_SVOD',11,'1',2) R
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC and DA.LINK_UP = @iDEP_LINK 
	left join dbo.KL_KBK KBK on KBK.LINK = R.VKR
	left join @tabCOL4R T on T.KBK = R.VKR and T.EKR = R.EKR
	WHERE (@ADM_CODE IS Null OR @ADM_CODE is not null and @ADM_CODE = LEFT(LTRIM(KBK.CODE),3)) and
		(@lbKBK_FILTER=0 OR R.VKR is not NULL AND R.VKR IN (Select LINK FROM @AdmFilter)) and
		T.KBK is null and T.EKR is null 
	GROUP BY R.VKR, R.EKR 


	

-- Графa 5
	DECLARE @tabCOL5R TABLE ([KBK]    INT,
							[EKR]    INT,
							[SUMMA5] FLOAT)

	INSERT @tabCOL5R
	SELECT	R.VKR,
			R.EKR,
			SUM(R.P1)
	FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_LIMIT',11,'1',1) R
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC and DA.LINK_UP = @iDEP_LINK
	left join dbo.KL_KBK KBK on KBK.LINK = R.VKR
	WHERE (@ADM_CODE IS Null OR @ADM_CODE is not null and @ADM_CODE = LEFT(LTRIM(KBK.CODE),3)) and
		@lbKBK_FILTER=0 OR R.VKR is not NULL AND R.VKR IN (Select LINK FROM @AdmFilter)
	GROUP BY R.VKR, R.EKR 

	/*INSERT @tabCOL245
	select * from(
	SELECT	[COL1] = ISNULL(A.VKR, B.VKR),
			[COL2] = ISNULL(A.EKR, B.EKR),
			[COL4] = ISNULL(SUM(A.P1), 0),
			[COL5] = ISNULL(SUM(B.P1), 0)
	FROM (SELECT S.VKR, S.EKR, P1 = SUM(S.P1) FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_ASSIGN',11,'1',1) S
			inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = S.DEP_ACC and DA.LINK_UP = @iDEP_LINK GROUP BY VKR, EKR) as A
	FULL JOIN (SELECT S.VKR, S.EKR, P1 = SUM(S.P1) FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_LIMIT',11,'1',1	) S
			inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = S.DEP_ACC and DA.LINK_UP = @iDEP_LINK  GROUP BY VKR, EKR) as B
		 ON A.VKR = B.VKR AND A.EKR = B.EKR
	WHERE @ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = ISNULL(A.VKR, B.VKR))
	GROUP BY ISNULL(A.VKR, B.VKR), ISNULL(A.EKR, B.EKR)) S 
	where	(@lbKBK_FILTER=0 OR S.COL1 is not NULL AND S.COL1 IN (Select LINK FROM @AdmFilter))	
*/
	-- Графа 6.
	EXEC dbo.[BufferClear] 'BUDJ_RASH_LSP'
	EXEC dbo.[BufferClear] 'BUDJ_RASH_LSM'
	EXEC dbo.[BufferClear] 'BUDJ_RASH_not30405'
	
	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'BUDJ_RASH_LSP' FROM dbo.S_ACCOUNTS WHERE ZABALANS = 0  AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null)  AND cSinth = '304' AND cAnalit = '05' -- CODE LIKE '1.304.05%'
	
	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'BUDJ_RASH_LSM' FROM dbo.S_ACCOUNTS WHERE ZABALANS = 0  AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null)  AND cSinth = '210' AND cAnalit = '02' -- CODE LIKE '1.210.02%'

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'BUDJ_RASH_not30405' FROM dbo.S_ACCOUNTS WHERE ZABALANS = 0  AND (cSinth <> '304' OR cAnalit <> '04')
/*
Расчет 304.05 по оборотам с исключением корреспонденций с счетом 304.04 по дебету С и по кредиту С2
*/
	DECLARE @tCOL6Temp TABLE ([KBK]    INT,
				  [EKR]    INT,
				  [SUMMA] FLOAT)
	INSERT @tCOL6Temp
	SELECT	A.KT_VKR,A.KT_SGU,ISNULL(A.SUMMA, 0)
	FROM dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'BUDJ_RASH_not30405', 'BUDJ_RASH_LSP') A
	WHERE A.DEP_LINK = @liOwnDepLink AND A.KT_SGU IN (SELECT LINK FROM dbo.[KOSGU] WHERE CODE IN ('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'))
	
	INSERT @tCOL6Temp
	SELECT	A2.DT_VKR,A2.DT_SGU,- ISNULL(A2.SUMMA, 0)
	FROM dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'BUDJ_RASH_LSP', 'BUDJ_RASH_not30405') A2
	WHERE A2.DEP_LINK = @liOwnDepLink AND A2.DT_SGU IN (SELECT LINK FROM dbo.[KOSGU] WHERE CODE IN ('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'))

	INSERT @tCOL6Temp
	SELECT	B.KBK, B.SGU, ISNULL(B.K_SUMMA, 0) - ISNULL(B.D_SUMMA, 0)
	FROM dbo.ARestTableByDateAccounts(@ldEnd, 'BUDJ_RASH_LSM') B
	WHERE B.DEP_LINK = @liOwnDepLink AND B.SGU IN (SELECT LINK FROM dbo.KOSGU WHERE CODE = '640')
	
	INSERT @tabCOL6
	SELECT	T.KBK, T.EKR, SUM(ISNULL(T.SUMMA, 0))
	FROM @tCOL6Temp T
	WHERE (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = T.KBK))
				AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY KBK, EKR



	EXEC dbo.[BufferClear] 'BUDJ_RASH_LSP'
	EXEC dbo.[BufferClear] 'BUDJ_RASH_LSM'
	EXEC dbo.[BufferClear] 'BUDJ_RASH_not30405'
	
-- Графа 7.
	EXEC dbo.[BufferClear] 'BUDJ_DOH_2010[1,7]'
	
	INSERT dbo.BUFFER(LINK, ID)
	SELECT	LINK, 'BUDJ_DOH_2010[1,7]' FROM dbo.S_ACCOUNTS WHERE (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null)  AND cSinth = '201' AND (cAnalit = '21' OR cAnalit = '23' OR cAnalit = '27' ) AND ZABALANS = 0

	INSERT @tabCOL7
	SELECT [KBK], [EKR], [SUMMA7] = SUM(K_SUMMA)
	FROM dbo.ARestPackedOborotByAccounts(@ldBegin, @dCALC_DATE, 'BUDJ_DOH_2010[1,7]')
	WHERE [DEP_LINK] = @liOwnDepLink
		  AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = [KBK]))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY [KBK], [EKR]

	EXEC dbo.[BufferClear] 'BUDJ_DOH_2010[1,7]'

-- Графа 8.
/*	EXEC dbo.[BufferClear] 'BUDJ_DOH_20103'
	
	INSERT dbo.BUFFER(LINK, ID)
	SELECT	LINK, 'BUDJ_DOH_20103' FROM dbo.S_ACCOUNTS WHERE (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) AND cSinth = '201' AND cAnalit = '03' AND ZABALANS = 0

	INSERT @tabCOL8
	SELECT [KBK], [EKR], [SUMMA8] = SUM(K_SUMMA)
	FROM dbo.ARestPackedOborotByAccounts(@ldBegin, @dCALC_DATE, 'BUDJ_DOH_20103')
	WHERE [DEP_LINK] = @liOwnDepLink
			AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = [KBK]))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY [KBK], [EKR]

	EXEC dbo.[BufferClear] 'BUDJ_DOH_20103'
*/

	-- Сборка.
	DECLARE @tabReturn2 TABLE ([CODE]  VARCHAR(250),
[COL1]  VARCHAR(250),
[COL2]  VARCHAR(250),

[COL3]  VARCHAR(4),
[COL4]  VARCHAR(7),
[COL5]  VARCHAR(3),
[COL6]  VARCHAR(3),

[COL7]  FLOAT,
[COL8]  FLOAT,
[COL9]  FLOAT,
[COL10] FLOAT,
[COL11] FLOAT,
[COL12] FLOAT,
[COL13] FLOAT,
[COL14] FLOAT,
[COL15] VARCHAR(250))

	INSERT @tabReturn2
	SELECT	SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),4,254) + ISNULL([S].[CODE],'000'),
		ISNULL([S].[NAME],''),
		'200',

--		SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),4,254) + ISNULL([S].[CODE],'000'),
		SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),5,4),  -- РЗПР
		SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),10,7), -- ЦСР
		SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),18,3), -- ВР
		ISNULL([S].[CODE],'000'), -- ЭКР

		ISNULL(SUMMA4, 0),
		ISNULL(SUMMA5, 0),
		ISNULL(SUMMA6, 0),
		ISNULL(SUMMA7, 0),
		ISNULL(SUMMA8, 0),
		ISNULL(SUMMA6, 0) + ISNULL(SUMMA7, 0) + ISNULL(SUMMA8, 0),
		ISNULL(SUMMA4, 0) - (ISNULL(SUMMA6, 0) + ISNULL(SUMMA7, 0) + ISNULL(SUMMA8, 0)),
		ISNULL(SUMMA5, 0) - (ISNULL(SUMMA6, 0) + ISNULL(SUMMA7, 0) + ISNULL(SUMMA8, 0)),
		SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),4,254) + ISNULL([S].[CODE],'000')

	FROM (select KBK, EKR from @tabCOL4R where SUMMA4 <> 0 union
		  select KBK, EKR from @tabCOL5R where SUMMA5 <> 0 union
		  select KBK, EKR from @tabCOL6 where SUMMA6 <> 0 union
		  select KBK, EKR from @tabCOL7 where SUMMA7 <> 0  union
		  select KBK, EKR from @tabCOL8 where SUMMA8 <> 0 ) T	
	INNER JOIN dbo.[KL_KBK] [K] ON T.KBK = [K].[LINK] and K.[TYPE] = 1
			
	LEFT JOIN @tabCOL4R A ON T.KBK = A.KBK AND T.EKR = A.EKR
	LEFT JOIN @tabCOL5R L ON T.KBK = L.KBK AND T.EKR = L.EKR
	LEFT JOIN @tabCOL6 B ON T.KBK = B.KBK AND T.EKR = B.EKR
	LEFT JOIN @tabCOL7 C ON T.KBK = C.KBK AND T.EKR = C.EKR
	LEFT JOIN @tabCOL8 D ON T.KBK = D.KBK AND T.EKR = D.EKR
	LEFT JOIN dbo.[KOSGU]  [S] ON T.EKR = [S].[LINK]
	ORDER BY SUBSTRING(ISNULL(RTRIM(REPLACE([K].[CODE],'.','')),REPLICATE('0',17)),4,254) + ISNULL([S].[CODE],'000')
	

	SELECT * from @tabReturn2
	
END

IF @tTable = 3
	BEGIN
	declare @tICOL4 table (	CODE_STR	char(3),
							KBK		int,
							SGU		int,
							SUMMA	float)

	-- Графа 4
	--Ассигнования
	INSERT @tICOL4
	SELECT  CODE_STR = '520',
			KBK		 = S.VKR, 
			SGU		 = S.EKR, 
			SUMMA4	 = SUM(S.P1) 
	FROM dbo.FB_REST_FINANS(@liYear,@dCALC_DATE,1,1,0,'FINANS_ASSIGN',11,'1',1) S
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = S.DEP_ACC and DA.LINK_UP = @liOwnDepLink  
	GROUP BY VKR, EKR

	INSERT @tICOL4
	SELECT	CODE_STR= '520',
			KBK		= FT.VKR,
			SGU		= FT.EKR,
			SUMMA4	= ISNULL(SUM(FT.SUMMA), 0)
	FROM G_PROV G
	inner join FINANSE_PLAN_SUMM FT on FT.LINK_UP = G.LINK
	inner join S_OBJECTS SO on G.OBJECT = SO.LINK and SO.CODE = 'FB_NAZN_127I'
	left join @tICOL4 T on T.KBK = FT.VKR and T.SGU = FT.EKR
	where DATE_PROV is not null and DATE_PROV <= @dCALC_DATE and YEAR(DATE_PROV) = @liYear 
			and	G.DEP = @liOwnDepLink
			AND (@ADM_CODE IS Null OR @ADM_CODE = (SELECT TOP 1 LEFT(LTRIM(CODE),3) FROM KL_KBK WHERE LINK = FT.VKR))
		AND (@lbKBK_FILTER=0 OR (FT.VKR is not NULL AND FT.VKR IN (Select LINK FROM @AdmFilter)))
	and T.KBK is null and T.SGU is null
	group by FT.VKR, FT.EKR
	
	
	EXEC dbo.[BufferClear] 'IST_121002'
	EXEC dbo.[BufferClear] 'IST_130405'
	EXEC dbo.[BufferClear] 'IST_NOT_130404'
	EXEC dbo.[BufferClear] 'IST_12010[1,7]'
	EXEC dbo.[BufferClear] 'IST_120103'
	EXEC dbo.[BufferClear] 'IST_130404'

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_130405'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0  AND cSinth = '304' AND cAnalit = '05' AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_121002'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0  AND cSinth = '210' AND cAnalit = '02' AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_NOT_130404'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0  AND NOT (cSinth = '304' and cAnalit = '04') AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_12010[1,7]'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0 AND cSinth = '201' AND (cAnalit = '21' or cAnalit = '23' or cAnalit = '27') AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_120103'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0 AND cSinth = '201' AND cAnalit = '03' AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	INSERT dbo.BUFFER(LINK, [ID])
	SELECT [LINK], 'IST_130404'
	FROM dbo.S_ACCOUNTS
	WHERE ZABALANS = 0  AND cSinth = '304' and cAnalit = '04' AND (cSource = @cFInSource and @cFInSource is not null or @cFInSource is null) 

	-- Графа 5.
	DECLARE @tICOL5 TABLE ( CODE_STR	char(3),
				KBK 		INT,
				SGU 		INT,
				SUMMA 	FLOAT)

	
	--срока 520	
	INSERT @tICOL5
	SELECT	[CODE_STR] ='520',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_121002', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR, KT_SGU, - SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_121002')) S
	--inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('171', '410', '430', '620', '630', '650', '710', '720')
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU
	
	--срока 520	
	INSERT @tICOL5
	SELECT	[CODE_STR] = '520',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_130405', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR, KT_SGU, - SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_130405')) S
	--inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('310', '330', '520', '530', '550', '810', '820')
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU


	--срока 811	
	INSERT @tICOL5
	SELECT	[CODE_STR] = '811',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_121002', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_121002')) S
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	WHERE S.DEP_LINK = @liOwnDepLink
	
	--срока 812	
	INSERT @tICOL5
	SELECT	[CODE_STR] = '812',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_130405', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_130405')) S
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	WHERE S.DEP_LINK = @liOwnDepLink

	-- Графа 6.
	DECLARE @tICOL6 TABLE (CODE_STR char(3),
				   		   KBK 		INT,
						   SGU 		INT,
						   SUMMA 	FLOAT)

	--срока 520	
	INSERT @tICOL6
	SELECT	[CODE_STR] = '520',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_12010[1,7]', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU as SGU, - SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_12010[1,7]')) S
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (KBK.TYPE = 4 OR KBK.TYPE = 8) and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--срока 710	
	INSERT @tICOL6
	SELECT	[CODE_STR] = '710',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_12010[1,7]', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU as SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_12010[1,7]')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE = '510'
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--срока 720	
	INSERT @tICOL6
	SELECT	[CODE_STR] = '720',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, KT_VKR AS KBK, KT_SGU as SGU, SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_12010[1,7]') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU as SGU, - SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_12010[1,7]', 'IST_NOT_130404')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE = '610'
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--срока 812	
/*	INSERT @tICOL6
	SELECT	[CODE_STR] = '812',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_130405', 'IST_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_130404', 'IST_130405')) S
	--inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.DB_KR = 1
	WHERE S.DEP_LINK = @liOwnDepLink*/

	--срока 821	
	INSERT @tICOL6
	SELECT	[CODE_STR] = '821',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR as KBK, DT_SGU as SGU, SUMMA  from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_12010[1,7]', 'IST_NOT_130404')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('510')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	WHERE S.DEP_LINK = @liOwnDepLink

	--срока 822	
	INSERT @tICOL6
	SELECT	[CODE_STR] = '822',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR as KBK, DT_SGU as SGU, SUMMA  from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_12010[1,7]', 'IST_NOT_130404')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('610')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))


	-- Графа 7.
	DECLARE @tICOL7 TABLE (CODE_STR 	char(3),
				   KBK 	INT,
						   SGU 	INT,
						   SUMMA 	FLOAT)


	--срока 520	
	INSERT @tICOL7
	SELECT	[CODE_STR] = '520',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_120103', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU as SGU, - SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_120103')) S
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--срока 710	
	INSERT @tICOL7
	SELECT	[CODE_STR] = '710',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_120103', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_120103')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('510')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--срока 720	
	INSERT @tICOL7
	SELECT	[CODE_STR] = '720',
		[KBK] = S.KBK,
		[SGU] = S.SGU,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR AS KBK, DT_SGU as SGU, - SUMMA as SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_120103', 'IST_NOT_130404') union all
		select DEP_LINK, KT_VKR AS KBK, KT_SGU, SUMMA from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_NOT_130404', 'IST_120103')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('610')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))
	GROUP BY S.KBK, S.SGU

	--строка 821
	INSERT @tICOL7
	SELECT	[CODE_STR] = '821',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR as KBK, DT_SGU as SGU, SUMMA as summa from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_120103', 'IST_NOT_130404')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('510')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))

	--срока 822	
	INSERT @tICOL7
	SELECT	[CODE_STR] = '822',
		[KBK] = 0,
		[SGU] = 0,
		[SUMMA] = SUM(ISNULL(S.SUMMA, 0))
	FROM (select DEP_LINK, DT_VKR as KBK, DT_SGU as SGU, SUMMA as SUMMA  from dbo.AProvByBufferConditionsShort(@ldBegin, @dCALC_DATE, 'IST_120103', 'IST_NOT_130404')) S
	inner join dbo.KOSGU SGU on SGU.LINK = S.SGU and SGU.CODE IN ('610')
	inner join dbo.KL_KBK KBK on KBK.LINK = S.KBK and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))
	WHERE S.DEP_LINK = @liOwnDepLink
			AND (@lbKBK_FILTER=0 OR (KBK is not NULL AND KBK IN (Select LINK FROM @AdmFilter)))

	EXEC dbo.[BufferClear] 'IST_121002'
	EXEC dbo.[BufferClear] 'IST_130405'
	EXEC dbo.[BufferClear] 'IST_NOT_130404'
	EXEC dbo.[BufferClear] 'IST_12010[1,7]'
	EXEC dbo.[BufferClear] 'IST_120103'
	EXEC dbo.[BufferClear] 'IST_130404'
	-- Сборка.
	DECLARE @tCode TABLE (	CODE_STR char(3),
				CODE 	 varchar(30),
				KBK	 int,
				SGU	 int,
				CODE_KL	 varchar(20),
				[NAME]	 varchar(254))
	
	insert into @tCode
	select isnull(SPR.CODE_STR,''),isnull(SPR.CODE,''), C.KBK, C.SGU, isnull(SPR.CODE_IST,''), isnull(SPR.[NAME],'')
	from   (select CODE_STR, KBK, SGU from @tICOL4 where summa <> 0 union
		select CODE_STR, KBK, SGU from @tICOL5 where summa <> 0 union
		select CODE_STR, KBK, SGU from @tICOL6 where summa <> 0 union
		select CODE_STR, KBK, SGU from @tICOL7 where summa <> 0) C
	LEFT join dbo.KL_KBK KBK on KBK.LINK = C.KBK
	LEFT join dbo.KOSGU  SGU on SGU.LINK = C.SGU
	LEFT join dbo.R_SPR_IST_127_2011 SPR on SPR.CODE = case when C.CODE_STR = '520' and KBK.TYPE = 8 then '620' else C.CODE_STR end +
						 	 case C.CODE_STR when '811' then '06000000000000000'
									 when '812' then '07000000000000000'
				 					 when '821' then '09000000000000000'
				 					 when '822' then '01000000000000000'
				  					 else right(rtrim(replace(KBK.CODE,'.','')),14) + SGU.CODE end
	where C.KBK = 0 or ((KBK.TYPE = 4 OR KBK.TYPE = 8) and (@ADM_CODE IS Null OR @ADM_CODE = LEFT(LTRIM(KBK.CODE),3))) and 
			@dCALC_DATE between SPR.BEGIN_DATE and SPR.END_DATE and SPR.CODE_STR is not null
		  
	SELECT	[CODE] = C.CODE_STR + C.CODE_KL,
		COL1   = C.[NAME],
		COL2   = C.CODE_STR,
		COL3   = C.CODE_KL,
		COL4   = sum(ISNULL(C4.SUMMA, 0)),
		COL5   = sum(ISNULL(C5.SUMMA, 0)),
		COL6   = sum(ISNULL(C6.SUMMA, 0)),
		COL7   = sum(ISNULL(C7.SUMMA, 0)),
		COL8   = 0,
		COL9   = 0,
		COL10  = C.CODE_STR + C.CODE_KL
	FROM @tCode C
	left JOIN @tICOL4 C4 ON C4.KBK = C.KBK and C4.SGU = C.SGU and C4.CODE_STR = C.CODE_STR
	left JOIN @tICOL5 C5 ON C5.KBK = C.KBK and C5.SGU = C.SGU and C5.CODE_STR = C.CODE_STR
	left JOIN @tICOL6 C6 ON C6.KBK = C.KBK and C6.SGU = C.SGU and C6.CODE_STR = C.CODE_STR
	left JOIN @tICOL7 C7 ON C7.KBK = C.KBK and C7.SGU = C.SGU and C7.CODE_STR = C.CODE_STR
	
	GROUP BY C.CODE_STR, C.CODE_KL,C.[NAME]
	
	ORDER BY C.CODE_STR, C.CODE_KL
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on [RB_CALC_FORM_0503127G09] to public
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.[RA_EXPORT_FORM_STANDART]
	@iLINK_SAVED_FORM  INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	           INT=1,                  -- Формат: 1-внутренний, 2-минфиновский	
    @vcFILE_NAME_ARH   VARCHAR(100)='' OUTPUT
	--@bSvodWEB         BIT = 0     -- 1 - выгрузка из Свода-WEB, 0 - из Свода-КС.
AS

SET NOCOUNT ON

CREATE TABLE #IMPORT_TABLE([TXT]   VARCHAR(8000), 
                           [ORDER] INT IDENTITY(1, 1))	   

CREATE TABLE #REPORT_DINAMICS([LINK_SF]   INT,
                              [LINK_COL]  INT,
                              [CODE_ROW]  VARCHAR(50),
                              [FLOAT_VAL] NUMERIC(20,4),
                              [STR_VAL]   VARCHAR(8000))

CREATE TABLE #REPORT_SUMMA([LINK_SAVED_FORM] INT,
                           [LINK_COL]        INT,
                           [LINK_ROW]        INT,
                           [SUMMA]           FLOAT(53))

CREATE TABLE #tabExportForms([LINK_SAVED_FORM] INT)

DECLARE @vcVersion       VARCHAR(50),
        @lbIsEmpty       BIT,
        @lcEXPORT_CODE   CHAR(10),
        @lcFORM_CODE     CHAR(20),
        @liFORM_LINK     INT, 
        @lvcPARAM_EXPORT VARCHAR(8000), 
        @ldBEGIN_DATE    DATETIME,
        @ldSTART_DATE    DATETIME,  
        @lvcOUTCODE      VARCHAR(10),
        @lvcDEP_BUDG     VARCHAR(10),
        @lvcDEP_NAME     VARCHAR(254),   
        @lsVERSION       SMALLINT,
        @lvcOKATO        VARCHAR(20),
           
        @liError           INT, 
        @lvcTXT            VARCHAR(8000), 
        @lvcExecTable      VARCHAR(8000), 
        @liORDERS          INT, 
		  @lvcORDERS			VARCHAR(50),
        @lvcTXTDataNotNull VARCHAR(4000),

        @liDEP_LINK	         INT,
        @liDEP_LINK_OWN       INT,
        @liTABLE_LINK	      INT,
        @liTABLE_ORDER	      INT,
        @liTABLE_VAL_TYPE	   INT,
        @liLINK_CODE_COL	   INT,
        @ltORDER_CODE_COL	   INT,
        @liCOL_LINK	         INT,
        @liCOL_TYPE	         INT,
        @liCOL_VAL_LEN        INT,
        @ltCOL_ISEDITED       TINYINT,
        @ltCOL_ISEXPORTED     TINYINT,
        @ltPERIOD_TYPE        TINYINT,
        @lvcDICTIONARY_COLUMNS_LIST VARCHAR(250),

        @lvcExec	            VARCHAR(8000),
        @lvcVersion           VARCHAR(50),

        @lvcATRIBUTS     VARCHAR(8000),
        @lvcATR          VARCHAR(8000),
        @liPosition      INT,
		  @lvcUpdateSelect VARCHAR(8000),
        @tVersionPlace   TINYINT,

        @bIsFormUnion    BIT
        
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
   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

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%'
   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 'ОКАТО=' + @lvcOKATO
	   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
      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]
      
      IF LEN(@lvcTXT)>0
      BEGIN
         SET @lvcTXT = LEFT(@lvcTXT,LEN(@lvcTXT)-1)
      END

--      select @lvcTXT 
   END
   ELSE BEGIN
   	SELECT @lvcTXT = [TXT]
      FROM #tabPARAM_EXPORT 
      WHERE [TABLE_ORDER] = @liTABLE_ORDER
   END
   
	IF LEN(ISNULL(@lvcTXT, '')) > 0
	BEGIN
      IF @iMode = 1
      BEGIN
   		INSERT #IMPORT_TABLE 
         SELECT [TXT] = 'РД=' + LTRIM(CONVERT(VARCHAR(2),@liTABLE_ORDER)) 
      END
      ELSE BEGIN
   		INSERT #IMPORT_TABLE([TXT]) SELECT '#@'
   		INSERT #IMPORT_TABLE([TXT]) SELECT 'ТБ=' + RIGHT(RTRIM('0' + LTRIM(CONVERT(CHAR(2),@liTABLE_ORDER))),2)
   		INSERT #IMPORT_TABLE([TXT]) SELECT '#$'
      END
/*
		SELECT @liLINK_CODE_COL = [LINK_CODE_COL]
      FROM dbo.[REPORT_TABLES]
      WHERE [LINK_TABLE] = @liTABLE_LINK
*/
		SELECT @lvcExecTable = 'CREATE TABLE #tabRI_PROC_T ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] ' + 
                             CASE 
                                WHEN [A].[COL_TYPE] = 1 THEN 'VARCHAR(50)' 
                                ELSE 'FLOAT' 
                             END,
				 @lvcUpdateSelect = 'SELECT [CHECKED], [UPD], [DEL], [LINK_SAVED_FORM], [LINK_ROW], [ORDERS], [CALC_ORDERS], [PRINT_NULL], [CODE] '
		FROM dbo.[REPORT_COLOUMNS]    [A]
      LEFT JOIN dbo.[REPORT_TABLES] [B] ON [B].[LINK_CODE_COL] = [A].[LINK_COL]
		WHERE [B].[LINK_TABLE] = @liTABLE_LINK

      SET @lvcTXTDataNotNull = '1=2'

   	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(@lvcTXT, 'STR(', 'CONVERT(VARCHAR(20), ') + 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
-- Выгрузка подписей.
	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)

   INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcExec)
   
	SET @lvcExec = 'Тел.=' 
	SELECT  @lvcExec = @lvcExec + RTRIM(ISNULL([PHONES],''))
   FROM dbo.[RA_GET_USER_INFO](NULL)

	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 ALL ON dbo.[RA_EXPORT_FORM_STANDART] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_772]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_772]
END
GO

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_772]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(SUBSTRING(TXT, 22,8000), '*|*****|***|', '9|99999|999|')
      WHERE TXT LIKE '%|%'
            and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=01')
         and [ORDER] < (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=02')

      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(SUBSTRING(TXT, 23,8000), '*|*****|***|', '9|99999|999|')
      WHERE TXT LIKE '%|%'
            and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=02')
         and [ORDER] < (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=03')

      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(SUBSTRING(TXT, 20,8000), '*|*****|***|', '8|88888|888|')
      WHERE TXT LIKE '%|%'
            and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=04')


      UPDATE #IMPORT_TABLE
      SET TXT = '0|00011|000|' + SUBSTRING(TXT, 4, 8000)
      WHERE TXT LIKE '11|%'

      UPDATE #IMPORT_TABLE
      SET TXT = ''
      WHERE TXT IN ('ТБ=02', 'ТБ=03', 'ТБ=04') OR TXT LIKE '**|%'


--SELECT * FROM #import_table
 
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

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

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
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
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int

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

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)
VALUES (@LINK,@ORDERS,@REF_DED,@SummaBase,@PERCENT,@Summa,@LinkVKR,@LinkEKR)

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0


GO


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

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_KBK_CASHE_UPDATE]
	@iLINK INT = NULL,
	@vcCodeForm	   VARCHAR(100) = NULL,
   @tOnlyAdd   BIT = 0
AS

IF isnull(@tOnlyAdd, 0) = 0
BEGIN 
   DELETE dbo.report_kbk_cashe
   WHERE (Link_Up = @iLINK OR @iLINK IS NULL)
   AND (@vcCodeForm IS NULL OR Link_UP IN (SELECT link FROM dbo.report_kbk WHERE [Code_Form] = @vcCodeForm))

   INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
   SELECT K.[LINK],
   [begin_date] = isnull((case when isnull(K.[begin_date],'19000101') > isnull(KH.date_begin,'19000101') then K.[begin_date] ELSE KH.date_begin END), '19000101'),
   [end_date] = ISNULL((case when isnull(K.[end_date],'30000101') > isnull(KH.date_end,'30000101') then KH.[date_end] ELSE K.end_date END),'30000101'),
   isnull(KH.[NAME], K.Name),
   isnull(KH.[LONG_NAME], K.[LONG_NAME])
   FROM dbo.report_kbk K
   LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   WHERE (K.Link = @iLINK OR @iLINK IS NULL)
   AND (@vcCodeForm IS NULL OR K.[Code_Form] = @vcCodeForm)

   INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
   SELECT K.[LINK],
   isnull(K.[begin_date], '19000101'),
   KH.[date_begin]-1,
   K.[NAME],
   K.[LONG_NAME]
   FROM dbo.report_kbk K
   LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   WHERE isnull(K.begin_date, '20000101') < KH.date_begin
   AND KH.date_begin = (SELECT MIN(KH1.DATE)
   FROM dbo.[REPORT_KBK_HIST] KH1
   WHERE KH1.[LINK_UP] = K.[link])
   AND (K.Link = @iLINK OR @iLINK IS NULL)
   AND (@vcCodeForm IS NULL OR K.[Code_Form] = @vcCodeForm)
END 
ELSE
BEGIN
   INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
   SELECT K.[LINK],
   [begin_date] = isnull((case when isnull(K.[begin_date],'19000101') > isnull(KH.date_begin,'19000101') then K.[begin_date] ELSE KH.date_begin END), '19000101'),
   [end_date] = ISNULL((case when isnull(K.[end_date],'30000101') > isnull(KH.date_end,'30000101') then KH.[date_end] ELSE K.end_date END),'30000101'),
   isnull(KH.[NAME], K.Name),
   isnull(KH.[LONG_NAME], K.[LONG_NAME])
   FROM dbo.report_kbk K
      LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   WHERE (K.Link = @iLINK OR @iLINK IS NULL)
      AND (@vcCodeForm IS NULL OR K.[Code_Form] = @vcCodeForm)
      AND NOT EXISTS(SELECT * FROM dbo.report_kbk_cashe C WHERE C.[LINK_UP] = K.[link])

   INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
   SELECT K.[LINK],
   isnull(K.[begin_date], '19000101'),
   KH.[date_begin]-1,
   K.[NAME],
   K.[LONG_NAME]
   FROM dbo.report_kbk K
   LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   WHERE isnull(K.begin_date, '20000101') < KH.date_begin
   AND KH.date_begin = (SELECT MIN(KH1.DATE)
   FROM dbo.[REPORT_KBK_HIST] KH1
   WHERE KH1.[LINK_UP] = K.[link])
   AND (K.Link = @iLINK OR @iLINK IS NULL)
   AND (@vcCodeForm IS NULL OR K.[Code_Form] = @vcCodeForm)
      AND NOT EXISTS(SELECT * FROM dbo.report_kbk_cashe C WHERE C.[LINK_UP] = K.[link])
END       




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

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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


/*
c Кейсистемс (Keysystems), 2009
Размножение правил "для всех столбцов", "для всех колонок"
с учетом диапазона столбцов и колонок для правил, в котором есть деление, умножение, маски

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(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(250), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(250), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10))
create table #t_Rows_Static(Link_Row int primary key, Code varchar(50), Link_Table int)
create table #report_dinamics(Link_SF int, Code_Row varchar(50), link_col int, float_val numeric(20,4), str_val varchar(8000))
*/
CREATE    PROCEDURE dbo.RO_RAZMNOJ_KS_INSIDE
  @From tinyint = 0, -- откуда вызвали, 0 - с проверки КС, 1 - с досчета КС,
  @cProgressTable     varchar(254)  = ''

AS

SET NOCOUNT ON

if object_id('tempdb..#t_KS') is NULL
begin
  return -1
end

create table #t_KS2 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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 default(0))

CREATE INDEX #IX_t_ks2 ON #t_KS2 (Link_Rule, OrderRow, OrderCol, CodeRow)

exec sp_executesql N'insert #t_KS2
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, px_Comment, [property]
from #t_KS
where algorithm in (0,9) 
delete #t_KS where algorithm in (0,9)'

declare @link_table int,@calc_maska int,@ExecStr nvarchar(4000), @LinkRule int, @LinkTable int, @ValType tinyint, @CondRows varchar(3000),@get_str varchar(250),@ExecStr1 varchar(8000)
declare  @orderCol tinyint, @lsf INT 
SELECT @lsf = lsf FROM #t_summa
IF @lsf IS NULL
  SELECT @lsf = link_sf FROM #report_dinamics

create table #t_temp (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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 default (0))

   update #T_KS2
    set mask=dbo.rn_getwordnum(mask,1,'#')         
    where  charindex('#',mask)>0 and charindex('select',mask) = 0
         AND charindex('reports_atr',mask) = 0

-- РАЗМНОЖАЕМ КОЛОНКИ   
insert #t_temp
  select * from #t_KS2 where (Link_Col is NULL or Cols <> '') and (Val_Type = 0 or Val_Type = 3 or Val_Type = 4)

 delete #t_KS2 where (Link_Col is NULL or Cols <> '') and (Val_Type = 0 or Val_Type = 3 or Val_Type = 4)

insert #t_KS2
  select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, B.Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], B.orderCol, CodeRow, cOrderTable, B.cOrderCol, px_Comment, [property]
  from #t_temp A left merge join #t_Col B on A.link_table = B.link_table
  where A.Cols = '' or (A.Cols <> '' and CHARINDEX(',' + LTRIM(STR(B.OrderCol)) + ',', ',' + RTRIM(A.Cols) + ',') > 0) 


insert #t_KS2 
  select Link_Rule, OrderRow, val_type, [sign], B.Link_Table, B.Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], C.orderCol, CodeRow, cOrderTable, B.cOrderCol, px_Comment, [property]
  from #t_Col C, #t_KS2 B  
  where B.orderCol = 0
    and C.Link_Table = (select top 1 Link_Table from #t_temp A1 where A1.Link_Rule = B.Link_Rule and Link_Table is NOT NULL) 
    and not exists(select top 1 * from #t_temp A where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow)
    and (B.Cols = '' or (B.Cols <> '' and CHARINDEX(',' + LTRIM(STR(C.OrderCol)) + ',', ',' + RTRIM(B.Cols) + ',') > 0))

delete #t_KS2 where Link_Rule in (select distinct Link_Rule from #t_temp) and (orderCol = 0)

--select * from #t_ks where link_rule=745468 order by orders,orderrow
--  select * from #t_KS where [Rows] <> '' and filter<>''

truncate table #t_temp

-- РАЗМНОЖАЕМ ^
-- для внутридокументных пока только
create table #tmp_b (Link_Rule int , Link_Col int,Link_Row int,Code_Row varchar(100),LinkTable int,PrevOrderRow int,OrderRow int,orderCol tinyint, CodeRow varchar(50), [property] tinyint)

insert #tmp_b 
select A.Link_Rule,A.Link_Col,A.Link_Row,A.Code_Row,A.link_Table, (select max(orderRow) from #T_KS2 B where B.orderRow<A.orderRow and B.link_rule=A.link_rule) as PrevOrderRow,A.OrderRow,A.orderCol, A.CodeRow, [property]
      from #T_KS2 A where A.sign='^'

--для статических таблиц
INSERT #T_KS2
select E.Link_Rule, E.OrderRow, E.val_type, '+', E.Link_Table, G.Link_Col, F.Link_Row, '', E.Factor, E.px, E.Exec_Proc, E.Filter, E.Filter_desc, E.Mask , E.part, E.algorithm, E.cols, E.[rows], E.[Value], E.orderCol, E.CodeRow, E.cOrderTable, G.cOrderCol, E.px_comment, E.[property]
from #t_Rows_Static F ,#T_COL G,
(select (select Orders from #t_Rows_Static where link_row=D.link_row) RowOrders1, 
       (select Orders from #t_Rows_Static where link_row=C.link_row) RowOrders2,
       (select OrderCol from #T_COL where link_Col=D.Link_Col) ColOrders1,
       (select OrderCol from #T_COL where link_Col=C.Link_Col) ColOrders2,
        C.link_col as MainCol, C.Code_Row Code_Row1,D.Code_Row Code_Row2,D.Link_Rule,C.OrderRow,D.Val_type,D.px,D.cOrderTable, D.algorithm, D.Link_Table,D.[Rows],D.[Cols],D.Factor,D.Exec_Proc,D.Filter,D.Mask,D.Value,D.OrderCol,D.CodeRow,D.sign,D.part,D.Filter_Desc, D.px_comment, D.[property]
	from #tmp_b C LEFT JOIN #T_KS2 D ON C.Link_rule=D.Link_rule and D.orderrow=C.prevOrderRow and C.orderCol=D.orderCol and C.CodeRow = D.CodeRow WHERE C.PrevOrderRow is not null ) E
where  F.link_table=E.link_table AND F.orders>=RowOrders1 and F.orders<=RowOrders2 and G.link_Table=E.link_table and ((G.OrderCol>=ColOrders1 and G.OrderCol<=ColOrders2) or (ColOrders1 is null or ColOrders2 is null)) 

--для динамических таблиц
INSERT #T_KS2 
select  E.Link_Rule, E.OrderRow, E.val_type, '+', E.Link_Table, G.Link_Col, NULL, F.Code_Row, E.Factor, E.px, E.Exec_Proc, E.Filter, E.Filter_desc, E.Mask , E.part, E.algorithm, E.cols, E.[rows], E.[Value], E.orderCol, E.CodeRow, E.cOrderTable, G.cOrderCol, E.px_comment, E.[property]
from #report_dinamics F ,#T_COL G,
(select (select OrderCol from #t_Col where link_Col=D.Link_Col) ColOrders1,
        (select OrderCol from #t_Col where link_Col=C.Link_Col) ColOrders2,
        C.link_col as MainCol,D.Code_Row Code_Row1,C.Code_Row Code_Row2,D.Link_Rule,C.OrderRow,D.Val_type,D.Link_Table,D.[Rows],D.[Cols],D.Factor, D.px, D.cOrderTable,D.Exec_Proc,D.Filter,D.Mask,D.Value,D.OrderCol, D.CodeRow,D.sign,D.part,D.algorithm,D.Filter_Desc, D.px_comment, D.[property]
from #tmp_b C LEFT JOIN #T_KS2 D ON C.Link_rule=D.Link_rule and D.orderrow=C.prevOrderRow and C.orderCol=D.orderCol and C.CodeRow = D.CodeRow WHERE C.PrevOrderRow is not null ) E
where  E.val_type=3 and F.link_table=E.link_table AND F.CODE_ROW>=Code_ROW1 and F.CODE_ROW<=CODE_ROW2 and G.link_Table=E.link_table  and ((G.OrderCol>=ColOrders1 and G.OrderCol<=ColOrders2) or (ColOrders1 is null or ColOrders2 is null)) and G.Link_Col = F.Link_Col

delete from #T_KS2 where Exists(select * from #tmp_b A where A.link_rule=#T_KS2.link_rule and A.orderCol = #T_KS2.OrderCol and A.CodeRow = #T_KS2.CodeRow And ((#T_KS2.OrderRow=A.OrderRow AND #T_KS2.sign='^') OR #T_KS2.OrderRow=A.PrevOrderRow))

-- РАЗМНОЖАЕМ СТРОКИ С ДИАПАЗОНОМ
declare @t_table table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)
insert #t_temp
  select * from #t_KS2 where [Rows] <> '' and rtrim(filter)=''

insert @t_table 
	select * from #t_temp

delete #t_KS2 where [Rows] <> '' and rtrim(filter)=''

while exists(select top 1 * from #t_temp)
begin
  set @LinkTable=null	
  select top 1 @LinkRule = Link_Rule, @CondRows = [Rows] from #t_temp
  select top 1 @LinkTable = Link_Table, @ValType = Val_Type from #t_temp where Link_Rule = @LinkRule and Link_Table is NOT NULL
  if @ValType = 0 -- таблица статическая
  begin
    set @ExecStr = 'insert #t_KS2 
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, isnull(A.Link_Row,B.Link_Row), Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join #t_Rows_Static B on A.link_table = B.link_table
where A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and (' + REPLACE(@CondRows, 'COL(', 'dbo.RO_COL_Static(' + LTRIM(STR(@lsf)) + ',' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,') + ')'
  end
  else 
    begin -- таблица динамическая
  set @ExecStr = 'insert #t_KS2
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, case when isnull(A.Code_Row,'''') = '''' then  RD.Code_Row else A.Code_Row end, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, RD.Code_Row, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join 
#report_dinamics RD on A.Link_Col = RD.Link_Col
where  A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and (' + REPLACE(REPLACE(REPLACE(REPLACE(@CondRows, 'CODE', 'RD.Code_Row'),'.RD.Code_Row', '.Code'), '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 =' + LTRIM(STR(@LinkTable))+' and RC.orders ='), 'COLS(','(select top 1 str_val 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders =') + ')'
end
--print @ExecStr
  exec sp_executesql @ExecStr
--	IF @linktable is null
--		delete #t_temp where Link_Rule = @LinkRule and link_table is null
--	else
--		delete #t_temp where Link_Rule = @LinkRule and link_table=@linktable
	delete #t_temp where Link_Rule = @LinkRule --and link_table=isnull(@linktable,link_table) 
end

	--select * from #t_ks2 WHERE link_rule =   5215051


---- если вообще нет строк
DELETE #t_ks2
WHERE Link_Rule IN (SELECT Link_Rule FROM @t_table A where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and CodeRow <> ''))

--insert #t_KS2 -- в случае если есть другие слагаемые, которые не надо размножать
--select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, 'нет данных', Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, '', cOrderTable, cOrderCol, px_comment, [property]
--from @t_table A
--where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and CodeRow <> '')

insert #t_KS2 -- в случае если есть другие слагаемые, которые не надо размножать
select A.Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, K1.CodeRow, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], A.orderCol, K1.CodeRow, cOrderTable, cOrderCol, px_comment, [property]
from @t_table A  inner join (select distinct Link_Rule, CodeRow, OrderCol from #t_ks2 where CodeRow <> '') K1 on A.Link_Rule = K1.Link_Rule and A.orderCol = K1.OrderCol
where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and A.orderCol = K.orderCol and A.OrderRow = K.OrderRow and K.CodeRow = K1.CodeRow)

 -- досчет
if @From = 1
begin
	insert #t_ks2 -- если есть другие части
	select A.Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, K1.CodeRow, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], A.orderCol, K1.CodeRow, cOrderTable, cOrderCol, px_comment, [property]
	from @t_table A inner join (select distinct Link_Rule, CodeRow, OrderCol from #t_ks2 where CodeRow <> '') K1 on A.Link_Rule = K1.Link_Rule and A.orderCol = K1.OrderCol
	where part = 0 and exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and CodeRow <> '')
END


truncate table #t_temp
-- РАЗМНОЖАЕМ СТРОКИ С ФИЛЬТРОМ, с учетом МАСКИ
declare @LF int, @LC int, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
   @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
  @CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @option_import_report INT
insert #t_temp
  select * from #t_KS2 where ([Filter] <> '' OR MASK <> '') and Val_Type = 4
--set @cnt = @@rowcount
--set @i = 0
--select @mini = min(ord) from #t_temp

delete @t_table
insert @t_table
select * from #t_temp

delete #t_KS2 where ([Filter] <> '' OR MASK <> '') and Val_Type = 4

declare @condFilter varchar(3000),@orderrow int,@condMaska varchar(200)
create table #t_KS1 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)

while exists(select top 1 * from #t_temp)
begin
  select top 1 @LinkRule = Link_Rule, @CondFilter =REPLACE('('+rtrim([Filter])+')' + case when [rows] <> '' then ' and (' + [rows] + ')' else '' end,'report_dinamics_all', '#report_dinamics') ,@CondMaska =[Mask], @orderrow = orderrow, @orderCol = orderCol 
	from #t_temp


  select top 1 @LinkTable = Link_Table  from #t_temp where Link_Rule = @LinkRule and Link_Table is NOT NULL and orderrow = @orderrow
  select top 1 @valtype=val_type from report_tables where link_table=@linkTable
  
  	-- атрибуты в фильтрах
   SELECT @CondFilter = REPLACE(@CondFilter, '#' + rtrim(code_atr) + '#', '''' + str_val + ''''),
         @condMaska = REPLACE(@condMaska, '#' + rtrim(code_atr) + '#', '''' + str_val + '''')
   FROM dbo.[REPORT_ATRIBUT_VALUES] rav
   WHERE rav.[link_saved_form] = @lsf
   
   SELECT  @CondFilter = REPLACE(@CondFilter, '#' + rtrim(SO1.code) + '#', '''' + isnull(OV.[VALUE],'') + ''''),
         @condMaska = REPLACE(@condMaska, '#' + 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'
     

      
  if @ValType = 0 -- таблица статическая
  begin
       set @condMaska= RTRIM(case when @condMaska<>'' then REPLACE(REPLACE(@condMaska,'CODE', 'B.CODE'), 'COL(', 'dbo.RO_COL_Static(' + LTRIM(STR(@lsf)) + ',' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')   else '' end)
       set @ExecStr=''
       set @ExecStr = 'insert #t_KS1 
		select Link_Rule, OrderRow, 0, [sign], A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol,  ' + case when @condMaska = '' then '''''' else @condMaska end + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join #t_Rows_Static B on A.link_table = B.link_table
        where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) +/* ' and A.orderCol = ' + STR(@orderCol) +*/ ' and (' + REPLACE(REPLACE(REPLACE(@CondFilter, 'COL(', '(select case when col_type = 0 then STR((select summa from #t_summa S where S.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 = B.Link_Row) end from report_coloumns RC where link_table = ' + STR(@LinkTable) + ' and orders ='), 'CODE', 'B.CODE'), '.B.CODE', '.CODE') + ')'
  end
  else begin -- таблица динамическая
    set @condMaska= RTRIM(case when @condMaska<>'' then REPLACE(REPLACE(REPLACE(@CondMaska, 'CODE', 'RD.Code_Row'),'.RD.Code_Row','.Code'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,' + LTRIM(STR(@LinkTable)) + ', RD.Code_Row,')   else '' end)
    set @ExecStr = '
      insert #t_KS1 
		select Link_Rule, OrderRow, 3, [sign], A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, ' + case when @condMaska = '' then '''''' else @condMaska end + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join 
        (select distinct Link_SF, Link_Table, Code_Row from #report_dinamics) RD on A.Link_Table = RD.Link_Table '+
        'where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) /*+ ' and A.orderCol = ' + STR(@orderCol)*/ + ' and (' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@CondFilter,'B.','A.'),'A.Link_SF','RD.Link_SF'), 'CODE', 'RD.Code_Row'),'.RD.Code_Row','.Code'), 'COL(','(select top 1 case when RC.Col_Type = 0 then float_val 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders ='), 'COLS(','(select top 1 str_val 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders =') +  ')' +
        ' IF @@rowcount=0 
        insert #t_KS1 
		select Link_Rule, OrderRow, 3, [sign], Link_Table, Link_Col, NULL, ''нет строк'', Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, CodeRow, cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp  where orderrow='+LTRIM(STR(@orderrow))+ ' and Link_Rule = ' + LTRIM(STR(@LinkRule))-- + ' and orderCol = ' + LTRIM(STR(@orderCol))
    
  end
--	print @ExecStr
  exec sp_executesql @ExecStr
  delete #t_temp where Link_Rule = @LinkRule and orderrow = @orderrow  --and orderCol = @orderCol
end

--if @From = 1 -- этих строк нет, но они должны появиться в досчете
--begin
	update #t_KS1
	set CodeRow = K.CodeRow
	from (select * from #t_KS1 where CodeRow <> '') K
	where #t_KS1.Code_Row = 'нет строк' and K.Link_Rule = #t_KS1.Link_Rule and K.orderCol = #t_KS1.orderCol

/*	insert #t_ks1
	select K.Link_Rule, K.OrderRow, K.val_type, K.[sign], K.Link_Table, K.Link_Col, K.Link_Row, K1.CodeRow, K.Factor, K.px, K.Exec_Proc, K.Filter, K.Filter_Desc, K.Mask , K.part, K.algorithm, K.cols, K.[rows], K.[Value], K.orderCol, K1.CodeRow, K.cOrderTable, K.cOrderCol
	from (select * from #t_ks1 where OrderRow = 1 and CodeRow = '') K
		left join (select distinct Link_Rule, CodeRow, orderCol from #t_ks1 where OrderRow <> 1 and CodeRow <> '') K1 on K.Link_Rule = K1.Link_Rule and K.orderCol = K1.orderCol
*/
	insert #t_KS1
	select T.Link_Rule, T.OrderRow, 3, T.[sign], T.Link_Table, T.Link_Col, NULL, 'нет строк', T.Factor, T.px, T.Exec_Proc, T.Filter, T.Filter_desc, T.Mask , T.part, T.algorithm, T.cols, T.[rows], T.[Value], T.orderCol, K.CodeRow, T.cOrderTable, T.cOrderCol, px_comment, [property]
	from (select distinct Link_Rule, orderCol, CodeRow from #t_KS1 where CodeRow <> '' ) K inner join @t_table T on K.Link_Rule = T.Link_Rule and K.orderCol = T.orderCol
	where not exists(select top 1 * from #t_KS1 K1 where K1.Link_Rule = T.Link_Rule and K1.orderCol = T.orderCol and K1.orderrow = T.orderRow and K1.CodeRow = K.CodeRow)
	
	delete #t_ks1
	where isnull(CodeRow,'') = '' and (isnull(Code_Row,'') = '' or Code_Row = 'нет строк') and Link_Row is NULL and part = 0

	insert #t_ks2
    select *
    from #t_ks1 



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

truncate table #t_temp

-- РАЗМНОЖАЕМ СТРОКИ БЕЗ ДИАПАЗОНА

insert #t_temp
  select * from #t_KS2 where ((Link_Row is NULL and Val_Type = 0) or (Code_Row = '' and Val_Type = 3)) and [Rows] = '' 

delete #t_KS2 where ((Link_Row is NULL and Val_Type = 0) or (Code_Row = '' and Val_Type = 3)) and [Rows] = ''

-- для статических таблиц
insert #t_KS2 
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, isnull(A.Link_Row, B.Link_Row), Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join #t_Rows_Static B on A.link_table = B.link_table

insert #t_KS2 
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code, cOrderTable, cOrderCol, px_comment, [property]
  from #t_Rows_Static B, #t_KS2 A  
  where A.CodeRow = '' and B.Link_Table = (select top 1 Link_Table from #t_temp A1 where A1.Link_Rule = A.Link_Rule) 
    and not exists(select top 1 * from #t_temp B where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow and A.orderCol = B.orderCol)


-- для динамических таблиц
insert #t_KS2
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, RD.Code_Row, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join (select distinct Code_Row, Link_Table from #report_dinamics) RD on A.Link_Table = RD.Link_Table
where isnull(A.Code_Row, '') = ''

-- если вообще нет строк
insert #t_KS2
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, 'нет данных', Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, '', cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A
where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and CodeRow <> '')


if @From = 1
begin
	delete #t_KS2
	where part = 0 and CodeRow = '' and Code_Row = 'нет данных'
end
	

insert #t_KS2
select Link_Rule, OrderRow, val_type, [sign], A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, RD.Code_Row, cOrderTable, cOrderCol, px_comment, [property]
  from #t_KS2 A, (select distinct Code_Row, Link_Table from #report_dinamics) RD 
  where  A.CodeRow = '' and RD.Link_Table = (select top 1 Link_Table from #t_temp A1 where A1.Link_Rule = A.Link_Rule) 
    and not exists(select top 1 * from #T_temp B where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow and A.orderCol = B.orderCol)

delete #t_KS2 where Link_Rule in (select Link_Rule from #t_temp) and CodeRow = ''

update #t_KS2
set algorithm = 1
where Link_Rule not in (select Link_Rule from #t_KS2 where sign not in ('+', '-'))
      AND [algorithm] = 0

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, px_comment, [property])
select * from #t_KS2


drop table #t_temp
drop table #t_KS1
drop table #t_KS2

GO
GRANT ALL ON dbo.[RO_RAZMNOJ_KS_INSIDE] 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].[ro_copy_table]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ro_copy_table]
GO








/*
	c Кейсистемс (Keysystems), 2005	
	Копирование таблицы, линк таблицы находится в buffer

*/
CREATE       proc dbo.ro_copy_table
	@savelink_id	varchar(100) = null,
	@form		int
as

declare @savelink int, @name varchar(200), @orders int, @link_code_col int, @val_type tinyint, @script_str varchar(7000), @new_link int
declare @cLink_col_new int, @clink_col int, @corders tinyint, @cname varchar(250), @cIsExported tinyint, @cCol_Type tinyint, @cExport_Order tinyint, @cCalc_Orders int, @cIsEdited tinyint, @cVal_len int
declare @rlink_row_new int, @rlink_row int , @rorders int, @rcalc_orders smallint, @rprint_null tinyint,@Property int,@Input_mask varchar(250),@Dictionary varchar(100),@Dictionary_Columns_List varchar(250),@Dictionary_Fields_List varchar(250)


if @savelink_id  IS NOT NULL 
begin

	select @savelink = link from buffer where id = @savelink_id

	select @link_code_col = link_code_col from report_tables where link_table = @savelink

	select @name = name, @val_type = val_type, @script_str = script_str
	from report_tables
	where link_table = @savelink

	select @orders = max(orders) + 1 from report_tables where link_form = @form

	if @orders is NULL
		set @orders = 1
	
	exec i_report_save_report_tables @new_link output, @name, @form, @orders

	declare cur_cols cursor local for
		select link_col, orders, name, IsExported, Col_Type, Export_Order, Calc_Orders, IsEdited, Val_len,Property,Input_mask,Dictionary,Dictionary_Columns_List,Dictionary_Fields_List from report_coloumns where link_table = @savelink

	open cur_cols

	fetch next from cur_cols
	into @clink_col, @corders, @cname, @cIsExported, @cCol_Type, @cExport_Order, @cCalc_Orders, @cIsEdited, @cVal_len,@Property,@Input_mask,@Dictionary,@Dictionary_Columns_List,@Dictionary_Fields_List

	while @@FETCH_STATUS = 0
	begin
		set @cLink_col_new = null
		exec i_report_save_report_coloumns @cLink_col_new output, @corders, @cname, @new_link, @cIsExported, @cCol_Type, @cExport_Order, @cCalc_Orders, @cVal_len, @cIsEdited,@Dictionary,@Dictionary_Columns_List,@Dictionary_Fields_List,@Input_mask,@Property
		if @link_code_col = @clink_col
		begin
			set @link_code_col = @cLink_col_new
		end
		
		if @val_type = 0 
		begin
			insert into report_formula (link_row, link_col, formula)
				select link_row, @cLink_col_new as link_col, formula from report_formula where link_col = @clink_col
		end

		FETCH NEXT FROM cur_cols
		into @clink_col, @corders, @cname, @cIsExported, @cCol_Type, @cExport_Order, @cCalc_Orders, @cIsEdited, @cVal_len,@Property,@Input_mask,@Dictionary,@Dictionary_Columns_List,@Dictionary_Fields_List
	end	

	exec i_report_save_report_tables @new_link, @name, @form, @orders, @link_code_col, @val_type, @script_str
	if @val_type = 0 
	begin
		declare cur_rows cursor local for
			select link_row, orders, calc_orders, print_null from report_rows where link_table = @savelink

		open cur_rows
	
		fetch next from cur_rows
		into @rlink_row, @rorders, @rcalc_orders, @rprint_null

		while @@FETCH_STATUS = 0
		begin
			set @rlink_row_new = null
			exec i_report_save_report_rows @rlink_row_new output, @rorders, @new_link, @rcalc_orders, @rprint_null
			update report_formula set link_row = @rlink_row_new
				where link_row = @rlink_row and link_col in (select link_col from report_coloumns where link_table = @new_link)
			fetch next from cur_rows
			into @rlink_row, @rorders, @rcalc_orders, @rprint_null
		end	

		close cur_rows
		deallocate cur_rows
	
	end

	close cur_cols
	deallocate cur_cols
	exec i_report_create_proc @new_link

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

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_RRO_ANALYZE]
	@iLINK_SAVED_FORM INT,
   @bCancel          BIT  = NULL OUTPUT
AS

SET NOCOUNT ON
SET DATEFORMAT dmy

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


IF OBJECT_ID('tempdb..#tabExportLog') IS NULL
BEGIN
   RETURN -1
END

DECLARE @vcExec          VARCHAR(8000),
        @iReturn			 INT,
		  @vcControlED		 VARCHAR(8000),
		  @vcControlStr	 VARCHAR(8000),
		  @vcControl		 VARCHAR(8000),
		  @iLINK_FORM		 INT,
		  @iLINK_TABLE_1   INT,
        @iLINK_TABLE_2   INT,
        @iLINK_TABLE_3   INT,

		  @vcGR0  VARCHAR(8000),
		  @vcGR1  VARCHAR(8000),
		  @vcGR2  VARCHAR(8000),
		  @vcGR3  VARCHAR(8000),
		  @vcGR10 VARCHAR(8000),
		  @vcGR11 VARCHAR(8000),
		  @vcGR12 VARCHAR(8000),
		  @vcGR13 VARCHAR(8000),
		  @vcGR14 VARCHAR(8000),
		  @vcGR15 VARCHAR(8000),
		  @vcGR16 VARCHAR(8000),
		  @vcGR17 VARCHAR(8000),
		  @vcGR18 VARCHAR(8000),
		  @vcGR19 VARCHAR(8000),
        @vcNameTable VARCHAR(100)

DECLARE @tabCheckedCodes TABLE ([CODE] VARCHAR(30))

DECLARE @tabErrorLog TABLE([TXT] VARCHAR(8000),[TABLE] INT,[ORDER] INT IDENTITY(1,1))

	  
DECLARE @tabXML TABLE ([TXT]	  VARCHAR(8000), 						
							  [ORDERS] INT IDENTITY(1,1))		  

CREATE TABLE #tabBILL([TABLE]     INT,
                      [ORDER]     CHAR(3),
                      [GR0]		 VARCHAR(8000),
							 [GR2]		 VARCHAR(8000),
							 [BRank]		 VARCHAR(8000),
							 [BClass]	 VARCHAR(8000),
							 [BDate]		 VARCHAR(8000),
							 [BNumb]		 VARCHAR(8000),
							 [BName]		 VARCHAR(8000),
							 [BRubric]	 VARCHAR(8000),
							 [BSubpar]	 VARCHAR(8000),
							 [BParagr]	 VARCHAR(8000),
							 [BPart]	    VARCHAR(8000),
							 [BParticle] VARCHAR(8000),
							 [BDateBeg]  VARCHAR(8000),
							 [BDateEnd]  VARCHAR(8000))

CREATE TABLE #tabAttr ([CODE] VARCHAR(100),
                       [NAME] VARCHAR(500),
						     [VAL]	VARCHAR(8000))

SELECT @iLINK_FORM = [LINK_FORM]
FROM dbo.[REPORT_SAVED_FORMS]
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM 

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

SELECT @iLINK_TABLE_2 = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 2

SELECT @iLINK_TABLE_3 = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 3
      
EXEC dbo.[X_GET_TABLE_NAME] @vcNameTable OUTPUT 

--SELECT @vcExec = 'CREATE TABLE #tabRI_PROC_T1([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),' +
--								         		      '[COL1] NUMERIC(20,1),[COL2] NUMERIC(20,1),[COL3] NUMERIC(20,1),[COL4] NUMERIC(20,1),[COL5] NUMERIC(20,1),[COL6] NUMERIC(20,1),[COL7] VARCHAR(8000),[COL8] VARCHAR(8000),[COL9] VARCHAR(8000),[COL10] VARCHAR(8000),'+
--													      '[COL11] VARCHAR(8000),[COL12] VARCHAR(8000),[COL13] VARCHAR(8000),[COL14] VARCHAR(8000),[COL15] VARCHAR(8000),[COL16] VARCHAR(8000),[COL17] VARCHAR(8000),[COL18] VARCHAR(8000),[COL19] VARCHAR(8000),[COL20] VARCHAR(8000),'+
--													      '[COL21] VARCHAR(8000),[COL22] VARCHAR(8000),[COL23] VARCHAR(8000),[COL24] VARCHAR(8000),[COL25] VARCHAR(8000),[COL26] VARCHAR(8000),[COL27] VARCHAR(8000),[COL28] VARCHAR(8000),[COL29] VARCHAR(8000),[COL30] VARCHAR(8000),'+
--													      '[COL31] VARCHAR(8000),[COL32] VARCHAR(8000),[COL33] VARCHAR(8000),[COL34] VARCHAR(8000),[COL35] VARCHAR(8000),[COL36] VARCHAR(8000),[COL37] VARCHAR(8000)) ' + CHAR(13) +
--                 'CREATE TABLE #tabRI_PROC_T2([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),' +
--								         		      '[COL1] NUMERIC(20,1),[COL2] NUMERIC(20,1),[COL3] NUMERIC(20,1),[COL4] NUMERIC(20,1),[COL5] NUMERIC(20,1),[COL6] NUMERIC(20,1),[COL7] VARCHAR(8000),[COL8] VARCHAR(8000),[COL9] VARCHAR(8000),[COL10] VARCHAR(8000),'+
--													      '[COL11] VARCHAR(8000),[COL12] VARCHAR(8000),[COL13] VARCHAR(8000),[COL14] VARCHAR(8000),[COL15] VARCHAR(8000),[COL16] VARCHAR(8000),[COL17] VARCHAR(8000),[COL18] VARCHAR(8000),[COL19] VARCHAR(8000),[COL20] VARCHAR(8000),'+
--													      '[COL21] VARCHAR(8000),[COL22] VARCHAR(8000),[COL23] VARCHAR(8000),[COL24] VARCHAR(8000),[COL25] VARCHAR(8000),[COL26] VARCHAR(8000),[COL27] VARCHAR(8000),[COL28] VARCHAR(8000),[COL29] VARCHAR(8000),[COL30] VARCHAR(8000),'+
--													      '[COL31] VARCHAR(8000),[COL32] VARCHAR(8000),[COL33] VARCHAR(8000),[COL34] VARCHAR(8000),[COL35] VARCHAR(8000),[COL36] VARCHAR(8000),[COL37] VARCHAR(8000),[COL38] VARCHAR(8000),[COL39] VARCHAR(8000),[COL40] VARCHAR(8000),'+
--													      '[COL41] VARCHAR(8000),[COL42] VARCHAR(8000),[COL43] VARCHAR(8000),[COL44] VARCHAR(8000),[COL45] VARCHAR(8000),[COL46] VARCHAR(8000),[COL47] VARCHAR(8000),[COL48] VARCHAR(8000),[COL49] VARCHAR(8000)) ' + CHAR(13) +
--   				  ' INSERT #tabRI_PROC_T1 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE_1)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + CHAR(13) +
--					  ' INSERT #tabRI_PROC_T2 EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE_2)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + CHAR(13) +
--					  ' INSERT #tabBILL SELECT 1,RIGHT(RTRIM([COL37]),3),RTRIM([COL7]),RTRIM([COL9]),1,RTRIM([COL18]),RTRIM([COL20]),RTRIM([COL19]),dbo.[RT_RRO_GET_BNAME]([COL11]),RTRIM([COL12]),RTRIM([COL13]),RTRIM([COL14]),RTRIM([COL15]),RTRIM([COL16]),RTRIM([COL21]),RTRIM([COL22]) FROM #tabRI_PROC_T1 WHERE LEN([COL18])>0 OR LEN([COL20])>0 OR LEN([COL19])>0' + CHAR(13) + CHAR(10) +
--					  ' INSERT #tabBILL SELECT 1,RIGHT(RTRIM([COL37]),3),RTRIM([COL7]),RTRIM([COL9]),2,RTRIM([COL30]),RTRIM([COL32]),RTRIM([COL31]),dbo.[RT_RRO_GET_BNAME]([COL23]),RTRIM([COL24]),RTRIM([COL25]),RTRIM([COL26]),RTRIM([COL27]),RTRIM([COL28]),RTRIM([COL33]),RTRIM([COL34]) FROM #tabRI_PROC_T1 WHERE LEN([COL30])>0 OR LEN([COL32])>0 OR LEN([COL31])>0' + CHAR(13) + CHAR(10) +
--					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),1,RTRIM([COL18]),RTRIM([COL20]),RTRIM([COL19]),dbo.[RT_RRO_GET_BNAME]([COL11]),RTRIM([COL12]),RTRIM([COL13]),RTRIM([COL14]),RTRIM([COL15]),RTRIM([COL16]),RTRIM([COL21]),RTRIM([COL22]) FROM #tabRI_PROC_T2 WHERE LEN([COL18])>0 OR LEN([COL20])>0 OR LEN([COL19])>0' + CHAR(13) + CHAR(10) +
--					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),2,RTRIM([COL30]),RTRIM([COL32]),RTRIM([COL31]),dbo.[RT_RRO_GET_BNAME]([COL23]),RTRIM([COL24]),RTRIM([COL25]),RTRIM([COL26]),RTRIM([COL27]),RTRIM([COL28]),RTRIM([COL33]),RTRIM([COL34]) FROM #tabRI_PROC_T2 WHERE LEN([COL30])>0 OR LEN([COL32])>0 OR LEN([COL31])>0' + CHAR(13) + CHAR(10) +
--					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),3,RTRIM([COL42]),RTRIM([COL44]),RTRIM([COL43]),dbo.[RT_RRO_GET_BNAME]([COL35]),RTRIM([COL36]),RTRIM([COL37]),RTRIM([COL38]),RTRIM([COL39]),RTRIM([COL40]),RTRIM([COL45]),RTRIM([COL46]) FROM #tabRI_PROC_T2 WHERE LEN([COL42])>0 OR LEN([COL44])>0 OR LEN([COL43])>0' + CHAR(13) + CHAR(10) +
--					  ' DROP TABLE #tabRI_PROC_T1' + CHAR(13) + CHAR(10) +
--					  ' DROP TABLE #tabRI_PROC_T2'

SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE_1)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ', @tmp_table = ''' + RTRIM(@vcNameTable) + '1''' + CHAR(13) +
					  ' EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE_2)) + '] @DEL_FCOL=1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ', @tmp_table = ''' + RTRIM(@vcNameTable) + '2''' + CHAR(13) +
					  ' INSERT #tabBILL SELECT 1,RIGHT(RTRIM([COL37]),3),RTRIM([COL7]),RTRIM([COL9]),1,RTRIM([COL18]),RTRIM([COL20]),RTRIM([COL19]),dbo.[RT_RRO_GET_BNAME]([COL11]),RTRIM([COL12]),RTRIM([COL13]),RTRIM([COL14]),RTRIM([COL15]),RTRIM([COL16]),RTRIM([COL21]),RTRIM([COL22]) FROM ' + RTRIM(@vcNameTable) + '1 WHERE LEN([COL18])>0 OR LEN([COL20])>0 OR LEN([COL19])>0' + CHAR(13) + CHAR(10) +
					  ' INSERT #tabBILL SELECT 1,RIGHT(RTRIM([COL37]),3),RTRIM([COL7]),RTRIM([COL9]),2,RTRIM([COL30]),RTRIM([COL32]),RTRIM([COL31]),dbo.[RT_RRO_GET_BNAME]([COL23]),RTRIM([COL24]),RTRIM([COL25]),RTRIM([COL26]),RTRIM([COL27]),RTRIM([COL28]),RTRIM([COL33]),RTRIM([COL34]) FROM ' + RTRIM(@vcNameTable) + '1 WHERE LEN([COL30])>0 OR LEN([COL32])>0 OR LEN([COL31])>0' + CHAR(13) + CHAR(10) +
					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),1,RTRIM([COL18]),RTRIM([COL20]),RTRIM([COL19]),dbo.[RT_RRO_GET_BNAME]([COL11]),RTRIM([COL12]),RTRIM([COL13]),RTRIM([COL14]),RTRIM([COL15]),RTRIM([COL16]),RTRIM([COL21]),RTRIM([COL22]) FROM ' + RTRIM(@vcNameTable) + '2 WHERE LEN([COL18])>0 OR LEN([COL20])>0 OR LEN([COL19])>0' + CHAR(13) + CHAR(10) +
					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),2,RTRIM([COL30]),RTRIM([COL32]),RTRIM([COL31]),dbo.[RT_RRO_GET_BNAME]([COL23]),RTRIM([COL24]),RTRIM([COL25]),RTRIM([COL26]),RTRIM([COL27]),RTRIM([COL28]),RTRIM([COL33]),RTRIM([COL34]) FROM ' + RTRIM(@vcNameTable) + '2 WHERE LEN([COL30])>0 OR LEN([COL32])>0 OR LEN([COL31])>0' + CHAR(13) + CHAR(10) +
					  ' INSERT #tabBILL SELECT 2,RIGHT(RTRIM([COL49]),3),RTRIM([COL7]),RTRIM([COL9]),3,RTRIM([COL42]),RTRIM([COL44]),RTRIM([COL43]),dbo.[RT_RRO_GET_BNAME]([COL35]),RTRIM([COL36]),RTRIM([COL37]),RTRIM([COL38]),RTRIM([COL39]),RTRIM([COL40]),RTRIM([COL45]),RTRIM([COL46]) FROM ' + RTRIM(@vcNameTable) + '2 WHERE LEN([COL42])>0 OR LEN([COL44])>0 OR LEN([COL43])>0' + CHAR(13) + CHAR(10) + 
                 ' DROP TABLE ' + RTRIM(@vcNameTable) + '1 DROP TABLE ' + RTRIM(@vcNameTable) + '2'                
                 

/*
select * from report_forms where code = 'rro'
select * from report_tables where link_form = 2007
RI_PROC_T5278 19063,@del_fcol = 1
sp_help RI_PROC_T5278

select max(link_saved_form) from report_saved_forms where link_form=2007
*/

EXEC(@vcExec)

--SELECT [BDate], [BDateBeg], [BDateEnd]
--FROM #tabBILL
--WHERE ISDATE([BDate])=1 AND ISDATE([BDateBeg])=1 AND ISDATE([BDateEnd])=1

SET DATEFORMAT dmy
 
UPDATE #tabBILL
SET [BClass]    = ISNULL([BClass],''),
	 [BDate]	    = CASE 
                     WHEN ISDATE([BDate])=1 THEN RTRIM(CONVERT(CHAR(10),CONVERT(DATETIME,[BDate]),120))
                     ELSE RTRIM(ISNULL([BDate],''))
                  END,
	 [BNumb]	    = ISNULL([BNumb],''),
	 [BName]	    = ISNULL([BName],''),
	 [BRubric]	 = ISNULL([BRubric],''),
	 [BSubpar]	 = ISNULL([BSubpar],''),
	 [BParagr]	 = ISNULL([BParagr],''),
	 [BPart]	    = ISNULL([BPart],''),
	 [BParticle] = ISNULL([BParticle],'')
WHERE ISDATE([BDate])=1 


UPDATE #tabBILL
SET [BClass]    = ISNULL([BClass],''),
	 [BNumb]	    = ISNULL([BNumb],''),
	 [BName]	    = ISNULL([BName],''),
	 [BRubric]	 = ISNULL([BRubric],''),
	 [BSubpar]	 = ISNULL([BSubpar],''),
	 [BParagr]	 = ISNULL([BParagr],''),
	 [BPart]	    = ISNULL([BPart],''),
	 [BParticle] = ISNULL([BParticle],''),
	 [BDateBeg]  = CASE 
                     WHEN ISDATE([BDateBeg])=1 THEN RTRIM(CONVERT(CHAR(10),CONVERT(DATETIME,[BDateBeg]),120))
                     ELSE RTRIM(ISNULL([BDateBeg],''))
                  END
WHERE ISDATE([BDateBeg])=1 

UPDATE #tabBILL
SET [BClass]    = ISNULL([BClass],''),
	 [BNumb]	    = ISNULL([BNumb],''),
	 [BName]	    = ISNULL([BName],''),
	 [BRubric]	 = ISNULL([BRubric],''),
	 [BSubpar]	 = ISNULL([BSubpar],''),
	 [BParagr]	 = ISNULL([BParagr],''),
	 [BPart]	    = ISNULL([BPart],''),
	 [BParticle] = ISNULL([BParticle],''),
	 [BDateEnd]  = CASE 
                     WHEN ISDATE([BDateEnd])=1 THEN RTRIM(CONVERT(CHAR(10),CONVERT(DATETIME,[BDateEnd]),120))
                     WHEN LEN([BDateEnd]) = 0 THEN '2999-01-01'
                     ELSE RTRIM(ISNULL([BDateEnd],'2999-01-01'))
                  END
WHERE ISDATE([BDateEnd])=1 OR ISNULL([BDateEnd],'') = ''

SET DATEFORMAT ymd
 
insert @tabErrorLog([TXT],[TABLE])
select 'В РО "' + LEFT(Code_Row,16) + '" в графе "' + RTRIm((select name from dbo.report_coloumns RC where RC.link_col = RD.link_col)) + '" встречается некорректный символ ' +  dbo.[RO_CORRECT_SYMBOL](str_val) + ' (код символа ' + STR(ASCII(dbo.[RO_CORRECT_SYMBOL](str_val))) + ') В строке:' + RTRIM(str_val) + ' ( номер символа ' + STR(CHARINDEX(dbo.[RO_CORRECT_SYMBOL](str_val), str_val)) + ')' , 1
from dbo.report_dinamics RD
where link_sf = @iLINK_SAVED_FORM
	and dbo.[RO_CORRECT_SYMBOL](str_val) <> ''



INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + '. В гр. ' +
       CASE [BRank]  
          WHEN 1 THEN '"Наименование и реквизиты нормативного правового акта РФ"'
          WHEN 2 THEN '"Наименование и реквизиты нормативного правового акта субъекта РФ"'
          WHEN 3 THEN '"Наименование и реквизиты нормативного правового акта МО"'
       END + 
       REPLACE(' в частях: ' +
       CASE 
          WHEN LEN([BClass])=0 THEN ', "Тип НПА"'
          ELSE ''
       END +
       CASE 
          WHEN LEN([BDate])=0 THEN ', "Дата принятия НПА"'
          ELSE ''
       END +
       CASE 
          WHEN LEN([BNumb])=0 THEN ', "Номер НПА"'
          ELSE ''
       END +
       CASE 
          WHEN LEN([BName])=0 THEN ', "Полное официальное название НПА"'
          ELSE ''
       END,'в частях: ,','в частях: ') +
       ' пустое значение недопустимо.',
       [TABLE]
FROM #tabBill
WHERE LEN([BClass])=0 OR
      LEN([BDate])=0 OR
      LEN([BNumb])=0 OR
      LEN([BName])=0 

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + '. В гр. ' +
       CASE [BRank]  
          WHEN 1 THEN '"Наименование и реквизиты нормативного правового акта РФ"'
          WHEN 2 THEN '"Наименование и реквизиты нормативного правового акта субъекта РФ"'
          WHEN 3 THEN '"Наименование и реквизиты нормативного правового акта МО"'
       END + 
       ' в части "Дата принятия НПА" неверное значение даты.',
       [TABLE]
FROM #tabBill
WHERE ISDATE([BDate])=0

SELECT CONVERT(DATETIME, [BDate])  AS date, [Gr0], [Gr2],[ORDER], [BRank], [TABLE]
INTO #date    
FROM #tabBill 
WHERE ISDATE([BDate])=1 AND BDATE NOT IN ('.', ',')

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + '. В гр. ' +
       CASE [BRank]  
          WHEN 1 THEN '"Наименование и реквизиты нормативного правового акта РФ"'
          WHEN 2 THEN '"Наименование и реквизиты нормативного правового акта субъекта РФ"'
          WHEN 3 THEN '"Наименование и реквизиты нормативного правового акта МО"'
       END + 
       ' в части "Дата принятия НПА" не может быть меньше 1967 года.',
       [TABLE]
FROM #date A 
WHERE date < 1967

DROP TABLE #date
 
INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Дата вступления в силу НПА" пустое значение недопустимо.',
       [TABLE]
FROM #tabBill
WHERE LEN([BDateBeg])=0

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Дата вступления в силу НПА" неверное значение даты.'+[BDateBeg]+'|'+CAST(ISDATE([BDateBeg]) AS VARCHAR(50))+'|',
       [TABLE]
FROM #tabBill
WHERE ISDATE([BDateBeg])=0

SELECT CONVERT(DATETIME, [BDateBeg])  AS date, [Gr0], [Gr2],[ORDER], [BRank], [TABLE]
INTO #date1    
FROM #tabBill 
WHERE ISDATE([BDateBeg])=1

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Дата вступления в силу НПА" не может быть меньше 1967 года.',
       [TABLE]
FROM #date1 A 
WHERE YEAR(date) < 1967

DROP TABLE #date1


INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Дата прекращения действия НПА " неверное значение даты.',
       [TABLE]
FROM #tabBill
WHERE ISDATE([BDateEnd])=0

SELECT * into #AAAA from #tabBill WHERE ISDATE([BDateEnd])=1

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Дата прекращения действия НПА " значение даты не может превышать 2999-01-01.',
       [TABLE]
FROM #AAAA A
WHERE [BDateEnd] > CONVERT(DATETIME, '29990101', 112) 

DROP TABLE #AAAA 

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Номер абзаца НПА.'+[BRubric]+'  Не может превышать 50 символов',
       [TABLE]
FROM #tabBill
WHERE LEN(BRubric) > 50

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Номер подпункта НПА.'+[BSubpar]+'  Не может превышать 50 символов',
       [TABLE]
FROM #tabBill
WHERE LEN(BSubpar) > 50

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Номер пункта НПА.'+[BParagr]+'  Не может превышать 50 символов',
       [TABLE]
FROM #tabBill
WHERE LEN(BParagr) > 50

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Номер части НПА.'+[BPart]+'  Не может превышать 50 символов',
       [TABLE]
FROM #tabBill
WHERE LEN(BPart) > 50

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT 'Код ' + RTRIM(LTRIM([Gr0] + ' ' + [Gr2])) +
       CASE 
          WHEN dbo.[RA_ISNUMERIC]([ORDER])=1 THEN ', стр.' + LTRIM(STR(CAST([ORDER] AS INT)+1))
          ELSE ''
       END + ', гр. "Номер статьи НПА.'+[BParticle]+'  Не может превышать 50 символов',
       [TABLE]
FROM #tabBill
WHERE LEN(BParticle) > 50

/*
45256	4.9.   
select * from report_dinamics where link_sf=19071
delete report_dinamics where link_sf=19071 and code_row='1.1.   РС-А-0100039' and link_col=45249
delete report_dinamics where link_sf=19071 and code_row='1.1.   РС-А-0100001' and link_col in (45237)
delete report_dinamics where link_sf=19071 and code_row='4.9.   РС-Г-0900000' and link_col in (45256)

select * from report_coloumns where link_col=45256
RI_PROC_T5278 19071, @del_fcol=1


*/

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

SET @vcExec = 'EXEC dbo.[RI_PROC_T' + RTRIM(LTRIM(@iLINK_TABLE_3)) + '] ' + STR(@iLINK_SAVED_FORM) + ', @tmp_table = ''' + @vcNameTable + '''' + 
	      	  ' INSERT #tabAttr([CODE],[NAME],[VAL]) SELECT [CODE],RTRIM([COL1]),[COL2] FROM ' + @vcNameTable + ' WHERE ISNULL([FCOL2],'''')<>''ЗАПРЕТ()'' ' 

--SET @vcExec = '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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(8000),[FCOL2] VARCHAR(50),[COL3] VARCHAR(8000),[ITOG] INT) ' +
--        		  'INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T' + RTRIM(LTRIM(@iLINK_TABLE_3)) + '] ' + STR(@iLINK_SAVED_FORM) + 
--	      	  ' INSERT #tabAttr([CODE],[NAME],[VAL]) SELECT [CODE],RTRIM([COL1]),[COL2] FROM #tabRI_PROC_T WHERE ISNULL([FCOL2],'''')<>''ЗАПРЕТ()'' DROP TABLE #tabRI_PROC_T' 

--print '----------------------------------------------------------------------------------------------------------------------'
EXEC(@vcExec)
UPDATE #tabAttr 
SET [VAL] = ISNULL(LEFT((SELECT TOP 1 RTRIM(ISNULL([POST],'')) FROM dbo.[RA_GET_USER_INFO](NULL)),50),'')
WHERE [CODE] = 'CLERK_SHIP_DN' AND
      LEN(ISNULL([VAL],'')) = 0

UPDATE #tabAttr 
SET [VAL] = ISNULL(LEFT((SELECT TOP 1 RTRIM(ISNULL([C].[FM],''))+' '+RTRIM(ISNULL([C].[IM],''))+' '+RTRIM(ISNULL([C].[OT],''))
  			                FROM dbo.[RA_GET_USER_INFO](NULL) [A] 
			                JOIN dbo.[EMPL] [B] ON [A].[EMPL_LINK] = [B].[LINK]
				             JOIN dbo.[PERSON] [C] ON [C].[LINK] = [B].[PERS_LINK]),70),'')
WHERE [CODE] = 'FULL_NAME_DN' AND
      LEN(ISNULL([VAL],'')) = 0

UPDATE #tabAttr 
SET [VAL] = ISNULL(LEFT((SELECT TOP 1 RTRIM(dbo.[RA_GETWORDNUM](ISNULL([PHONES],''),1,','))
								 FROM dbo.[RA_GET_USER_INFO](NULL)),20),'')
WHERE [CODE] = 'PHONE_DN' AND
      LEN(ISNULL([VAL],'')) = 0

INSERT @tabCheckedCodes([CODE])
SELECT [CODE] = 'CODE_SUBJ' UNION 
SELECT 'NAME_SUBJ' UNION
SELECT 'EMAIL' UNION
SELECT 'DATE_OPERATION' UNION
SELECT 'TYPE_INF' UNION
SELECT '58701_SIGNER_POST' UNION
SELECT '58701_SIGNER_FN' UNION
SELECT '58701_CLERK_SHIP' UNION
SELECT '58701_CLERK_FN' UNION
SELECT '58701_PHONE' UNION
SELECT '58701_DATE_SPP' UNION
SELECT '58702_SIGNER_POST' UNION
SELECT '58702_SIGNER_FN' UNION
SELECT '58702_CLERK_SHIP' UNION
SELECT '58702_CLERK_FN' UNION
SELECT '58702_PHONE' UNION
SELECT '58702_DATE_SPP' UNION
SELECT '58703_SIGNER_POST' UNION
SELECT '58703_SIGNER_FN' UNION
SELECT '58703_CLERK_SHIP' UNION
SELECT '58703_CLERK_FN' UNION
SELECT '58703_PHONE' UNION
SELECT '58703_DATE_SPP' UNION
SELECT 'CLERK_SHIP_DN' UNION
SELECT 'FULL_NAME_DN' UNION
SELECT 'PHONE_DN'

INSERT @tabErrorLog([TXT],[TABLE]) 
SELECT CASE 
          WHEN LEFT([A].[CODE],3)='587' THEN 'Подписание документа ' + LEFT([A].[CODE],5) +': '
          ELSE ''
       END + 
       'Для стр. "' + [A].[NAME] +'" пустое значение недопустимо.',
       3
FROM #tabAttr         [A]
JOIN @tabCheckedCodes [B] ON [A].[CODE]=[B].[CODE]
WHERE LEN(ISNULL([A].[VAL],''))=0



     
--------------------------------------------------------------------------------------------------------------------------------------------------------
IF EXISTS(SELECT * FROM @tabErrorLog WHERE [TABLE] = 1)
BEGIN
   INSERT #tabExportLog([TXT]) VALUES ('Анализ таблицы 1: "Реестр расходных обязательств субъекта Российской Федерации":')

   INSERT #tabExportLog([TXT]) 
   SELECT 'ОШИБКА: ' + [TXT]
   FROM @tabErrorLog 
   WHERE [TABLE] = 1
   ORDER BY [ORDER]

   INSERT #tabExportLog([TXT]) VALUES ('')
END

IF EXISTS(SELECT * FROM @tabErrorLog WHERE [TABLE] = 2)
BEGIN
   INSERT #tabExportLog([TXT]) VALUES ('Анализ таблицы 2: "Свод реестров расходных обязательств муниципальных образований, входящих в состав субъекта Российской Федерации":')

   INSERT #tabExportLog([TXT]) 
   SELECT 'ОШИБКА: ' + [TXT]
   FROM @tabErrorLog 
   WHERE [TABLE] = 2
   ORDER BY [ORDER]

   INSERT #tabExportLog([TXT]) VALUES ('')
END

IF EXISTS(SELECT * FROM @tabErrorLog WHERE [TABLE] = 3)
BEGIN
   INSERT #tabExportLog([TXT]) VALUES ('Анализ таблицы 3: "Служебная информация":')

   INSERT #tabExportLog([TXT]) 
   SELECT 'ОШИБКА: ' + [TXT]
   FROM @tabErrorLog 
   WHERE [TABLE] = 3
   ORDER BY [ORDER]

   INSERT #tabExportLog([TXT]) VALUES ('')
END


IF EXISTS(SELECT * 
          FROM @tabErrorLog)
BEGIN
   SET @bCancel = 1
   INSERT #tabExportLog([TXT]) VALUES ('Выгрузка отменена. Устраните ошибки и повторите выгрузку.')
END
ELSE BEGIN
   SET @bCancel = 0
END
   

RETURN 0

DROP TABLE #tabAttr 
--DROP TABLE #tabRRO1
--DROP TABLE #tabRRO2
DROP TABLE #tabBill

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

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))
*/



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 = '2009' BEGIN

		SET @TITLE = @TITLE + ' на конец 2009г.'

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

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


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

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


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

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


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

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


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

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

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

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

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

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

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '9 МАЯ (ДЕНЬ ПОБЕДЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '12 ИЮНЯ (ДЕНЬ РОССИИ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', '', 'SALARY'

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ

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

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '30 АПРЕЛЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '8 МАЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '3 НОЯБРЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '31 ДЕКАБРЯ', '', 'SALARY'

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

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '6 ЯНВАРЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '8 ЯНВАРЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '9 ЯНВАРЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '9 МАРТА', '', 'SALARY'
		UNION ALL SELECT @TITLE, '11 МАЯ', '', 'SALARY'


		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','ф'))
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА 2009 ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'11 ЯНВАРЯ (РАБОЧИЙ ДЕНЬ!)', 11, 1, @TD_LINK, 3

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '11 ЯНВАРЯ', '', 'SALARY'

	END --IF @CODE = '2009' BEGIN


	IF @CODE = '2010' BEGIN

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

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

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


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

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


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

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


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

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


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

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

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

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

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

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

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

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

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

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '9 МАЯ (ДЕНЬ ПОБЕДЫ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '12 ИЮНЯ (ДЕНЬ РОССИИ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', '', 'SALARY'

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		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)
			SELECT	'27 ФЕВРАЛЯ', 27, 2, @TD_LINK, 2
			UNION ALL
			SELECT	'30 АПРЕЛЯ', 30, 4, @TD_LINK, 2
			UNION ALL
			SELECT	'11 ИЮНЯ', 11, 6, @TD_LINK, 2
			UNION ALL
			SELECT	'3 НОЯБРЯ', 3, 11, @TD_LINK, 2
			UNION ALL
			SELECT	'31 ДЕКАБРЯ', 31, 12, @TD_LINK, 2

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '27 ФЕВРАЛЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '30 АПРЕЛЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '11 ИЮНЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '3 НОЯБРЯ', '', 'SALARY'
		UNION ALL SELECT @TITLE, '31 ДЕКАБРЯ', '', 'SALARY'

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		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	'6 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО СО 2 ЯНВАРЯ)', 6, 1, @TD_LINK, 3
			UNION ALL
			SELECT	'8 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО С 3 ЯНВАРЯ)', 8, 1, @TD_LINK, 3
			UNION ALL
			SELECT	'22 ФЕФРАЛЯ (ПЕРЕНОС ВЫХОДНОГО С 27 ФЕВРАЛЯ)', 22, 2, @TD_LINK, 3
			UNION ALL
			SELECT	'3 МАЯ (ПЕРЕНОС ВЫХОДНОГО С 1 МАЯ)', 3, 5, @TD_LINK, 3						
			UNION ALL
			SELECT	'10 МАЯ (ПЕРЕНОС ВЫХОДНОГО С 9 МАЯ)', 10, 5, @TD_LINK, 3						
			UNION ALL
			SELECT	'14 ИЮНЯ (ПЕРЕНОС ВЫХОДНОГО С 12 ИЮНЯ)', 14, 6, @TD_LINK, 3									
			UNION ALL			
			SELECT	'5 НОЯБРЯ (ПЕРЕНОС ВЫХОДНОГО С 13 НОЯБРЯ)', 5, 11, @TD_LINK, 3

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '6 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО СО 2 ЯНВАРЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '8 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО С 3 ЯНВАРЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '22 ФЕФРАЛЯ (ПЕРЕНОС ВЫХОДНОГО С 27 ФЕВРАЛЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '3 МАЯ (ПЕРЕНОС ВЫХОДНОГО С 1 МАЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '10 МАЯ (ПЕРЕНОС ВЫХОДНОГО С 9 МАЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '14 ИЮНЯ (ПЕРЕНОС ВЫХОДНОГО С 12 ИЮНЯ)', '', 'SALARY'
		UNION ALL SELECT @TITLE, '5 НОЯБРЯ (ПЕРЕНОС ВЫХОДНОГО С 13 НОЯБРЯ)', '', 'SALARY'

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','ф'))
		IF COALESCE(@TD_LINK,0) > 0
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'13 НОЯБРЯ (РАБОЧИЙ ДЕНЬ!)', 13, 11, @TD_LINK, 3

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

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '13 НОЯБРЯ (РАБОЧИЙ ДЕНЬ!)', '', 'SALARY'

	END --IF @CODE = '2010' BEGIN
	
	IF @CODE = '2011' BEGIN

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

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

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


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

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


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

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


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

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


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

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

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

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

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

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

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

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

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

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'5 МАРТА', 5, 3, @TD_LINK, 2, 7, 3
			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)
			SELECT	'6 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО С 1 ЯНВАРЯ)', 6, 1, @TD_LINK, 3
			UNION ALL
			SELECT	'10 ЯНВАРЯ (ПЕРЕНОС ВЫХОДНОГО СО 2 ЯНВАРЯ)', 10, 1, @TD_LINK, 3
			UNION ALL
			SELECT	'7 МАРТА (ПЕРЕНОС ВЫХОДНОГО С 5 МАРТА)', 7, 3, @TD_LINK, 3
			UNION ALL
			SELECT	'2 МАЯ (ПЕРЕНОС ВЫХОДНОГО С 1 МАЯ)', 2, 5, @TD_LINK, 3						
			UNION ALL
			SELECT	'13 ИЮНЯ (ПЕРЕНОС ВЫХОДНОГО С 12 ИЮНЯ)', 13, 6, @TD_LINK, 3									

		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
		--	INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
		--	SELECT	'13 НОЯБРЯ (РАБОЧИЙ ДЕНЬ!)', 13, 11, @TD_LINK, 3

		--SET @TITLE = 'Установлены переносы рабочих дней'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, '13 НОЯБРЯ (РАБОЧИЙ ДЕНЬ!)', '', 'SALARY'

	END --IF @CODE = '2011' BEGIN	

	IF @CODE = '2012' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2012г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2326.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2326.00', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '4651.99'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 4651.99', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 9303.99', '', 'SALARY'


		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 9303.99', '', 'SALARY'


		--Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 42666.66', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам                                                                                                                                                             
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 42666.66', '', 'SALARY'
		
		--Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 38583.33', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 38583.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'28 АПРЕЛЯ (предпраздничный день за 30 апреля)', 28, 4, @TD_LINK, 2, 30, 4
			UNION ALL
			SELECT	'9 ИЮНЯ (предпраздничный день за 11 июня)', 9, 6, @TD_LINK, 2, 11, 6
			UNION ALL
			SELECT	'29 ДЕКАБРЯ (предпраздничный день за 31 декабря)', 29, 12, @TD_LINK, 2, 31, 12
			UNION ALL
			SELECT	'12 МАЯ (предпраздничный день за 8 мая)', 12, 5, @TD_LINK, 2, 8, 5

		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'6 ЯНВАРЯ (перенос выходного с 1 января)', 6, 1, @TD_LINK, 3, 1, 1
			UNION ALL
			SELECT	'9 ЯНВАРЯ (перенос выходного с 7 января)', 9, 1, @TD_LINK, 3, 7, 1
			UNION ALL
			SELECT	'9 МАРТА (перенос выходного с 11 марта)', 9, 3, @TD_LINK, 3, 11, 3
			UNION ALL
			SELECT	'30 АПРЕЛЯ (перенос выходного с 28 апреля)', 30, 4, @TD_LINK, 3, 28, 4			
			UNION ALL
			SELECT	'7 МАЯ (перенос выходного с 5 мая)', 7, 5, @TD_LINK, 3, 5, 5			
			UNION ALL
			SELECT	'8 МАЯ (перенос выходного с 12 мая)', 8, 5, @TD_LINK, 3, 12, 5			
			UNION ALL			
			SELECT	'11 ИЮНЯ (перенос выходного с 9 июня)', 11, 6, @TD_LINK, 3, 9, 6									
			UNION ALL
			SELECT	'5 НОЯБРЯ (перенос выходного с 4 ноября)', 5, 11, @TD_LINK, 3, 4, 11
			UNION ALL
			SELECT	'31 ДЕКАБРЯ (перенос выходного с 29 декабря)', 31, 12, @TD_LINK, 3, 29, 12			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5

		END
		
		SET @TITLE = 'Установлены переносы рабочих дней'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '11 МАРТА (рабочий день за 9 марта)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '28 АПРЕЛЯ (рабочий день за 30 апреля)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '5 МАЯ (рабочий день за 7 мая)', '', 'SALARY'

	END --IF @CODE = '2012' BEGIN	

END


GO


GRANT EXECUTE ON dbo.[SA_SET_STATIC_NASTR] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_REP_FUR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_REP_FUR]

GO


CREATE   PROCEDURE [dbo].SA_REP_FUR @LINK_DOC INT
AS

declare @OBJ_CODE varchar(254), @SR_VID INT, @AvgDays NUMERIC(18,2), @PAYMENT INT, @PER INT, @DATE_BEG DATETIME, @LINK_EMPL INT, @LINK_PAYS INT 
Set @OBJ_CODE = (Select top 1 O.CODE from dbo.sdoc D inner join S_OBJECTS O on D.OBJECT = O.LINK and D.LINK = @LINK_DOC)

Select top 1 @SR_VID = [TYPE], @PAYMENT = [PAYMENT], @PER = [TYP_PERIOD], @DATE_BEG = DATE1, @LINK_EMPL = LINK_EMPL, @LINK_PAYS = LINK_PAY
from SDOC_AVAC where LINK_UP = @LINK_DOC

--
DECLARE @LINK_DEP INT
select @LINK_DEP = LINK_DEP from SDOC where LINK = @LINK_DOC

SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29,4)

Select  NAME_DOC = 'Расчет отпускных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_ADD_FUR C 
	INNER JOIN dbo.item_vacation iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = 'Расчет командировочных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_TRAVEL C 
	INNER JOIN dbo.item_travel iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = CASE WHEN TYPE = 1 THEN 'Расчет компенсации за неиспользованный отпуск №' else 'Расчет по среднему №' end + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = '',
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_AVG C 
where C.LINK = @LINK_DOC


DECLARE @SCRIPT1 VARCHAR(8000), 
	@I INT, 
	@DATE_BEGIN_RP DATETIME,
	@RP_SUMMA_PREM NUMERIC(18,2),
	@RP_SUMMA_MAT NUMERIC(18,2),
	@RP_SUMMA NUMERIC(18,2),
	@SR_PREM NUMERIC(18,2),
	@RP_DAYS INT,
	@RP_HOURS NUMERIC(18,2),
	@RP_DAYS_N INT,
	@RP_HOURS_N NUMERIC(18,2),
	@SUMMA_BASE0 NUMERIC(18,2),
	@ITOGO_DNI NUMERIC(6,2),
	@ITOGO_CH NUMERIC(18,2),
	@INSTR TINYINT,
	@SYST_PAY TINYINT

SELECT  @SCRIPT1 = '', @I = 1, @DATE_BEGIN_RP = DATE_PER,
	@RP_SUMMA_PREM = RP_SUMMA_PREM, @RP_SUMMA_MAT = RP_SUMMA_MAT, @RP_SUMMA = RP_SUMMA, 
	@SR_PREM = SR_PREM, @SYST_PAY = SYST_PAY,
	@RP_DAYS = RP_DAYS,	@RP_HOURS = RP_HOURS,
	@RP_DAYS_N = RP_DAYS_N , @RP_HOURS_N = RP_HOURS_N,
	@SUMMA_BASE0 = SUMMA_BASE, @ITOGO_DNI = ITOGO_DNI, @ITOGO_CH = ITOGO_CH,
	@INSTR = INSTR
FROM 	(
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_ADD_FUR where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_TRAVEL where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_AVG where LINK = @LINK_DOC
	) DOC


---начисление по видам оплат
DECLARE @COUNT_M INT
SET @COUNT_M = COALESCE((Select COUNT(DISTINCT PERIOD) from SDOC_AVAC_TABLE2 where LINK_UP = @LINK_DOC),0) - (CASE WHEN @INSTR = 2 THEN 1 ELSE 0 END)
SET @COUNT_M = CASE WHEN @COUNT_M <= 0 THEN 1 ELSE @COUNT_M END
SET @COUNT_M = CASE WHEN @COUNT_M > 12 THEN 12 ELSE @COUNT_M END


IF EXISTS (Select LINK_UP from dbo.SDOC_AVAC_TABLE3 T3 where LINK_UP = @LINK_DOC)
BEGIN

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 + '+ COALESCE(SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',0)'
		SET @I = @I + 1
	END

	SET @SCRIPT1 = 'Select ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
END
ELSE
BEGIN --Если вручную заполнили суммы по месяцам, а по видам начислений данных нет

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = 0.00'
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	SET @SCRIPT1 = 'Select ORDERS=0, LINK_PAY=0, NAME_PAY = '''', LINK_KBK=0, CODE_KBK = '''' ' + @SCRIPT1 

END

exec (@SCRIPT1)

--Коэффициенты индексации
IF (	COALESCE((Select COUNT(distinct koef1) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef1,0) > 0 group by link_up having count(koef1) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef2) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef2,0) > 0 group by link_up having count(koef2) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef3) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef3,0) > 0 group by link_up having count(koef3) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef4) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef4,0) > 0 group by link_up having count(koef4) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef5) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef5,0) > 0 group by link_up having count(koef5) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef6) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef6,0) > 0 group by link_up having count(koef6) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef7) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef7,0) > 0 group by link_up having count(koef7) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef8) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef8,0) > 0 group by link_up having count(koef8) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef9) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef9,0) > 0 group by link_up having count(koef9) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef10) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef10,0) > 0 group by link_up having count(koef10) > 0),1)
	*COALESCE((Select COUNT(distinct koef11) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef11,0) > 0 group by link_up having count(koef11) > 0),1)
	*COALESCE((Select COUNT(distinct koef12) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef12,0) > 0 group by link_up having count(koef12) > 0),1) 
)  = 1 
BEGIN

	SET  @SCRIPT1 = 'Select distinct INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS = 1, NAME_PAY = ''для всех начислений'', CODE_KBK = ''для всех источников''' 
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = MAX(COALESCE(koef' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',1))'
		SET @I = @I + 1
	END
	SET  @SCRIPT1 = @SCRIPT1 + ' from dbo.SDOC_AVAC_TABLE3 where LINK_UP = ' + CONVERT(VARCHAR(20),@LINK_DOC)
	exec (@SCRIPT1)

END
ELSE BEGIN

	SET  @SCRIPT1 = ''
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = KOEF' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END
	
	SET @SCRIPT1 = 'Select INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
	
	exec (@SCRIPT1)
END

		

DECLARE @DAYS_SZ NUMERIC(18,2)
--- Время за расчетный период
SELECT  [PERIOD],
	[DAYS_N] = MAX(DAYS_N) ,
	[HOURS_N] = MAX(HOURS_N),
	[DAYS] = MAX(DAYS) ,
	[HOURS] = MAX(HOURS),
	[KDAYS] = MAX(KDAYS),
	[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
INTO #TMP
FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
GROUP BY [PERIOD]

SELECT  
	@DAYS_SZ = SUM(
		CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
				CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
			ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END
		ELSE --В календарных днях
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
			ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END				
		END)
FROM #TMP

---начисление по месяцам
Select ORDERS, PERIOD, SUMMA, PREM, MATER, 
	DAYS = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS END, 
	HOURS, 
	DAYS_N = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS_N END, 
	HOURS_N, CODE_KBK = KBK.CODE, 
	RP_S_PREM = @RP_SUMMA_PREM, RP_SUMMA = @RP_SUMMA, RP_S_MAT = @RP_SUMMA_MAT, 
	RP_DAYS = @RP_DAYS,	RP_HOURS = @RP_HOURS,
	RP_DAYS_N = @RP_DAYS_N,	RP_HOURS_N = @RP_HOURS_N,
	SR_PREM = @SR_PREM, DSUM = @SUMMA_BASE0,
	SUM_DSZ = @DAYS_SZ,
	KOEF = 
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN 1 else 1.2 END
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
	CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			1
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,
	DAYS_SZ = ROUND(
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
		ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
		ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,2)
from SDOC_AVAC_TABLE2 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC
ORDER BY PERIOD

---

DECLARE @FURLOUGH_OPT11 int -- Расчет с учетом районного коэффициента
SET @FURLOUGH_OPT11 = dbo.sa_get_option_by_code('FURLOUGH_OPT11')
---Накручиваем северный коэффициент, если надо
DECLARE @FURLOUGH_GOS_OPT5 int -- Расчет с учетом северного коэффициента
SET @FURLOUGH_GOS_OPT5 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT5')

DECLARE @FURLOUGH_GOS_OPT4 varchar(10) --Дата применения районного коэффициента к мат. помощи
SET @FURLOUGH_GOS_OPT4 = COALESCE((SELECT VALUE FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('FURLOUGH_GOS_OPT4'))) AND SID IS NULL),'')
SET @FURLOUGH_GOS_OPT4 = CASE WHEN @FURLOUGH_GOS_OPT4 LIKE '%.  .%' THEN '' ELSE @FURLOUGH_GOS_OPT4 END

SET @FURLOUGH_GOS_OPT4 = CASE WHEN LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) = '' THEN '01.01.1900' else LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) END


select INSTR = @INSTR, CODE_PAYS = P.CODE, NAME_PAYS = P.NAME, S.SUMMA,
	RAION_S = S.SUMMA *
	CASE WHEN @FURLOUGH_OPT11 = 1 THEN
		CASE WHEN WAY_CALC = 12
			THEN (CASE WHEN @DATE_BEG >= CONVERT(DATETIME,@FURLOUGH_GOS_OPT4,104) THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100  ELSE 1 END) 
			ELSE DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100
		END
	ELSE 0
	END,
	NORHT_S = S.SUMMA * CASE WHEN @FURLOUGH_GOS_OPT5 = 1 THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,2) / 100 ELSE 0 END
INTO #TMPA
from 
	dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEG, DEFAULT, @LINK_DEP) S
	inner join dbo.pays P on s.link_pay = p.link
where 
	WAY_CALC not in (6, 7, 12)
	AND
	s.link_pay IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)

IF NOT EXISTS (SELECT * FROM #TMPA)
	INSERT INTO #TMPA (INSTR, CODE_PAYS, NAME_PAYS) 
	VALUES (1, '', '')

SELECT * FROM #TMPA

---начисление по расчету
Select ORDERS, DATE1, DATE2, DAYS, HOURS, SR_ZP, SUMMA, 
	CODE_KBK = KBK.CODE, ITOGO_DNI = @ITOGO_DNI, ITOGO_CH = @ITOGO_CH
from SDOC_AVAC_TABLE1 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC 





GO


GRANT EXECUTE ON dbo.[SA_REP_FUR] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_RSV1_EXPORT_0700_2012]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_RSV1_EXPORT_0700_2012]

GO


CREATE      PROCEDURE [dbo].SA_RSV1_EXPORT_0700_2012 ( @Link int /*Ссылка на расчет*/ ) 
AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254), @WORK_END varchar(1)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------

DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1, 
	RIGHT(REPLICATE('0',12) + LTRIM(RTRIM(DD1.INN)), 12) AS INN1, 
	DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15) AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	OGRN = RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15),
	DD1.OKATO,
	DD1.OKVED,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = '01',
	TFOMS_KTI = '03',
	WORK_END = '1'
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @Cur0 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @Cur CURSOR, @Cur1 CURSOR, @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254),
		@CurI0 CURSOR,@CurI CURSOR, @CurI1 CURSOR

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),@YEAR) + '-ORG-' + RTRIM(LTRIM(COALESCE(PFNUMBER,''))) + '-DCK-00001-DPT-000000-DCK-00000.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
	    UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
	    UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="Единичный запрос">'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_СВ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_НАЧИНАЯ_С_2012_ГОДА>'
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерПФР>' + LTRIM(RTRIM(ISNULL(PFNUMBER,''))) + '</РегистрационныйНомерПФР>'  + CHAR(10) +
								  SPACE(3) + '<НомерКорректировки>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@Version),''))) + '</НомерКорректировки>'  + CHAR(10) +
								  SPACE(3) + '<КодОтчетногоПериода>' + CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END +'</КодОтчетногоПериода>' + CHAR(10) +
								  SPACE(3) + '<КалендарныйГод>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@YEAR),''))) + '</КалендарныйГод> ' + CHAR(10) +
							      CASE WHEN LTRIM(RTRIM(ISNULL(@WORK_END,''))) = 'Л' THEN
										SPACE(3) + '<ПрекращениеДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(1),WORK_END),''))) + '</ПрекращениеДеятельности> ' + CHAR(10)
								  ELSE '' END
	   FROM #DEP_DATA						   

	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL(FULL_NAME,''))) + '</НаименованиеОрганизации>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерТФОМС>' + LTRIM(RTRIM(ISNULL(TFOMS_RNUM,''))) + '</РегистрационныйНомерТФОМС>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ИНН>' + LTRIM(RTRIM(ISNULL(INN1,''))) + '</ИНН>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КПП>' + LTRIM(RTRIM(ISNULL(KPP1,''))) + '</КПП>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОГРН>' + LTRIM(RTRIM(ISNULL(OGRN1,''))) + '</ОГРН>' FROM #DEP_DATA 
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКАТО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKATO,''))),SPACE(1),'') + '</КодПоОКАТО>' 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) + '<Номер>'+ 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) + '<Номер>'+ 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) + '<Номер>'+ 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) + '<КоличествоСтраниц>6</КоличествоСтраниц>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '<КоличествоЛистовПриложения>0</КоличествоЛистовПриложения>'

----- стр.2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел1РасчетПоНачисленнымУплаченным>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаНачалоРасчетногоПериода2012>'
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) + '<СтраховыеВзносыТФОМС>'+ 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*/) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаНачалоРасчетногоПериода2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<НачисленоСначалаРасчетногоПериода2012>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2012>' WHEN 6 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2012>' ELSE  SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2012>' 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),''))) + '</СтраховыеВзносыОМС>'	+ 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) + '</ВсегоСначалаРасчетногоПериода2012>' WHEN 6 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2012>' ELSE  SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2012>' 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,4,5/*,6*/)  ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</НачисленоСначалаРасчетногоПериода2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериода2012>'
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) + '<СтраховыеВзносыТФОМС>'+ 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*/) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ДоначисленоСначалаРасчетногоПериода2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВсегоКуплате2012>'
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) + '<СтраховыеВзносыТФОМС>'+ 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,5/*,6*/) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВсегоКуплате2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<УплаченоСначалаРасчетногоПериода2012>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 9 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2012>' WHEN 13 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2012>' ELSE  SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 9))) + 'с2012>' 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),''))) + '</СтраховыеВзносыОМС>' + CHAR(10) +			
	--WHEN 6 THEN SPACE(6) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'  + CHAR(10) +	
		 CASE T.ROW WHEN 9 THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода2012>' WHEN 13 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2012>' ELSE  SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 9))) + 'с2012>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (9,10,11,12,13) AND T.COL IN (3,4,5/*,6*/)  ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</УплаченоСначалаРасчетногоПериода2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВтомЧислеЗаПредыдущиеРасчетныеПериоды2012>'
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) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 14, DEFAULT) T WHERE T.COL IN (3,4,5/*,6*/) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВтомЧислеЗаПредыдущиеРасчетныеПериоды2012>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаКонецРасчетногоПериода2012>'
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) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 15, DEFAULT) T WHERE T.COL IN (3,4,5/*,6*/) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаКонецРасчетногоПериода2012>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел1РасчетПоНачисленнымУплаченным>'	

-----Разделы 2
CREATE TABLE #TABLES (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES 
		SELECT 3,'Раздел2РасчетПоТарифу'
--UNION	SELECT 4,'РасчетСтраховыхВзносовПоПониженномуТарифу'

CREATE TABLE #STR_2_2R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_2R 
		SELECT 1,3,'НаОбязательноеПенсионноеСтрахование'
UNION	SELECT 2,3,'НаОбязательноеМедицинскоеСтрахование'

--UNION	SELECT 2,4,'НачисленоСтраховыхВзносовВпользуРаботниковИнвалидов'
--UNION	SELECT 3,4,'РасчетПоВыплатамРаботникамЕНВД' WHERE @YEAR <= 2010
--UNION	SELECT 4,4,'НачисленоСтраховыхВзносовВпользуРаботниковЕНВД' WHERE @YEAR <= 2010

CREATE TABLE #STR_2_2B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_2B 
		SELECT 1,1,'ВыплатыИвознаграждения_1966старше'
UNION	SELECT 2,1,'ВыплатыИвознаграждения_1967моложе'
UNION	SELECT 3,1,'ВыплатыИвознаграждения_ВременноИГ'
UNION	SELECT 4,1,'НеПодлежащиеОбложению_1966старше'
UNION	SELECT 5,1,'НеПодлежащиеОбложению_1967моложе'
UNION	SELECT 6,1,'НеПодлежащиеОбложению_ВременноИГ'
UNION	SELECT 7,1,'СуммаРасходовПринимаемыхКвычету_1966старше'
UNION	SELECT 8,1,'СуммаРасходовПринимаемыхКвычету_1967моложе'
UNION	SELECT 9,1,'СуммаРасходовПринимаемыхКвычету_ВременноИГ'
UNION	SELECT 11,1,'ПревышающиеПредельнуюВеличинуБазы_1966старше'
UNION	SELECT 12,1,'ПревышающиеПредельнуюВеличинуБазы_1967моложе'
UNION	SELECT 13,1,'ПревышающиеПредельнуюВеличинуБазы_ВременноИГ'
UNION	SELECT 14,1,'БазаДляНачисленияСтраховыхВзносовНаОПС_1966старше'
UNION	SELECT 15,1,'БазаДляНачисленияСтраховыхВзносовНаОПС_1967моложе'
UNION	SELECT 16,1,'НачисленоНаОПСстраховая'
UNION	SELECT 17,1,'НачисленоНаОПСнакопительная'
UNION	SELECT 18,1,'НачисленоНаОПСсСуммПревышающих'
UNION	SELECT 19,1,'КоличествоФЛпоКоторымБазаПревысилаПредел'
UNION	SELECT 20,2,'СуммаВыплатИвознаграждений'
UNION	SELECT 21,2,'НеПодлежащиеОбложению'
UNION	SELECT 22,2,'СуммаРасходовПринимаемыхКвычету'
UNION	SELECT 23,2,'ПревышающиеПредельнуюВеличинуБазы'
UNION	SELECT 24,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
UNION	SELECT 25,2,'НачисленоНаОМС'
/*UNION	SELECT 19,3,'ВыплатыИвознаграждения_1966старше'
UNION	SELECT 20,3,'ВыплатыИвознаграждения_1967моложе'
UNION	SELECT 21,3,'ВыплатыИвознаграждения_ВременноИГ'
UNION	SELECT 22,3,'НеПодлежащиеОбложению_1966старше'
UNION	SELECT 23,3,'НеПодлежащиеОбложению_1967моложе'
UNION	SELECT 24,3,'НеПодлежащиеОбложению_ВременноИГ'
UNION	SELECT 25,3,'СуммаРасходовПринимаемыхКвычету_1966старше'
UNION	SELECT 26,3,'СуммаРасходовПринимаемыхКвычету_1967моложе'
UNION	SELECT 27,3,'СуммаРасходовПринимаемыхКвычету_ВременноИГ'
UNION	SELECT 28,3,'ПревышающиеПредельнуюВеличинуБазы_1966старше'
UNION	SELECT 29,3,'ПревышающиеПредельнуюВеличинуБазы_1967моложе'
UNION	SELECT 30,3,'ПревышающиеПредельнуюВеличинуБазы_ВременноИГ'
UNION	SELECT 31,4,'БазаДляНачисленияСтраховыхВзносовНаОПС_1966старше'
UNION	SELECT 32,4,'БазаДляНачисленияСтраховыхВзносовНаОПС_1967моложе'
UNION	SELECT 33,4,'НачисленоНаОПСстраховая'
UNION	SELECT 34,4,'НачисленоНаОПСнакопительная'
UNION	SELECT 35,4,'НачисленоНаОПСсСуммПревышающих'
UNION	SELECT 36,4,'КоличествоФЛпоКоторымБазаПревысилаПредел'
*/
--select @TAB_NAME= TAB_NAME from  #TABLES order by NUM

--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<' + @TAB_NAME + '>'

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 + '>'
		--- Рабочие  тариф 01
		IF @TAB_NUM = 3
			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_2R 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 @Cur1 = CURSOR FORWARD_ONLY
				FOR select NUM, BLOK_NAME from #STR_2_2B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
				OPEN @Cur1
				FETCH NEXT FROM @Cur1 INTO @NUM, @BLOK_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN
						if @num = 19 
						begin
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @BLOK_NAME + '>'
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME, 
									CASE WHEN T.COL = 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
										 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
									ELSE SPACE(6) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
									END				
								FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @BLOK_NAME + '>'
						end
						else begin
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @BLOK_NAME + '>'
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME, 
									CASE WHEN T.COL = 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.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
									ELSE SPACE(7) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
									END				
								FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @BLOK_NAME + '>'
						end
					END
					FETCH NEXT FROM @Cur1 INTO @NUM, @BLOK_NAME
				END
				CLOSE @Cur1
				DEALLOCATE @Cur1

				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(3) + '</' + @TAB_NAME + '>'
	END
	FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
END
CLOSE @Cur0
DEALLOCATE @Cur0

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 NUM, TAB_NAME from #TABLES order by NUM
	OPEN @CurI0
	FETCH NEXT FROM @CurI0 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 + '>'


			--- Инвалиды  тариф 03
			IF @TAB_NUM = 3
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KTI,''))) + '</КодТарифа>' FROM #DEP_DATA

			SET @CurI = CURSOR FORWARD_ONLY
			FOR select NUM, RAZDEL_NAME from #STR_2_2R WHERE TAB_NUM = @TAB_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(4) + '<' + @RAZDEL_NAME + '>'
			
					SET @CurI1 = CURSOR FORWARD_ONLY
					FOR select NUM, BLOK_NAME from #STR_2_2B 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 = 19 
							begin
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @BLOK_NAME + '>'
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
									SELECT @lcFNAME,
										CASE WHEN T.COL = 3 THEN SPACE(6) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
											 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
										ELSE SPACE(6) + '<КоличествоЗЛ_' + 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(5) + '</' + @BLOK_NAME + '>'
							end
							else begin
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @BLOK_NAME + '>'
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
									SELECT @lcFNAME, 
										CASE WHEN T.COL = 3 THEN SPACE(6) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
											 SPACE(6) + '<РасчетСумм>' + CHAR(10) +
											 SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
										ELSE SPACE(7) + '<СуммаПоследние' + 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(6) + '</РасчетСумм>'
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @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(4) + '</' + @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(3) + '</' + @TAB_NAME + '>'
		END
		FETCH NEXT FROM @CurI0 INTO @TAB_NUM, @TAB_NAME
	END
	CLOSE @CurI0
	DEALLOCATE @CurI0	
end
--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</' + @TAB_NAME + '>'
			

-----Разделы 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, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
SELECT DISTINCT 
	FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
	DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
	PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
FROM
	#TAB5 T5

DROP TABLE #TAB5

--Проставить номера попорядку
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) + '<ДатаВыдачиСправки>' + LTRIM(RTRIM(ISNULL(DATE_SPR,'  '))) + '</ДатаВыдачиСправки>' + CHAR(10) +
				SPACE(6) + '<ДатаОкончанияДействия>' + LTRIM(RTRIM(ISNULL(PER_END,''))) + '</ДатаОкончанияДействия>' + 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_2---
		IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 6, DEFAULT, DEFAULT) WHERE SUMMA <> 0) > 0
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_2_ДляОбщественныхОрганизацийИнвалидов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьЧленовОрганизации>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
						 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
					WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
					WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
					WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 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, 6, 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, 6, 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_2_ДляОбщественныхОрганизацийИнвалидов>'
	END	--IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 6, 3, DEFAULT) WHERE SUMMA <> 0) > 0	

---Раздел3_3
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 7, DEFAULT, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_3_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленность>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 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, 7, 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, 7, 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, 7, 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(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, 7, 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(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, 7, 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(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, 7, 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(4) + '</Раздел3_3_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 7, 3, DEFAULT) WHERE SUMMA <> 0) > 0
END --	IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
--Раздел3_4


	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 8, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_4_ДляОрганизацийИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходовПоНКвсего>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>' + CHAR(10)
				+ SPACE(5) +'</СуммаДоходовПоНКвсего>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходовИТизНих>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>' + CHAR(10) 
				+ SPACE(5) +'</СуммаДоходовИТизНих>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ДоляДоходовИТ>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<ДоляДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоПредшествующему>' + CHAR(10) + 
					SPACE(6) + '<ДоляДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоТекущему>' + CHAR(10)
				+ SPACE(5) +'</ДоляДоходовИТ>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ЧисленностьРаботниковИТ>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<КоличествоЗЛпоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<КоличествоЗЛпоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоТекущему>' + CHAR(10)
				+ SPACE(5) +'</ЧисленностьРаботниковИТ>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 4, 3) 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 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
				WHEN 4 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\  \.\  \.\    '))) + '</ДатаЗаписиВреестре>'
				WHEN 5 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 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(4) + '</Раздел3_4_ДляОрганизацийИТ>'
	END	--(SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 7, D
----Раздел3_5	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 9, DEFAULT, DEFAULT) WHERE COL = 4 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) + '<СведенияПоВидуДеятельности>'
				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,''))) + '</НаименованиеВидаЭД>'
							 + SPACE(6) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КодПоОКВЭД>'
					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, 9, DEFAULT, DEFAULT) T where T.ROW IN (1,2,3,4,5,6,7,8,9,10) and T.COL IN (1,2,4,5) 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, 9, 11, 6) 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 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, 9, 12, DEFAULT) T WHERE T.COL IN (3,6,7) 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_5_ДляОрганизацийСМИ>'
	END
----Раздел3_6	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, DEFAULT) WHERE COL = 3 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) + 
				'<СуммаДоходаПоСтатье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, 10, 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, 10, 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, 10, 3, 3) T ORDER BY T.COL

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_6_ДляОрганизацийПрименяющихУСН>'
	END
----Раздел3_7	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL in (3,4) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_7_ДляНекоммерческихОрганизацийПрименяющихУСН>'
			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(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, 11, 1, DEFAULT) T WHERE T.COL IN (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(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, 11, 2, DEFAULT) T WHERE T.COL IN (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(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, 11, 3, DEFAULT) T WHERE T.COL IN (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(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, 11, 4, DEFAULT) T WHERE T.COL IN (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(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, 11, 4, DEFAULT) T WHERE T.COL IN (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(4) + '</Раздел3_7_ДляНекоммерческихОрганизацийПрименяющихУСН>'
	END
--- Раздел3_8
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL in (3,4) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_8_ДляОрганизацийОказывающихИнжиниринговыеУслуги>'
			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(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, 1, DEFAULT) T WHERE T.COL IN (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(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, 2, DEFAULT) T WHERE T.COL IN (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(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, 3, DEFAULT) T WHERE T.COL IN (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, 12, 5, DEFAULT) T WHERE T.COL IN (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, 12, 6, DEFAULT) T WHERE T.COL IN (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_8_ДляОрганизацийОказывающихИнжиниринговыеУслуги>'

	END
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел3РасчетНаПравоПримененияПониженногоТарифа>'

END --IF (SELECT COUNT(*) FROM #INVALID) > 0 OR -- информ. технол.

---РАЗДЕЛ_4  Стр.12
CREATE TABLE #DONACHISL (
	LINK INT, YEAR_D VARCHAR(4), MON int, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2), SUM_MED_STR NUMERIC(18,2))

CREATE TABLE #TAB13 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB13 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #DONACHISL (YEAR_D, MON, SUM_STR, SUM_NAK, SUM_MED_STR)
SELECT DISTINCT 
	YEAR_D = (SELECT TOP 1 STR_VAL FROM #TAB13 T WHERE T.COL = 2 AND T.ROW_CODE = T13.ROW_CODE),
	MON = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 3 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 4 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_NAK = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 5 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_MED_STR = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 6 AND T.ROW_CODE = T13.ROW_CODE)
FROM
	#TAB13 T13

DROP TABLE #TAB13

--Проставить номера попорядку
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СуммыДоначисленныхСтраховыхВзносов>'

		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<СуммаДоначисленныхВзносовЗаПериод>'  + CHAR(10) +
				SPACE(4) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_D,''))) + '</Год>' + CHAR(10) + 		
				SPACE(4) + '<Месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(2),ISNULL(MON,0)))) + '</Месяц>' + CHAR(10) + 		
				SPACE(4) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</ОПСстраховаяЧасть>' + CHAR(10) + 										
				SPACE(4) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
				SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,0)))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
			SPACE(3) + '</СуммаДоначисленныхВзносовЗаПериод>'
		FROM #DONACHISL				


		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<ИтогоДоначислено>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR,0))))) + '</ОПСстраховаяЧасть>' + CHAR(10) +			
					SPACE(4) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_NAK,0))))) + '</ОПСнакопительнаяЧасть>' + 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СуммыДоначисленныхСтраховыхВзносов>'	
	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 #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 #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 #TAB14 T WHERE T.COL = 2 AND T.ROW_CODE = T14.ROW_CODE),
	NUM_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	DATE_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	NUM_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	DATE_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 5 AND T.ROW_CODE = T14.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 6 AND T.ROW_CODE = T14.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 7 AND T.ROW_CODE = T14.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 8 AND T.ROW_CODE = T14.ROW_CODE)
FROM
	#TAB14 T14

DROP TABLE #TAB14

--Проставить номера попорядку
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, 14, 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СведенияОВыплатахВпользуОбучающихся>'
		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, 15, 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, 15, 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СведенияОВыплатахВпользуОбучающихся>'	
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) + '<НомерУдостоверяющего>' + 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) + '</РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_СВ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_НАЧИНАЯ_С_2012_ГОДА>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]



GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_0700_2012] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_O_OTHER_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_O_OTHER_PROV]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.SD_O_OTHER_PROV
@varKSparLINK int
AS

IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> 'DOCUMENTS_CLOSE_MONTH'
	RETURN 5

IF EXISTS (SELECT * FROM DBO.CALCULATE_JURNAL WHERE LINK_DOC = @varKSparLINK)
BEGIN
		RAISERROR('Документ уже проведен!', 11, 1)
		RETURN 0
END

Declare @varKStrancount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,0

DECLARE @LinkEKR213 int
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

INSERT INTO dbo.CALCULATE_JURNAL (LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,PROCENT,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,LINK_VKR,LINK_EKR)
SELECT [LINK_EMPL] =NULL,
		[LINK_PAYS] = TAB.REF_DED,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] =0,
		[HOURS] = 0,
		[SUMMA_BASE] = TAB.SUMMA_BASE,
		[PERCENT],
		[SUMMA] = TAB.SUMMA,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = dbo.DateBeginOfMonth(CONVERT(DATETIME,('01/'+ RTRIM(DOC.MONTH)+'/'+RTRIM(DOC.YEAR)))), 
		[DATE_END] = dbo.DateEndOfMonth(CONVERT(DATETIME,('01/'+ RTRIM(DOC.MONTH)+'/'+RTRIM(DOC.YEAR)))), 
		[LINK_DEP] = LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = TAB.LINK_VKR,
		[LINK_EKR] = TAB.LINK_EKR
FROM dbo.DOCUMENTS_DED_OTHER DOC, dbo.DOCUMENTS_DED_OTHER_TABLE TAB, dbo.USER_INFO UI
WHERE UI.SID = SUSER_SID() AND DOC.LINK = TAB.LINK  AND  DOC.LINK = @varKSparLINK and TAB.SUMMA<>0


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[SD_O_OTHER_PROV] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_VEDOM_DGH_PROVERKA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_VEDOM_DGH_PROVERKA]

GO



CREATE   PROCEDURE dbo.SA_VEDOM_DGH_PROVERKA (@result int output, @link int, @maska int)
AS

set @result = 0

SELECT 
	ord = 1
	,msg_before = 'Предупреждение! Отсутствует расшифровка сумм в ведомости!'
	,msg = 'Для физлица: ' + LTRIM(RTRIM(T.FIO))
	,msg_after = +'Вероятно, из-за неверно указанного источника в ведомости суммы не были рассчитаны автоматически, а проставлены вручную.'
		+'Проверьте правильность источника в ведомости и повторите расчёт. Должна обязательно быть расшифровка сумм по физлицам.'
	,SUMMA = NULL	
FROM 
	dbo.DOCUMENTS_DED_PR_DGH D 
	INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH T ON D.LINK = T.LINK 
WHERE 
	D.LINK = @link
	AND
	@maska = 1
	AND
	NOT EXISTS 
	(
		SELECT *
		FROM 
			dbo.DOCUMENTS_DED_PR_DGH DD 
			INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH TT1 ON DD.LINK = TT1.LINK 
			INNER JOIN dbo.DOCUMENTS_DED_PR_DGH_TABLE2 TT ON TT1.LINK = TT.LINK AND TT1.PERS_LINK = TT.PERS_LINK
		WHERE 
			DD.LINK = D.LINK
			AND
			TT1.PERS_LINK = T.PERS_LINK
	)
UNION
SELECT 
	ord = 2
	,msg_before = 'Предупреждение! Не сформированы операции по ведомости!'
	,msg = 'Для физлица: ' + LTRIM(RTRIM(T.FIO))
	,msg_after = 'Проверьте расшифровку суммы в ведомости. '
		+CHAR(13) + CHAR(10) + 'Вероятно, в ведомости по источнику ' + LTRIM(RTRIM(D.NAME_VKR)) + ' суммы не были рассчитаны автоматически.'
		+CHAR(13) + CHAR(10) + 'Проверьте правильность источника в ведомости и повторите расчёт. Должна обязательно быть расшифровка сумм по физлицам.'
	,SUMMA = NULL	
FROM 
	dbo.DOCUMENTS_DED_PR_DGH D 
	INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH T ON D.LINK = T.LINK 
WHERE 
	D.LINK = @link
	AND
	@maska = 2
	AND
	NOT EXISTS 
	(
		SELECT J.PERS_LINK
		FROM 
			dbo.CALCULATE_JURNAL J
		WHERE 
			J.LINK_DOC = D.LINK
			AND
			J.PERS_LINK = T.PERS_LINK
		GROUP BY 
			J.PERS_LINK	
		HAVING
			SUM(J.SUMMA) = 	T.DISBURS			
	)

if @@ROWCOUNT = 0 
	set @result = 1


RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_VEDOM_DGH_PROVERKA] 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_DEP_ACC_DETAILS_INFO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_DEP_ACC_DETAILS_INFO]
GO




/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.BB_DEP_ACC_DETAILS_INFO
	@varKSiDepAcc 	INT,
	@varKSdDateB 	DATETIME,
	@varKSdDateE 	DATETIME,
	@varKSiVkr 	INT,
	@varKSiEkr 	INT,
	@varKSiDop_cl 	INT,
	@varKSiEmptyAcc tinyint = 0

AS

IF @varKSdDateB IS NULL
	SET @varKSdDateB = dbo.DateBeginOfYear(@varKSdDateE)

set @varKSiDop_cl = isnull(@varKSiDop_cl,0)

DECLARE @varKSiOwnDep	INT,
	@varKSiFYear	INT

-- Ассигнования
DECLARE @varKSTableAssign TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))

--Лимиты
DECLARE @varKSTableLimit TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))

-- Бюджетные обязательства
DECLARE @varKSTableBO TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))

-- Денежные обязательства
DECLARE @varKSTableDO TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))

-- Кассовый расход 
DECLARE @varKSTableKassaR TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))
DECLARE @varKSTableKassaD TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))

-- Финансирование
DECLARE @varKSTableFinans TABLE(
	G_LINK    INT ,
	SUMMA 	NUMERIC(28,2))
-- Кассовый план 
DECLARE @varKSTableKP TABLE(
	G_LINK    INT ,
	SUMMA 	  NUMERIC(28,2))
select @varKSiVkr = isnull(@varKSiVkr,0), @varKSiEkr = isnull(@varKSiEkr,0), @varKSiDop_cl = isnull(@varKSiDop_cl,0)

--select @varKSiVkr, @varKSiEkr, @varKSiDop_cl

set @varKSiOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
SET @varKSiFYear = YEAR(@varKSdDateE)

-- Ассигнования

INSERT INTO @varKSTableAssign(G_LINK, SUMMA)
select G_LINK, SUMMA 
from dbo.FB_LIST_FINANS_DOC(@varKSdDateB, @varKSdDateE, @varKSiFYear, 'FINANS_ASSIGN', @varKSiOwnDep, @varKSiDepAcc, @varKSiEmptyAcc, @varKSiVkr, @varKSiEkr, @varKSiDop_cl,0)


-- Кассовый план
INSERT INTO @varKSTableKP
select G_LINK, SUMMA 
from dbo.FB_LIST_FINANS_DOC(@varKSdDateB, @varKSdDateE, @varKSiFYear, 'FB_PLAN', @varKSiOwnDep, @varKSiDepAcc, @varKSiEmptyAcc, @varKSiVkr, @varKSiEkr, @varKSiDop_cl,0)

exec dbo.BufferClear 'ISP_BO'
exec dbo.BufferClear 'ISP_DO'
exec dbo.BufferClear 'ISP_KR'
exec dbo.BufferClear 'LIMIT'

INSERT INTO BUFFER (link, id)
select SA.link, 'ISP_BO' 
from dbo.DEPARTMENT_ACCOUNT_SOURCE A
inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
								(SA.cSinth = '502' and SA.cAnalit = '11' or 
									 SA.cSinth = '506' and SA.cAnalit = '00'or 
									 SA.cSinth = '506' and SA.cAnalit = '10')

INSERT INTO BUFFER (link, id)
select SA.link, 'ISP_DO' 
from dbo.DEPARTMENT_ACCOUNT_SOURCE A
inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '502' and SA.cAnalit = '12'

INSERT INTO BUFFER (link, id)
select SA.link, 'LIMIT' 
from dbo.DEPARTMENT_ACCOUNT_SOURCE A
inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
								(SA.cSinth = '501' and SA.cAnalit = '13' or 
								SA.cSinth = '506' and SA.cAnalit = '00'or 
								SA.cSinth = '506' and SA.cAnalit = '10')

-- Денежные обязательства
INSERT INTO @varKSTableDO
SELECT LINK, sum(summa) 
FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_DO')) A	
WHERE (KT_DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and 
	DEP_LINK = @varKSiOwnDep AND
	isnull(KT_VKR,0) = @varKSiVkr AND
	isnull(KT_EKR,0) = @varKSiEkr AND 
	isnull(KT_AP2,0) = @varKSiDop_cl
GROUP BY LINK

-- Обязательства
INSERT INTO @varKSTableBO
SELECT LINK, sum(summa) 
FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_BO')) A	
WHERE (KT_DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and 
	DEP_LINK = @varKSiOwnDep AND
	isnull(KT_VKR,0) = @varKSiVkr AND
	isnull(KT_EKR,0) = @varKSiEkr AND 
	isnull(KT_AP2,0) = @varKSiDop_cl
GROUP BY LINK

-- Лимиты
INSERT INTO @varKSTableLimit
SELECT LINK, sum(summa) 
FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'LIMIT')) A	
WHERE (KT_DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and 
	DEP_LINK = @varKSiOwnDep AND
	isnull(KT_VKR,0) = @varKSiVkr AND
	isnull(KT_EKR,0) = @varKSiEkr AND 
	isnull(KT_AP2,0) = @varKSiDop_cl
GROUP BY LINK


-- Кассовый расход 
INSERT INTO @varKSTableKassaR
SELECT GP.LINK, SUM(case GS.DB_KR when 1 then GS.SUMMA else - GS.SUMMA end) 
FROM dbo.BK_GetTableOborotByDate1 (@varKSdDateB, @varKSdDateE, 2, NULL, @varKSiOwnDep) GS 	
INNER JOIN G_PROV GP ON GP.LINK = GS.LINK_DOC 
INNER JOIN S_ACCOUNTS SA ON SA.LINK = GS.ACCOUNT AND (SA.CODE LIKE '%201.[12]1%' and GS.DB_KR = 1 or SA.CODE LIKE '%304.05%')
inner join dbo.BB_FIN_SOURCE S on SA.cSource = S.CODE 
INNER JOIN dbo.DEPARTMENT_ACCOUNT_SOURCE A on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc
WHERE (GS.DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and GS.DEP_ACC = 0)
	AND isnull(GS.KBK,0) = @varKSiVkr
	AND isnull(GS.EKR,0) = @varKSiEkr
	AND isnull(GS.AP2,0) = @varKSiDop_cl
GROUP BY GP.LINK

/*INSERT INTO @varKSTableKassaD
SELECT GP.LINK, SUM(GS.SUMMA) 
FROM dbo.BK_GetTableOborotByDate1 (@varKSdDateB, @varKSdDateE, 0, NULL, @varKSiOwnDep) GS 	
INNER JOIN G_PROV GP ON GP.LINK = GS.LINK_DOC 
INNER JOIN S_ACCOUNTS SA ON SA.LINK = GS.ACCOUNT AND SA.CODE LIKE '%304.05%'
inner join dbo.BB_FIN_SOURCE S on SA.cSource = S.CODE 
INNER JOIN dbo.DEPARTMENT_ACCOUNT_SOURCE A on S.LINK = A.[SOURCE] and A.ACC = GS.DEP_ACC 
WHERE (GS.DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and GS.DEP_ACC = 0)
	AND isnull(GS.KBK,0) = @varKSiVkr
	AND isnull(GS.EKR,0) = @varKSiEkr
	AND isnull(GS.AP2,0) = @varKSiDop_cl
GROUP BY GP.LINK*/

-- Финансирование
INSERT INTO @varKSTableFinans
SELECT GP.LINK, SUM(GS.SUMMA) 
FROM dbo.BK_GetTableOborotByDate1 (@varKSdDateB, @varKSdDateE, 0, NULL, @varKSiOwnDep) GS 	
INNER JOIN G_PROV GP ON GP.LINK = GS.LINK_DOC 
INNER JOIN S_ACCOUNTS SA ON SA.LINK = GS.ACCOUNT AND SA.CODE LIKE '%201.01%'
inner join dbo.BB_FIN_SOURCE S on SA.cSource = S.CODE 
INNER JOIN dbo.DEPARTMENT_ACCOUNT_SOURCE A on S.LINK = A.[SOURCE] and A.ACC = GS.DEP_ACC 
WHERE (GS.DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and GS.DEP_ACC = 0)
	AND isnull(GS.KBK,0) = @varKSiVkr
	AND isnull(GS.EKR,0) = @varKSiEkr
	AND isnull(GS.AP2,0) = @varKSiDop_cl
GROUP BY GP.LINK

INSERT INTO @varKSTableFinans
select G_LINK, SUMMA 
from dbo.FB_LIST_FINANS_DOC(@varKSdDateB, @varKSdDateE, @varKSiFYear, 'FB_RESULT_FINANS', @varKSiOwnDep, @varKSiDepAcc, @varKSiEmptyAcc, @varKSiVkr, @varKSiEkr, @varKSiDop_cl,0)
union 
SELECT GP.LINK, sum(MONEY_CURRENT) as SUMMA
FROM FIN_RR_TABLE F , G_Prov GP
WHERE GP.object in (select link from s_objects where Code = 'FIN_RR_IN')
	and GP.DATE_PROV is not null  
	and F.link_up = GP.link
	and GP.DEP = @varKSiOwnDep
	and GP.DATE_PROV <= @varKSdDateE
	and GP.DATE_PROV >= @varKSdDateB
	and (GP.ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and GP.ACC is null)
	and isnull(F.VKR,0) = @varKSiVkr
	and isnull(F.EKR,0) = @varKSiEkr 
	--and (F.DOP_CL = @varKSiDop_cl OR (F.DOP_CL IS NULL OR @varKSiDop_cl IS NULL))
GROUP BY GP.LINK

--объединяем и добавляем расшифровку 
SELECT 	CHECKED = 0,
	LOCKED = convert(bit,0),
	UPD = 0,
	DEL = 0,
	GP.DATE_PROV, 
	GP.[DATE], 
	GP.NUMBER, 
	[FLAG_JC]   = CASE WHEN GP.DATE_PROV IS NULL THEN 0 ELSE 1 END,
	LINK   = GP.LINK,
	DOC_CODE   = SO.CODE,
	DOC_NAME   = SO.[NAME],
	[SUMMA_A]  = ISNULL(A.SUMMA,0),
	[SUMMA_L]  = ISNULL(L.SUMMA,0),
	[SUMMA_BO] = ISNULL(B.SUMMA,0),
	[SUMMA_DO] = ISNULL(D.SUMMA,0),
	[SUMMA_KR] = ISNULL(KR.SUMMA,0) /*- ISNULL(KD.SUMMA,0)*/,
	[SUMMA_F]  = ISNULL( F.SUMMA,0),
	[SUMMA_KP]  = ISNULL( KP.SUMMA,0)
FROM (SELECT DISTINCT G_LINK FROM @varKSTableAssign UNION
	SELECT DISTINCT G_LINK FROM @varKSTableLimit UNION
	SELECT DISTINCT G_LINK FROM @varKSTableBO UNION
	SELECT DISTINCT G_LINK FROM @varKSTableDO UNION
	SELECT DISTINCT G_LINK FROM @varKSTableKassaR UNION
	--SELECT DISTINCT G_LINK FROM @varKSTableKassaD UNION
	SELECT DISTINCT G_LINK FROM @varKSTableFinans UNION
	SELECT DISTINCT G_LINK FROM @varKSTableKP) CD
INNER JOIN G_PROV GP ON GP.LINK = CD.G_LINK
INNER JOIN S_OBJECTS SO ON GP.OBJECT = SO.LINK
LEFT JOIN @varKSTableAssign A  ON A.G_LINK = GP.LINK
LEFT JOIN @varKSTableLimit L   ON L.G_LINK = GP.LINK
LEFT JOIN @varKSTableBO B      ON B.G_LINK = GP.LINK
LEFT JOIN @varKSTableDO D      ON D.G_LINK = GP.LINK
--LEFT JOIN @varKSTableKassaD KD ON KD.G_LINK = GP.LINK
LEFT JOIN @varKSTableKassaR KR ON KR.G_LINK = GP.LINK
LEFT JOIN @varKSTableFinans F  ON F.G_LINK = GP.LINK
LEFT JOIN @varKSTableKP KP	   ON KP.G_LINK = GP.LINK
ORDER BY GP.DATE_PROV, GP.NUMBER

print getdate()




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_REP_SVOD2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_SVOD2]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
--[dbo].SD_REP_SVOD2 '20081001', '20081031', 1, '', 0, '', 0
CREATE    PROCEDURE dbo.SD_REP_SVOD2
	@varKSstart_date DATETIME, @varKSEND_DATE DATETIME,	
	@varKSnMode int,							
	@varKScVal1 char(1), @varKSnOtborLink1 int,	
	@varKScVal2 char(1), @varKSnOtborLink2 int	
AS
BEGIN

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	CREATE TABLE #EMPLS(LINK_EMPL INT)
	IF LEN(@varKScVal1) <> 0 
		INSERT INTO #EMPLS
		SELECT RECORD FROM OBJECT_VAR_EMPL WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO #EMPLS
		SELECT E.LINK FROM dbo.EMPL E where E.DEP_LINK = @DEP_LINK


	SELECT --По сотрудникам
		LINK_PAYS,
		TYP_OPER, 
		[CODE] = CODE_PAYS,
		[NAME] = NAME_PAYS,
		[HOURS] = SUM(HOURS),
		[DAYS] = SUM(DAYS),
		[SUM_PAY] = SUM(CASE WHEN TYP_OPER = 1 OR TYP_OPER = 3 THEN SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE		
	INTO #TMP
	FROM dbo.S_J_C_Short SJC inner join #EMPLS E on SJC.LINK_EMPL = E.LINK_EMPL
		inner join dbo.kosgu EKR on EKR.link = LINK_EKR
	WHERE 
		SJC.LINK_DEP = @DEP_LINK
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND ( (@varKSnMode = 1 AND TYP_OPER <3 ) OR (@varKSnMode = 2 AND TYP_OPER = 3))
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,'')
	UNION
	SELECT --По Внештатникам
		LINK_PAYS,
		TYP_OPER, 
		[CODE] = CODE_PAYS,
		[NAME] = NAME_PAYS,
		[HOURS] = SUM(HOURS),
		[DAYS] = SUM(DAYS),
		[SUM_PAY] = SUM(CASE WHEN TYP_OPER = 1 OR TYP_OPER = 3 THEN SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE		
	FROM S_J_C_Short SJC inner join dbo.kosgu EKR on EKR.link = LINK_EKR
	WHERE 
		SJC.LINK_DEP = @DEP_LINK
		AND COALESCE(SJC.LINK_EMPL,0) = 0 AND COALESCE(SJC.LINK_FACE,0) = 0 AND COALESCE(SJC.PERS_LINK,0) <> 0
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND ( (@varKSnMode = 1 AND TYP_OPER <3 ) OR (@varKSnMode = 2 AND TYP_OPER = 3))
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
		AND LEN(@varKScVal1) = 0 
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,'')
	UNION
	SELECT --Травматизм
		LINK_PAYS,
		TYP_OPER, 
		[CODE] = CODE_PAYS,
		[NAME] = NAME_PAYS,
		[HOURS] = 0,
		[DAYS] = 0,
		[SUM_PAY] = SUM(CASE WHEN TYP_OPER = 1 OR TYP_OPER = 3 THEN SUMMA ELSE 0 END),
		[SUM_TAX] = SUM(CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END),
		COALESCE(EKR.CODE,'') as EKR_CODE		
	FROM S_J_C_Short SJC inner join dbo.kosgu EKR on EKR.link = LINK_EKR
	WHERE
		SJC.LINK_DEP = @DEP_LINK 
		AND COALESCE(SJC.LINK_EMPL,0) = 0 AND COALESCE(SJC.LINK_FACE,0) = 0 AND COALESCE(SJC.PERS_LINK,0) = 0 
		AND SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND @varKSnMode = 2 
		AND TYP_OPER = 3
		AND (
			LEN(@varKScVal2) = 0
			OR SJC.LINK_VKR IN (SELECT RECORD FROM dbo.OBJECT_VAR_SAL_SFIN WHERE LINK_UP = @varKSnOtborLink2 )
		)
	GROUP BY LINK_PAYS, TYP_OPER, CODE_PAYS, NAME_PAYS, COALESCE(EKR.CODE,'')

	-----
	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	
	SELECT 
		LINK_PAYS,
		[TYP_OPER], 
		[CODE],
		[NAME],
		[EKR] =  CASE WHEN TYP_OPER = 3 THEN
							CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
									CASE WHEN ISNULL(EKR_CODE,'213') = '211' THEN '213' ELSE ISNULL(EKR_CODE,'213') END
								ELSE 
									CASE WHEN ISNULL(EKR_CODE,'213') IN ('211', '212') THEN '213' ELSE ISNULL(EKR_CODE,'213') END
							END
						ELSE EKR_CODE
					END, 	
		[HOURS] = SUM(HOURS),
		[DAYS] = SUM(DAYS),
		[SP] = SUM(SUM_PAY),
		[SUM_TAX] = SUM(SUM_TAX),
		[SUM_PAY] = SUM(SUM_PAY)
	INTO #RES
	FROM #TMP 
	GROUP BY
		LINK_PAYS, 
		TYP_OPER, 
		[CODE],
		[NAME],
		[EKR_CODE]
	ORDER BY TYP_OPER, CODE, EKR


	Select LINK_PAYS, TYP_OPER, CODE, [NAME], HOURS = sum(HOURS), DAYS = sum(DAYS), SUM_PAY= sum(SUM_PAY), SUM_TAX= sum(SUM_TAX)
	into #RES1
	from #RES
	GROUP by LINK_PAYS, TYP_OPER, CODE, [NAME]

	DECLARE @varKSTABLE_N VARCHAR(100)
	DECLARE @varKSTABLE_U VARCHAR(100)
	EXEC X_GET_TABLE_NAME @varKSTABLE_N OUTPUT
	SET @varKSTABLE_U = @varKSTABLE_N + '1'

	DECLARE @varKSCNT_N INT
	SELECT @varKSCNT_N = COUNT(DISTINCT EKR) FROM #RES 

		EXEC M_CROSS_TABLE
			'LINK_PAYS', 
			'EKR', 'VARCHAR(3)', 
			'SP', 'NUMERIC(20,2)', 'SUM(SP) AS SP',
			'#RES', @varKSTABLE_N

		EXEC (' SELECT R.TYP_OPER, R.CODE, R.NAME, R.HOURS, R.DAYS,  R.SUM_PAY, R.SUM_TAX, N.* FROM #RES1 R left join ' + @varKSTABLE_N + ' N ON N.LINK_PAYS  =R.LINK_PAYS 
				order by R.TYP_OPER, R.CODE, R.NAME')

	
END




GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD2] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ro_import_form_spr]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[ro_import_form_spr]

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- Процедура импорта справочников
CREATE PROCEDURE dbo.[ro_import_form_spr]
AS

   CREATE TABLE #t_CodeRow (Code VARCHAR(254), Code_Form VARCHAR(254), begin_date DATETIME, end_date DATETIME,
                           Code_s VARCHAR(254), Code_Form_s VARCHAR(254), begin_date_s DATETIME, end_date_s DATETIME)
   
   INSERT #t_CodeRow ([Code], [Code_Form], [begin_date], [end_date], [Code_s], [Code_Form_s], [begin_date_s], [end_date_s])
   SELECT K.Code, K.[Code_Form], K.[begin_date], K.[end_date], K1.[Code], K1.[Code_Form], K1.[begin_date], K1.[end_date]
   FROM dbo.report_kbk k
         JOIN dbo.report_kbk K1 ON K.[Link_self] = K1.[link] AND K1.code_form <> K.code_form
         JOIN dbo.report_kbk_U U ON K1.[Code_Form] = U.[Code_Form] AND K1.[Code] = U.[Code]
        
   DELETE dbo.report_kbk
   WHERE code_form IN (SELECT distinct K.code_form FROM dbo.report_kbk_U K)
   
     
	insert dbo.report_kbk(Code, link_self, Code_form, childrens, Name, ImageIndex, Code_Str, property, add_info, orders, long_name, begin_date, end_date)
	select Code, 0, Code_Form, childrens, Name, ImageIndex, Code_Str, property, add_info, orders, long_name, begin_date, end_date
	from dbo.report_kbk_U K

	update K
	set link_self = isnull((select top 1 K2.link from dbo.report_kbk K2 where K2.code_form = U1.code_form and K2.code = U1.code and isnull(K2.begin_date, '19000101') = isnull(U1.begin_date, '19000101') and isnull(K2.end_date, '30000101') = isnull(U1.end_date, '30000101')),0)
	from dbo.report_kbk K join dbo.report_kbk_U U on K.code_form = U.code_form and K.code = U.code and isnull(K.begin_date, '19000101') = isnull(U.begin_date, '19000101') and isnull(K.end_date, '30000101') = isnull(U.end_date, '30000101')
		left join dbo.report_kbk_U U1 on U.link_self = U1.link


   UPDATE K
   SET link_self = K1.[link]
   FROM dbo.report_kbk K
         JOIN #t_CodeRow C ON K.[Code_Form] = C.[Code_Form] AND K.[Code] = C.[Code] AND ISNULL(K.begin_date, '19000101') = ISNULL(C.begin_date, '19000101') AND ISNULL(K.end_date, '30000101') = ISNULL(C.end_date, '30000101')
         JOIN dbo.report_kbk K1 ON K1.[Code_Form] = C.[Code_Form_S] AND K1.[Code] = C.[Code_S] AND ISNULL(K1.begin_date, '19000101') = ISNULL(C.begin_date_S, '19000101') AND ISNULL(K1.end_date, '30000101') = ISNULL(C.end_date_S, '30000101')
         
   DELETE #t_CodeRow
   WHERE EXISTS(SELECT * 
                FROM dbo.report_kbk K JOIN dbo.report_kbk K1 ON K.[Link_self] = K1.[link] 
                WHERE K.[Code_Form] = #t_CodeRow.[Code_Form] AND K.[Code] = #t_CodeRow.[Code] AND ISNULL(K.begin_date, '19000101') = ISNULL(#t_CodeRow.begin_date, '19000101') AND ISNULL(K.end_date, '30000101') = ISNULL(#t_CodeRow.end_date, '30000101')
                      AND K1.[Code_Form] = #t_CodeRow.[Code_Form_S] AND K1.[Code] = #t_CodeRow.[Code_S] AND ISNULL(K1.begin_date, '19000101') = ISNULL(#t_CodeRow.begin_date_S, '19000101') AND ISNULL(K1.end_date, '30000101') = ISNULL(#t_CodeRow.end_date_S, '30000101'))

   UPDATE K
   SET link_self = K1.[link]
   FROM dbo.report_kbk K
         JOIN #t_CodeRow C ON K.[Code_Form] = C.[Code_Form] AND K.[Code] = C.[Code] AND ISNULL(K.begin_date, '19000101') = ISNULL(C.begin_date, '19000101') AND ISNULL(K.end_date, '30000101') = ISNULL(C.end_date, '30000101')
         JOIN dbo.report_kbk K1 ON K1.[Code_Form] = C.[Code_Form_S] AND K1.[Code] = C.[Code_S] AND ISNULL(K1.begin_date, '19000101') = ISNULL(C.begin_date_S, '19000101')
         
   DELETE #t_CodeRow
   WHERE EXISTS(SELECT * 
                FROM dbo.report_kbk K JOIN dbo.report_kbk K1 ON K.[Link_self] = K1.[link] 
                WHERE K.[Code_Form] = #t_CodeRow.[Code_Form] AND K.[Code] = #t_CodeRow.[Code] AND ISNULL(K.begin_date, '19000101') = ISNULL(#t_CodeRow.begin_date, '19000101') AND ISNULL(K.end_date, '30000101') = ISNULL(#t_CodeRow.end_date, '30000101')
                      AND K1.[Code_Form] = #t_CodeRow.[Code_Form_S] AND K1.[Code] = #t_CodeRow.[Code_S] AND ISNULL(K1.begin_date, '19000101') = ISNULL(#t_CodeRow.begin_date_S, '19000101') )


   UPDATE K
   SET link_self = K1.[link]
   FROM dbo.report_kbk K
         JOIN #t_CodeRow C ON K.[Code_Form] = C.[Code_Form] AND K.[Code] = C.[Code] AND ISNULL(K.begin_date, '19000101') = ISNULL(C.begin_date, '19000101') AND ISNULL(K.end_date, '30000101') = ISNULL(C.end_date, '30000101')
         JOIN dbo.report_kbk K1 ON K1.[Code_Form] = C.[Code_Form_S] AND K1.[Code] = C.[Code_S] 
         

  DROP TABLE #t_CodeRow
  
  INSERT [dbo].[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
  SELECT rk.[link], h.[DATE], max(h.[NAME]), max(h.[LONG_NAME])
  FROM  [dbo].[REPORT_KBK_HIST_U] h
         JOIN [dbo].[REPORT_KBK_U] k ON h.[LINK_UP] = k.[LINK] 
         JOIN [dbo].[REPORT_KBK] rk ON rk.code_form = k.code_form AND rk.code = k.code 
                                       AND ISNULL(rk.[begin_date], '19000101') = ISNULL(k.[begin_date], '19000101')      
                                       AND ISNULL(rk.[end_date], '30000101') = ISNULL(k.[end_date], '30000101')
  GROUP BY  rk.[link], h.[DATE]                                      
GO


GRANT EXECUTE ON dbo.[ro_import_form_spr] TO PUBLIC

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 @varKSMonth int, 
		@varKSYear int, 
		@varKSLink1 int,
		@DEP_LINK INT,
		@varKSDate DATETIME	

SELECT 
	@varKSYear = YEAR(S.DATE_CALC),
	@varKSMonth = MONTH(S.DATE_CALC),
	@DEP_LINK = S.LINK_DEP,
	@varKSDate = 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] <= @varKSDate 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<=@varKSDate ORDER BY PERIOD DESC)
	AND
	dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@varKSMonth,@varKSYear))
		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(@varKSDate) 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))
INSERT INTO #SUMMA (LINK_TAX, LINK_PERS, LINK_INC, LINK_VKR, LINK_EKR, SUMMA_M, SUMMA)
SELECT
	B.LINK_TAX,
	ISNULL(J.PERS_LINK,E.PERS_LINK),
	P.LINK_INC,
	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) = @varKSMonth THEN SUMMA ELSE 0 END),
	SUMMA  = SUM(SUMMA)
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
WHERE
	J.LINK_DEP = @DEP_LINK
	AND
	P.[OBJECT] = 1 
	AND
	YEAR(J.PERIOD_BEGIN) = @varKSYear AND MONTH(J.PERIOD_BEGIN) <= @varKSMonth
	--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

		
-- Базовые суммы по физлицам в разрезе кодов дохода
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)	= @varKSYear AND MONTH(DATE_CALC) < @varKSMonth
GROUP BY
	LINK_TAX, LINK_PERS, LINK_INC

-- Расчёт скидки за месяц по физлицам в разрезе кодов дохода и источников
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 ISNULL(S2.SUMMA,0) > ISNULL(SK.PREDEL,0) THEN ISNULL(SK.PREDEL,0) ELSE ISNULL(S2.SUMMA,0) END) 
		--Уже предоставили
		- ISNULL(SP.SUMMA,0)
	) 
	--пропорционально кодам доходов
	* (S.SUMMA_M / S2.SUMMA_M),
	[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 #INV I ON --Инвалиды и процент по ним
						I.LINK = S2.LINK_PERS
WHERE
	S2.SUMMA_M <> 0
	--- не берем в расчет коды вычетов, полученные работниками  на предыдущем месте работы, 
	--- в случае когда они приняты в промежутке заданного года 
	and not EXISTS(select * from SD_EMPL_PREV_DED  
					   		where link_empl  IN (SELECT LINK FROM SD_EMPL 
															WHERE PERS_LINK = S2.LINK_PERS 
															and YEAR(DATE_begin) = @varKSYear )
															and link_ded = (select ref_deduct from dbo.DICTIONARY_TYP_INCOMS 
																							  where link =  S2.LINK_inc))

--===РАСЧЁТ ВЫЧЕТОВ
--Информация о предельном размере ВЫЧЕТА
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(@varKSDate) 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) = @varKSMonth 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) = @varKSYear AND MONTH(J.PERIOD_BEGIN) <= @varKSMonth
	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)	= @varKSYear AND MONTH(DATE_CALC) < @varKSMonth
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_EKR, SUMMA_M = SUM(SUMMA_M)
INTO #TMP_DOH FROM #SUMMA GROUP BY LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR

--Доход по сотрудникам
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))
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.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, SUMMA = SUM(SUMMA) FROM dbo.SDOC_DOT_VYCHET 
		WHERE LINK_UP = @LINK GROUP BY LINK_TAX, LINK_PERS, LINK_VKR
	) V
	ON V.LINK_TAX = DR.LINK_PAYS AND V.LINK_PERS = S.LINK_PERS AND V.LINK_VKR = S.LINK_VKR
	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

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.[SD_U_VEDOM_DGH_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_U_VEDOM_DGH_PROV]

GO

CREATE PROCEDURE dbo.SD_U_VEDOM_DGH_PROV
@varKSparLINK int
AS

IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> 'DOCUMENTS_DED_PAYROLL_DGH'
	RETURN 5

IF EXISTS (SELECT * FROM DBO.CALCULATE_JURNAL WHERE LINK_DOC = @varKSparLINK)
BEGIN
		RAISERROR('Документ уже проведен!', 11, 1)
		RETURN 0
END	

Declare @varKStrancount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,0


DECLARE @LinkEKR226 int
SET @LinkEKR226 = COALESCE((SELECT TOP 1 LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '226'),0)

/*Заготовка*/
SELECT 
	D.LINK, T1.ORDERS, T1.PERS_LINK, T.LINK_EKR,
	T1.DISBURS 
		* (CASE WHEN 
				COALESCE(SUM(case when T.TYP_PAY = 1 then T.summa else -T.summa end),0) <> 0 
			THEN 
				COALESCE(SUM(case when T.TYP_PAY = 1 then T.summa else -T.summa end),0) 
			ELSE 1 END)
		/ (CASE WHEN 
				COALESCE(R.SUMMA,0) <> 0 
			THEN 
				COALESCE(R.SUMMA,0) 
			ELSE 1 END) as DISBURS
INTO #TMP
FROM 
	dbo.DOCUMENTS_DED_PR_DGH D 
	INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH T1 ON D.LINK = T1.LINK 
	INNER JOIN 
	(
	SELECT DD.LINK, TT1.PERS_LINK, SUM(CASE WHEN TT.TYP_PAY = 1 then TT.SUMMA ELSE -TT.SUMMA END) SUMMA
	FROM 
		dbo.DOCUMENTS_DED_PR_DGH DD 
		INNER JOIN dbo.DOCUMENTS_DED_PR_TABLE_DGH TT1 ON DD.LINK = TT1.LINK 
		INNER JOIN dbo.DOCUMENTS_DED_PR_DGH_TABLE2 TT ON TT1.LINK = TT.LINK AND TT1.PERS_LINK = TT.PERS_LINK
	WHERE 
		DD.LINK = @varKSparLINK 
	GROUP BY 
		DD.LINK, TT1.PERS_LINK 
	) R ON T1.LINK = R.LINK AND T1.PERS_LINK = R.PERS_LINK
	INNER JOIN dbo.DOCUMENTS_DED_PR_DGH_TABLE2 T ON T1.LINK = T.LINK AND T1.PERS_LINK = T.PERS_LINK	
where 
	D.LINK = @varKSparLINK 
GROUP BY 
	D.LINK, T1.ORDERS, T1.PERS_LINK, t.LINK_EKR, T1.DISBURS, R.SUMMA

---
DECLARE @VEDOM_OPTIONS_OPT11 TINYINT
SET @VEDOM_OPTIONS_OPT11 = dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT11')

INSERT INTO dbo.CALCULATE_JURNAL (LINK_EMPL,LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,PERS_LINK,LINK_VKR,LINK_EKR)
SELECT [LINK_EMPL] = NULL,
		[LINK_PAYS] = DOC.REF_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = CASE WHEN @VEDOM_OPTIONS_OPT11 = 1 THEN dbo.DateBeginOfMonth(doc.REF_BASE) ELSE dbo.DateBeginOfMonth(doc.[DATE]) END,	
		[PERIOD_END] = CASE WHEN @VEDOM_OPTIONS_OPT11 = 1 THEN dbo.DateEndOfMonth(doc.REF_BASE) ELSE dbo.DateEndOfMonth(doc.[DATE]) END,	
		[DAYS] = 0,
		[HOURS] = 0,
		[SUMMA_BASE] = 0,
		[SUMMA] = TAB.DISBURS,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] =dbo.DateBeginOfMonth(doc.REF_BASE),
		[DATE_END] = dbo.DateEndOfMonth(doc.REF_BASE),
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[PERS_LINK]	= TAB.PERS_LINK, 
		[LINK_VKR] = DOC.LINK_VKR,
		COALESCE(TAB.LINK_EKR,@LinkEKR226)
FROM dbo.DOCUMENTS_DED_PR_DGH DOC,  #TMP TAB, dbo.USER_INFO UI
WHERE UI.SID = SUSER_SID() AND DOC.LINK = TAB.LINK  AND  DOC.LINK = @varKSparLINK and TAB.DISBURS<>0


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0






GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_DGH_PROV] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_NUO_DGH_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_NUO_DGH_PROV]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE   PROCEDURE dbo.SD_NUO_DGH_PROV

@varKSparLINK int
AS

IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> 'DOCUMENTS_DGH'
	RETURN 5

IF EXISTS (SELECT * FROM DBO.CALCULATE_JURNAL WHERE LINK_DOC = @varKSparLINK)
BEGIN
		RAISERROR('Документ уже проведен!', 11, 1)
		RETURN 0
END	

Declare @varKStrancount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,0

INSERT INTO dbo.CALCULATE_JURNAL (LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,PERS_LINK,LINK_VKR,LINK_EKR)
SELECT [LINK_PAYS] = TAB.LINK_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = 0,
		[HOURS] = 0,
		[SUMMA_BASE] = 0,
		[SUMMA] = TAB.SUMMA,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = dbo.DateBeginOfMonth(doc.PERIOD),
		[DATE_END] = dbo.DateEndOfMonth(doc.PERIOD),
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[PERS_LINK] = TAB.PERS_LINK,
		[LINK_VKR] = tab.link_vkr,
		[LINK_EKR] = tab.link_ekr
FROM dbo.DOCUMENTS_DGH DOC, dbo.DOCUMENTS_DGH_T1 TAB, dbo.USER_INFO UI
WHERE UI.SID = SUSER_SID() AND DOC.LINK = TAB.LINK  AND  DOC.LINK = @varKSparLINK  and TAB.Summa<>0


INSERT INTO dbo.CALCULATE_JURNAL (LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,PROCENT,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,PERS_LINK,LINK_VKR,LINK_EKR)
SELECT[LINK_PAYS] = TAB.LINK_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = 0,
		[HOURS] = 0,
		[SUMMA_BASE] =TAB.SUMMA_BASE,
		[PERCENT] = CASE WHEN ISNULL(TAB.[PERCENT],0) > 0 THEN TAB.[PERCENT]
					ELSE CASE WHEN TAB.SUMMA_BASE > 0 THEN (TAB.SUMMA / TAB.SUMMA_BASE) * 100 ELSE 0 END
					END,
		[SUMMA] = TAB.SUMMA,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = dbo.DateBeginOfMonth(doc.PERIOD),
		[DATE_END] = dbo.DateEndOfMonth(doc.PERIOD),
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[PERS_LINK] = TAB.PERS_LINK,
		[LINK_VKR] =tab.link_vkr,
		[LINK_EKR] = tab.link_ekr
FROM dbo.DOCUMENTS_DGH DOC, dbo.DOCUMENTS_DGH_T2 TAB, dbo.USER_INFO UI
WHERE UI.SID = SUSER_SID() AND DOC.LINK = TAB.LINK  AND  DOC.LINK = @varKSparLINK  and TAB.Summa<>0

INSERT INTO dbo.CALCULATE_JURNAL (LINK_PAYS,LINK_DOC,PERIOD_BEGIN,PERIOD_END,DAYS,HOURS,SUMMA_BASE,PROCENT,SUMMA,ORDERS,DATE_BEGIN,DATE_END,LINK_DEP,LINK_ORG,PERS_LINK,LINK_VKR,LINK_EKR)
SELECT[LINK_PAYS] = TAB.LINK_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = 0,
		[HOURS] = 0,
		[SUMMA_BASE] =TAB.SUMMA_BASE,
		[PERCENT] = CASE WHEN ISNULL(TAB.[PERCENT],0) > 0 THEN TAB.[PERCENT]
					ELSE CASE WHEN TAB.SUMMA_BASE > 0 THEN (TAB.SUMMA / TAB.SUMMA_BASE) * 100 ELSE 0 END
					END,
		[SUMMA] = TAB.SUMMA,
		[ORDERS] = TAB.ORDERS,
		[DATE_BEGIN] = dbo.DateBeginOfMonth(doc.PERIOD),
		[DATE_END] = dbo.DateEndOfMonth(doc.PERIOD),
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[PERS_LINK] = TAB.PERS_LINK,
		[LINK_VKR] = tab.link_vkr,
		[LINK_EKR] = tab.link_ekr
FROM dbo.DOCUMENTS_DGH DOC, dbo.DOCUMENTS_DGH_T3 TAB, dbo.USER_INFO UI
WHERE UI.SID = SUSER_SID() AND DOC.LINK = TAB.LINK  AND  DOC.LINK = @varKSparLINK  and TAB.Summa<>0


EXEC dbo.SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_PROV] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RN_IMPORT_FORM_154]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RN_IMPORT_FORM_154]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
CREATE PROCEDURE dbo.[RN_IMPORT_FORM_154]   
   @lvcKODF         VARCHAR(10),
   @lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
   @liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
   @bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0     -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn     INT,
        @ltImportType TINYINT,
        @liLSF        INT,
        @lvcAdm       VARCHAR(3),                
        @lvcTXT   VARCHAR(8000),
        @lvcWord1 VARCHAR(8000),
        @lvcWord2 VARCHAR(8000),
        @lvcKBP   VARCHAR(50),
        @lvcVB    VARCHAR(50),
        @liORDER  INT,
        @i        INT,
		@vcUK		varchar(100),
        @bBreak_To_Grbs BIT ,
        @iLinkOrg  INT ,
        @iLinkBudg  INT 

SET @bBreak_To_Grbs = 0
SET @ltImportType = 2

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   DECLARE curLSF CURSOR FOR
      SELECT [B].[LINK_SAVED_FORM]
      FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
      JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[KBP] = [B].[KBP] AND 
                                                  [A].[VB] = [B].[VB] AND 
                                                  [A].[LINK_FORM] = [B].[LINK_FORM] AND 
                                                  [A].[DT] = [B].[DT] AND 
                                                  [A].[PRD] = [B].[PRD] AND 
                                                  [A].[VF0] = [B].[VF0] AND 
                                                  [A].[IMPORT_DATE] >= [B].[IMPORT_DATE]
      WHERE [A].[LINK_SAVED_FORM] = @liRepeatRequest 
   
   OPEN curLSF
   
   FETCH NEXT 
   FROM curLSF
   INTO @liLSF
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
        
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liLSF,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode

      FETCH NEXT 
      FROM curLSF
      INTO @liLSF
   END
      
   CLOSE curLSF
   DEALLOCATE curLSF
   
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

SELECT @lvcKBP = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
      LEFT([TXT],3) IN ('KБ=')

SELECT @lvcVB = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

 SELECT top 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
 FROM #IMPORT_TABLE
 WHERE LEFT([TXT],3) IN ('TO|')

 IF @lvcKBP IS NULL
 BEGIN
    SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],''), @bBreak_To_Grbs = Break_To_Grbs      
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
    SELECT @iLinkOrg = link FROM dbo.departments WHERE budg =  REPLACE(@lvcKBP, 'КБП=', '') 
 END

 IF @lvcVB IS NULL 
 BEGIN
    SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
    
    SELECT @iLinkBudg = link FROM dbo.kl_budg_type WHERE outcode = REPLACE(@lvcVB, 'ВИД=', '') 
 END


IF @lvcKBP IS NULL
BEGIN
   SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_KBP_151'
END

IF @lvcVB IS NULL 
BEGIN
   SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_VB_151'
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE LEFT([TXT],3) = 'FK|')
BEGIN
   DELETE #IMPORT_TABLE 
   WHERE [ORDER] IN (1,2)

   SET IDENTITY_INSERT #IMPORT_TABLE ON  
   
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ='+@lvcKODF,-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'КБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   IF @lvcKODF = '0503154G'
   BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=5',2)
   END
   ELSE BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)
   END
   
   SET IDENTITY_INSERT #IMPORT_TABLE OFF

   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

DECLARE @tabIMPORT_HEAD TABLE ([TXT] VARCHAR(8000),
                               [ORDER] INT IDENTITY(1,1))


DECLARE @tabIMPORT TABLE ([TXT] VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))
   
DECLARE @tabRD TABLE ([TXT] VARCHAR(8000),
                      [RD]  TINYINT,
                      [ADM] VARCHAR(3))

INSERT @tabIMPORT_HEAD([TXT]) VALUES ('КОДФ='+@lvcKODF)


IF EXISTS (SELECT * 
           FROM #IMPORT_TABLE
           WHERE LEFT([TXT],3)='BO|')
BEGIN       
   INSERT @tabIMPORT_HEAD([TXT]) 
   SELECT 'ДТ=' + RTRIM(dbo.[RA_GETWORDNUM]([TXT],3,'|'))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3)='BO|'
END

INSERT @tabIMPORT_HEAD([TXT]) VALUES (ISNULL( @lvcKBP,'КБП='))
INSERT @tabIMPORT_HEAD([TXT]) VALUES (ISNULL(@lvcVB,'ВИД='))

IF @lvcKODF = '0503154G'
BEGIN
   INSERT @tabIMPORT_HEAD([TXT]) VALUES ('ПРД=5')
END
ELSE BEGIN
   INSERT @tabIMPORT_HEAD([TXT]) VALUES ('ПРД=3')
END
--select * from @tabIMPORT

INSERT @tabRD([ADM],
              [RD],
              [TXT])
SELECT [ADM] = '',
       [RD] = 1,
       [TXT] = SUBSTRING([TXT],7,8000)        
FROM #IMPORT_TABLE
WHERE LEFT([TXT],5) IN ('BOACT')  

INSERT @tabRD([ADM],
              [RD],
              [TXT])
SELECT [ADM] = '',
       [RD] = 2,
       [TXT] = SUBSTRING([TXT],7,8000)        
FROM #IMPORT_TABLE
WHERE LEFT([TXT],5) IN ('BOPAS')  


    INSERT #IMPORT_TABLE([TXT])
    SELECT CASE WHEN [TXT] LIKE 'КБП=%' THEN '' + ISNULL(@lvcKBP, '') WHEN [TXT] LIKE 'ВИД=%'THEN '' + isnull(@lvcVB, '') ELSE [TXT] END 
    FROM @tabIMPORT_HEAD
    ORDER BY [ORDER]                     


   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=1')
   
   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabRD
   WHERE  [RD] = 1
      
   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=2')
   
   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabRD
   WHERE [RD] = 2
   
   
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode




RETURN @liReturn

GO
GRANT ALL ON dbo.[RN_IMPORT_FORM_154] 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.[KU_NEW_FACE_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_NEW_FACE_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE [dbo].KU_NEW_FACE_SAVE
	@parLINK	int	OUTPUT,
	@parNumber  varchar(30),
	@parDate   datetime,
	@parSTAFF_LINK int = null,
	@parDATE_BEGIN     DATETIME = null,
	@parDATE_END       DATETIME = null,
	@parUSL_PR         VARCHAR(254) = null,
	@parETS_RAZR	INT = null,
	@parISP            VARCHAR(254) = null,
	@parKONTR_DATE     DATETIME = null,
	@parKONTR_NUM      VARCHAR(15) = null,
	@parNUM_STAKE	NUMERIC(4,2) = null,
	@parSTATUS int = null,
	@parEMPL_LINK      INT = null,
	@parORDER_LINK INT = null,
	@parDEP_LINK int = null,
	@parORDER_STATUS int = 0,
	@parTEMP_LINK int = null,
    @parIO int = null
AS
DECLARE @ERROR tinyint, @trancount int, @SQLError int, @RowCount int, @comment varchar(254)

SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @parDATE_BEGIN IS NULL or @parNUM_STAKE is null or @parNUM_STAKE<=0 or @parEMPL_LINK is null
		or @parSTAFF_LINK is null or @parSTATUS is null
	BEGIN
		ROLLBACK
		RETURN 5
	END
	
	IF @parDEP_LINK is null
		SELECT @parDEP_LINK = dep_link FROM user_dep

	IF @parDATE_BEGIN > @parDATE_END
	BEGIN
		ROLLBACK
		RETURN 107
	END

	IF (@parKONTR_DATE is null and @parKONTR_NUM is not null) or (@parKONTR_DATE is not null and @parKONTR_NUM is null)
	BEGIN
		ROLLBACK
		RETURN 108
	END
	
	SELECT @parORDER_LINK = link FROM ORDERS WITH (UPDLOCK) WHERE LINK = @parORDER_LINK
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	
	IF @RowCount = 0
	BEGIN
		SET @comment='О приеме '+dbo.ku_GetEmplFIO(@parEMPL_LINK)
		EXECUTE @ERROR = KU_ORDER_SAVE @parORDER_LINK OUTPUT, 1, @parNumber, @parDate, @comment, 0, @parDEP_LINK
		IF @ERROR <> 0
			RETURN @ERROR
	END
	
	IF @parLINK is null OR @parLINK = 0
	BEGIN
		INSERT INTO item_move WITH (ROWLOCK) (new_face, staff_link, date_begin, date_end2, usl_pr, ets_razr,
				isp, type, kontr_date, kontr_num, num_stake, status, empl_link, order_link,temp_link ,[io])
			VALUES (1, @parSTAFF_LINK, @parDATE_BEGIN, @parDATE_END, @parUSL_PR, @parETS_RAZR, @parISP,
					0, @parKONTR_DATE, @parKONTR_NUM, @parNUM_STAKE, @parSTATUS, @parEMPL_LINK, @parORDER_LINK,@parTEMP_LINK, @parIO)
		SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END ELSE BEGIN
		UPDATE item_move SET
			staff_link=@parSTAFF_LINK, date_begin=@parDATE_BEGIN,
			date_end2=@parDATE_END, usl_pr=@parUSL_PR, ets_razr=@parETS_RAZR, isp=@parISP, type=0, kontr_date=@parKONTR_DATE, kontr_num=@parKONTR_NUM,
			num_stake=@parNUM_STAKE, status=@parSTATUS, empl_link=@parEMPL_LINK, order_link=@parORDER_LINK,temp_link=@parTEMP_LINK, [io]=@parIO
		WHERE link=@parLINK
		SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @RowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
		UPDATE money_period SET date_begin = @parDATE_BEGIN WHERE item_link = @parLINK
		SELECT @SQLError = @@ERROR
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	IF not exists(SELECT * FROM oklad_pays WHERE dep_link=@parDEP_LINK) BEGIN
		ROLLBACK
		RETURN 113
	END

	IF @parORDER_STATUS=1
		UPDATE orders SET status = 1 WHERE link=@parORDER_LINK

IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[KU_NEW_FACE_SAVE] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_EXPORT_F1152026_502]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_EXPORT_F1152026_502]

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152026_502 (@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK VARCHAR (20),
		@OKATO VARCHAR (15),
		@OKATO_D VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT @DEP_LINK = LINK_ORGANIZATION,
			@dDATE_FORM	= BEGIN_DATE,
			@PERIOD_TYPE = PERIOD_TYPE,
			@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT @INN	= CONVERT (VARCHAR (10), INN_LONG),
			@KPP = CONVERT (VARCHAR (9), KPP),
			@IMNS = CONVERT (VARCHAR (4), IMNS),
			@OKVED = CONVERT (VARCHAR (8), OKVED),
			@DEP_NAME = [NAME],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT @NAME_RUK = IM,
			@FAM_RUK = FM,
			@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКАТО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT @KBK = ISNULL (COL2, ''),
		@OKATO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 1.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT @CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT @Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT @NAL_BASE = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '200'

	SELECT @NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '210'

	SELECT @SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '220'

	SELECT @SumAV = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '230'

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '240'

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '250'

	SELECT @SUM_NAL_PRED = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '260'

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_IMUD_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE (ID int identity(1,1), F_NAME VARCHAR(254) DEFAULT (''),
			OUT_TEXT TEXT DEFAULT (''))

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE @NAME_PROG VARCHAR(254),
		@VERS_PROG VARCHAR(254)

	SELECT @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK where CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.02">')

-- Документ

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152026"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')

		IF @cREORG_CODE LIKE '[1-3, 5-6]'
		BEGIN
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + @cREORG_INN + '"')
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + @cREORG_KPP + '"')
		END	
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущНД>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКАТО="' + CASE WHEN ISNULL (@OKATO, '') = ''
											THEN ISNULL (@OKATO_D, '')
											ELSE @OKATO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОст="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПер НалБаза="' + LTRIM (STR (ISNULL (@NAL_BASE, 0))) + '"'
			+ ' СумНалИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@SumAV, 0) = 0 THEN ''
					ELSE ' СумАвИсчисл="' + LTRIM (STR (ISNULL (@SumAV, 0))) + '"'
				END
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_NAL_PRED, 0) = 0 THEN ''
					ELSE ' СумНалПред="' + LTRIM (STR (ISNULL (@SUM_NAL_PRED, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущНД>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TASK_PROP
END 



GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152026_502] TO PUBLIC

GO


--Расширенные свойства--


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.[sysobjects]
           WHERE [ID] = OBJECT_ID(N'dbo.[I_CONTROL_RULES_LIST]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
   DROP PROCEDURE dbo.[I_CONTROL_RULES_LIST]
GO


/*******************************************************************************

	© Кейсистемс (Keysystems), 2005

*******************************************************************************/
CREATE PROCEDURE dbo.[I_CONTROL_RULES_LIST]
	@iLINK_SAVED_FORM	INT      = 7,	
	@tIsOutside	        TINYINT  = 0,
	@sPERIOD_TYPE	    SMALLINT = 0,	
	@sPERIOD_NUMBER	    SMALLINT = 0,	
	@sIsSvod	        SMALLINT = 0,	
	@IsUSE_TMP_TABLE    SMALLINT = 0	
AS

--считаем регион
declare @cStr varchar(250),@region varchar(250),@link_form int,@reg int
create table #tmp_rules_list (LINK_RULE int,REGION varchar(100),orderRule int)
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,''))
IF @IsUSE_TMP_TABLE=0  
BEGIN
IF @tIsOutside = 0  
BEGIN
	select @link_form=link_form from REPORT_SAVED_FORMS (NOLOCK) where LINK_SAVED_FORM = @iLINK_SAVED_FORM

	if not exists(select * from [REPORT_CONTROL_RULES] (NOLOCK) where link_form=@link_form and region=@region)
		set @region=''
	
	insert #tmp_rules_list
	SELECT [LINK_RULE],
          isnull([REGION],''),OrderRule
	FROM dbo.[REPORT_CONTROL_RULES] [R] (NOLOCK)
   JOIN dbo.[REPORT_SAVED_FORMS]   [F] (NOLOCK) ON [F].[LINK_FORM] = [R].[LINK_FORM]
	WHERE [F].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM AND 
         [R].[IsOutside] = 0                       AND
		   ([R].[PERIOD] = 0 OR ([R].[PERIOD] & [F].[PERIOD_TYPE] > 0 AND 
                               ([R].[PERIOD_NOM] = 0 OR [R].[PERIOD_NOM] & POWER(2,[F].[PERIOD_NUMBER] - 1)>0))) /*AND 
         ([R].[ORG_LEVEL] = 0 OR [R].[ORG_LEVEL] & (CASE 
                                                       WHEN [F].[LINK_ORGANIZATION] = dbo.[GetOwnDepLink]() 
                                                       THEN (SELECT ABS(MAX([REP_IS_SVOD]-2)) 
                                                             FROM dbo.[WorkMode]) 
                                                       ELSE 2 
                                                    END)>0)	AND 
         ([R].[IsSvod] = 0 OR [R].[IsSvod] = ([F].[IsSvod]+1))*/
		 and (isnull(R.region,'')=@region or isnull(R.region,'')='')

	IF @region<>''
	BEGIN
		delete #tmp_rules_list from #tmp_rules_list A where A.region='' and link_rule in 
		(select B.link_rule from  report_control_rows B JOIN dbo.[REPORT_CONTROL_RULES] rcr ON rcr.[Link_Rule] = B.[Link_Rule]
            where B.orderRow=1  and B.link_rule IN (select link_rule from #tmp_rules_list where 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(B.link_row,0) and isnull(C.code_row,'')=isnull(B.code_row,'') and isnull(C.link_col,0)=isnull(B.link_col,0) and isnull(C.link_table,0)=isnull(B.link_table,0)
-- следующее условие означает вот что:
-- не существует слагаемых в удаляемом правиле, что в правиле региона отстутствует данная таблица
           and not exists(select * from dbo.report_control_rows Ro2 where Ro2.Link_Rule = B.link_rule and Ro2.Link_Table is NOT NULL
               and not exists(select top 1 * from dbo.report_control_rows Ro3 where Ro3.Link_Rule = C.Link_Rule and Ro3.Link_Table is NOT NULL and RO2.Link_Table = RO3.Link_table))
         
)
      
)
			 
		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

	SELECT [LINK_RULE],
          [OrderRule] from #tmp_rules_list
END
ELSE BEGIN
	SELECT [LINK_RULE],
          [OrderRule]
	FROM dbo.[REPORT_CONTROL_RULES] [R] (NOLOCK)
   --JOIN dbo.[USER_INFO]            [U] ON [U].[LINK_TASK] = [R].[LINK_TASK]
	WHERE [R].[IsOutside] = 1 AND 
--         [R].[LINK_TASK] = (SELECT [LINK_TASK]
--                            FROM [USER_INFO]) AND 
       ([R].[PERIOD] = 0 OR ([R].[PERIOD] & @sPERIOD_TYPE > 0 AND 
                               ([R].[PERIOD_NOM] = 0 OR [R].[PERIOD_NOM] & POWER(2,@sPERIOD_NUMBER - 1) > 0))) /*AND 
         ([R].[ORG_LEVEL] = 0 OR [ORG_LEVEL] & (CASE 
                                                   WHEN @iLINK_SAVED_FORM=dbo.[GetOwnDepLink]() 
                                                   THEN (SELECT ABS(MAX([REP_IS_SVOD] - 2)) 
                                                         FROM dbo.[WORKMODE]) 
                                                   ELSE 2 
                                                END) > 0)	AND 
         ([R].[IsSvod] = 0 OR [R].[IsSvod] = (@sIsSvod+1))*/
END

END
ELSE
BEGIN
IF @tIsOutside = 0  
BEGIN
	select @link_form=link_form from REPORT_SAVED_FORMS where LINK_SAVED_FORM = @iLINK_SAVED_FORM
	if not exists(select * from [REPORT_CONTROL_RULES] where link_form=@link_form and region=@region)
		set @region=''
	
	insert #tmp_rules_list
	SELECT [LINK_RULE],
          isnull([REGION],''),OrderRule
	FROM dbo.[#REPORT_CONTROL_RULES] [R]
   JOIN dbo.[REPORT_SAVED_FORMS]   [F] ON [F].[LINK_FORM] = [R].[LINK_FORM]
	WHERE [F].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM AND 
         [R].[IsOutside] = 0                       AND
		   ([R].[PERIOD] = 0 OR ([R].[PERIOD] & [F].[PERIOD_TYPE] > 0 AND 
                               ([R].[PERIOD_NOM] = 0 OR [R].[PERIOD_NOM] & POWER(2,[F].[PERIOD_NUMBER] - 1)>0))) /*AND 
         ([R].[ORG_LEVEL] = 0 OR [R].[ORG_LEVEL] & (CASE 
                                                       WHEN [F].[LINK_ORGANIZATION] = dbo.[GetOwnDepLink]() 
                                                       THEN (SELECT ABS(MAX([REP_IS_SVOD]-2)) 
                                                             FROM dbo.[WorkMode]) 
                                                       ELSE 2 
                                                    END)>0)	AND 
         ([R].[IsSvod] = 0 OR [R].[IsSvod] = ([F].[IsSvod]+1)) */
		 and (isnull(R.region,'')=@region or isnull(R.region,'')='')

	IF @region<>''
	BEGIN
		delete #tmp_rules_list from #tmp_rules_list A where A.region='' and link_rule in 
		(select link_rule from  report_control_rows B where B.orderRow=1 and link_rule in 
				 (select link_rule from #tmp_rules_list where region='') 
			and			
			exists(select * from report_control_rows C where C.link_rule in (select link_rule from #tmp_rules_list where region<>'')
			 and C.orderRow=1 and isnull(C.link_row,0)=isnull(B.link_row,0) and isnull(C.code_row,'')=isnull(B.code_row,'') and isnull(C.link_col,0)=isnull(B.link_col,0) and isnull(C.link_table,0)=isnull(B.link_table,0)))

		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

	SELECT [LINK_RULE],
          [OrderRule] from #tmp_rules_list


END
ELSE BEGIN
	SELECT [LINK_RULE],
          [OrderRule]
	FROM dbo.[#REPORT_CONTROL_RULES] [R]
  -- JOIN dbo.[USER_INFO]            [U] ON [U].[LINK_TASK] = [R].[LINK_TASK]
	WHERE [R].[IsOutside] = 1 AND 
--         [R].[LINK_TASK] = (SELECT [LINK_TASK]
--                            FROM [USER_INFO]) AND 
         ([R].[PERIOD] = 0 OR ([R].[PERIOD] & @sPERIOD_TYPE > 0 AND 
                               ([R].[PERIOD_NOM] = 0 OR [R].[PERIOD_NOM] & POWER(2,@sPERIOD_NUMBER - 1) > 0))) /*AND 
         ([R].[ORG_LEVEL] = 0 OR [ORG_LEVEL] & (CASE 
                                                   WHEN @iLINK_SAVED_FORM=dbo.[GetOwnDepLink]() 
                                                   THEN (SELECT ABS(MAX([REP_IS_SVOD] - 2)) 
                                                         FROM dbo.[WORKMODE]) 
                                                   ELSE 2 
                                                END) > 0)	AND 
         ([R].[IsSvod] = 0 OR [R].[IsSvod] = (@sIsSvod+1))*/
END
END

drop table #tmp_rules_list
GO
GRANT ALL ON dbo.[I_CONTROL_RULES_LIST] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from dbo.[REPORT_CONTROL_RULES] 

exec dbo.[I_CONTROL_RULES_LIST] 5805,1,3

select * from report_saved_forms f1
join report_forms f2 on f1.link_form = f2.link_form 
where f2.code = '168o'

selct * FROM [USER_INFO]
*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_RECYCLE_SAVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_RECYCLE_SAVE]
GO

/*
© Кейсистемс (Keysystems), 2012
перед затиранием данных удаляем в корзину копию отчета
*/


CREATE                       procedure dbo.RO_RECYCLE_SAVE
	@varKSiLSF	int
AS
  
DECLARE @iLinkSF_Del INT   

EXEC dbo.[RA_COPY_SAVED_FORM] @varKSiLSF, @iLinkSF_Del OUTPUT

UPDATE dbo.[REPORT_SAVED_FORMS] 
SET [Del] = 1
WHERE [Link_Saved_Form] = @iLinkSF_Del

update report_saved_form_owner
set sid = SUSER_SID(),
	hostname = HOST_NAME(),
	date = GETDATE()
where LSF = @iLinkSF_Del

IF @@ROWCOUNT = 0
	insert report_saved_form_owner (LSF, sid, hostname, date)
	values(@iLinkSF_Del, SUSER_SID(), HOST_NAME(),GETDATE())

--

RETURN 0

GO
GRANT ALL ON dbo.[RO_RECYCLE_SAVE] 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].[BB_CREDIT_CARD_CB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_CREDIT_CARD_CB]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
c Кейсистемс (Keysystems), 2005
*/

create  procedure dbo.BB_CREDIT_CARD_CB
	@dDateB 	datetime,
	@dDateE 	datetime
	

as
declare @iOwnDep	int
	
declare @tRest table(CB_NAME varchar(254),
		      		[TYPE] tinyint,
					 SUMMA_R numeric(28,2),
					 SUMMA_N numeric(28,2))

set @iOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_P'
exec dbo.BufferClear 'SGU_K_KL_N'

insert into BUFFER (link, id)
select link, 'CREDIT_ACC' from s_accounts where code like '%301.12'

insert into BUFFER (link, id)
select link, 'CREDIT_PER' from s_accounts where code like '%210.02%' or code like '%201.07%' or code like '%201.11%'  or code like '%401.30%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL' from s_accounts where code like '%304.05%' or code like '%201.07%' or code like '%201.11%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL_N' from s_accounts where code like '%401.[1-2]0%'

insert into BUFFER (link, id)
select link, 'SGU_D' from dbo.KOSGU where CODE like '8%'

insert into BUFFER (link, id)
select link, 'SGU_K' from dbo.KOSGU where CODE like '7%'

insert into BUFFER (link, id)
select link, 'SGU_K_P' from dbo.KOSGU where CODE like '23%'

insert into BUFFER (link, id)
select link, 'SGU_K_PL_N' from dbo.KOSGU where CODE like '171'



-- Раздел 1
declare @tTempRasdel1 table(OPER_NAME	varchar(254),
							OPER_DATE	datetime,
							SUM_PER_R		numeric(28,2),
							SUM_PL_R	numeric(28,2),
							SUM_PER_N		numeric(28,2),
							SUM_PL_N		numeric(28,2),
							SUM_PR 		numeric(28,2),
							C_LINK	int,
							DOC_NAME	varchar(254),
							DOC_NUM		char(25),
							DOC_DATE	datetime)

declare @tRasdel1 table(DOC_NAME	varchar(254),
						DOC_NUM		char(25),
						DOC_DATE	datetime,
						OPER_NAME	varchar(254),
						OPER_DATE	datetime,
						CB_NAME		varchar(254),
						CB_SER		varchar(10),
						CB_NUM		varchar(25),
						SUM_PER_R		numeric(28,2),
						SUM_PL_R		numeric(28,2),
						SUM_PER_N		numeric(28,2),
						SUM_PL_N		numeric(28,2),
						SUM_PR 		numeric(28,2))



insert into @tTempRasdel1
select S.NAME_OPER, S.DATE_PROV, case isnull(KAU.CODE,'Размещение') when 'Размещение' then S.SUMMA else 0 end, 0, case isnull(KAU.CODE,'') when 'Номинал' then S.SUMMA else 0 end, 0, 0, isnull(S.KT_AP1, S.DT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PER', 'CREDIT_ACC',
			 null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,null, null,null) S
left join dbo.KAU KAU on S.KT_KAU = KAU.LINK
union
select S.NAME_OPER, S.DATE_PROV, 0, case isnull(KAU.CODE,'Размещение') when 'Размещение' then S.SUMMA else 0 end, 0, case isnull(KAU.CODE,'') when 'Номинал' then S.SUMMA else 0 end, 0, isnull(S.DT_AP1, S.KT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null) S
left join dbo.KAU KAU on S.DT_KAU = KAU.LINK
union
select S.NAME_OPER, S.DATE_PROV,  0, 0, 0, 0, S.SUMMA, isnull(S.DT_AP1, S.KT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL_N',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null) S
left join dbo.KAU KAU on S.DT_KAU = KAU.LINK
union
select S.NAME_OPER, S.DATE_PROV, 0, 0, 0, 0, S.SUMMA, isnull(S.KT_AP1, S.DT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,null, null,null) S
left join dbo.KAU KAU on S.KT_KAU = KAU.LINK


-- Раздел 2
declare @tTempRasdel2 table(OPER_NAME	varchar(254),
							OPER_DATE	datetime,
							SUM_PER	numeric(28,2),
							SUM_PL	numeric(28,2),
							SUM_PR 	numeric(28,2),
							C_LINK	int,
							DOC_NAME	varchar(254),
							DOC_NUM		char(25),
							DOC_DATE	datetime)

declare @tRasdel2 table(DOC_NAME	varchar(254),
						DOC_NUM		char(25),
						DOC_DATE	datetime,
						CB_NAME		varchar(254),
		      			OPER_NAME	varchar(254),
						OPER_DATE	datetime,
						SUM_PER		numeric(28,2),
						SUM_PL		numeric(28,2),
						SUM_PR 		numeric(28,2))

insert into @tTempRasdel2
select S.NAME_OPER, S.DATE_PROV, S.SUMMA, 0, 0, isnull(S.KT_AP1, S.DT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,null, null,null) S
union
select S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA, 0, isnull(S.DT_AP1, S.KT_AP1), dbo.JurnalProvGetDocKind (S.LINK, S.DOC_OBJECT), S.NUMBER, S.DOC_DATE
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null) S

insert into @tRest
select  isnull(C.[TYPE_NAME],''), case KBK.TYPE when 1 then 1 else 0 end,  sum(case when KBK.TYPE = 1 or isnull(KAU.CODE,'Размещение') = 'Размещение' then (R.K_SUMMA - R.D_SUMMA) else 0 end), sum(case when KBK.TYPE > 1 and isnull(KAU.CODE,'') = 'Номинал' then (R.K_SUMMA - R.D_SUMMA) else 0 end) 
	from dbo.aRestTableByDateAccounts(@dDateB,'CREDIT_ACC') R
	inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
	inner join dbo.BD_OSNOV O on R.AP1 = O.LINK  
	inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
	left join dbo.KAU KAU on R.KAU = KAU.LINK
	group by C.[TYPE_NAME], case KBK.TYPE when 1 then 1 else 0 end


insert into @tRest
select  isnull(C.[TYPE_NAME],''), 2 + case KBK.TYPE when 1 then 1 else 0 end, sum(case when KBK.TYPE = 1 or isnull(KAU.CODE,'Размещение') = 'Размещение' then (R.K_SUMMA - R.D_SUMMA) else 0 end), sum(case when KBK.TYPE > 1 and isnull(KAU.CODE,'') = 'Номинал' then (R.K_SUMMA - R.D_SUMMA) else 0 end)
	from dbo.aRestTableByDateAccounts(@dDateE,'CREDIT_ACC') R
	inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
	left join dbo.BD_OSNOV O on R.AP1 = O.LINK  
	inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
	left join dbo.KAU KAU on R.KAU = KAU.LINK
	group by C.[TYPE_NAME],2 + case KBK.TYPE when 1 then 1 else 0 end


insert into @tRasdel1
select	DOC_NAME	= S.DOC_NAME,
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		S.OPER_NAME,
		S.OPER_DATE,
		CB_NAME		= isnull(C.[TYPE_NAME],''),
		CB_SER		= convert(char(10), CP.VALUE),
		CB_NUM		= C.NUMBER,
		S.SUM_PER_R,
		S.SUM_PL_R,
		S.SUM_PER_N,
		S.SUM_PL_N,
		S.SUM_PR
from @tTempRasdel1 S
left join dbo.BD_OSNOV O on S.C_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK
left join dbo.CREDIT_PARAM CP on CP.LINK_UP = C.LINK
inner join dbo.CREDIT_PARAM_DICTION PD on PD.LINK = CP.PARAM_LINK and PD.CODE = 'SERIYA'



insert into @tRasdel2
select	DOC_NAME	= S.DOC_NAME,
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		CB_NAME		= isnull(C.[TYPE_NAME],''),
		S.OPER_NAME,
		S.OPER_DATE,
		S.SUM_PER,
		S.SUM_PL,
		S.SUM_PR
from @tTempRasdel2 S
left join dbo.BD_OSNOV O on S.C_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK


declare @tDocTable table(CB_NAME varchar(100))

insert into @tDocTable
select CB_NAME from @tRasdel2 union
select CB_NAME from @tRasdel1 union
select CB_NAME from @tRest
 
 /*
select * from @tDocTable
select * from @tRasdel1
select * from @tRasdel2
select * from @tRest
 */
select	DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		REST_B_R = isnull(RB.SUMMA_R,0),
		REST_E_R = isnull(RE.SUMMA_R,0),
		REST_B_N = isnull(RB.SUMMA_N,0),
		REST_E_N = isnull(RE.SUMMA_N,0),
		OPER_NAME = isnull(R.OPER_NAME,''),
		R.OPER_DATE,
		DT.CB_NAME,
		CB_NUM = isnull(R.CB_NUM,''),
		CB_SER = isnull(R.CB_SER,''),
		SUM_PER_R = isnull(R.SUM_PER_R,0),
		SUM_PL_R = isnull(R.SUM_PL_R,0),
		SUM_PER_N = isnull(R.SUM_PER_N,0),
		SUM_PL_N = isnull(R.SUM_PL_N,0),
		SUM_PR = isnull(R.SUM_PR,0)
		 
from @tDocTable DT
left join @tRasdel1 R on DT.CB_NAME = R.CB_NAME 
left join @tRest RB on DT.CB_NAME = RB.CB_NAME and RB.[TYPE] = 0
left join @tRest RE on DT.CB_NAME = RE.CB_NAME and RE.[TYPE] = 2
order by DT.CB_NAME

select	DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		SUM_REST_B = isnull(RB.SUMMA_R,0),
		SUM_REST_E = isnull(RE.SUMMA_R,0),
		OPER_NAME = isnull(R.OPER_NAME,''),
		R.OPER_DATE,
		DT.CB_NAME,
		SUM_PER = isnull(R.SUM_PER,0),
		SUM_PL = isnull(R.SUM_PL,0),
		SUM_PR = isnull(R.SUM_PR,0)
		 
from @tDocTable DT
left join @tRasdel2 R on DT.CB_NAME = R.CB_NAME
left join @tRest RB on DT.CB_NAME = RB.CB_NAME and RB.[TYPE] = 1
left join @tRest RE on DT.CB_NAME = RE.CB_NAME and RE.[TYPE] = 3
order by DT.CB_NAME


exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_KL_N'

return 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant all on dbo.BB_CREDIT_CARD_CB to public
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[FB_EXPORT_BR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[FB_EXPORT_BR]

GO





/*
© Кейсистемс (Keysystems), 2006
Выгрузки Лимитов БО и Ассигнований 
*/




CREATE          PROCEDURE dbo.FB_EXPORT_BR
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''
AS
DECLARE @iDepLink	int,
	@iPeriod	tinyint,
	@iPeriodType	tinyint


set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())


-- Блок FROM
SELECT	'' as KOD_TOFK, 
	'' as NM_TOFK,
	budg 	as KOD_BPR, 
	name 	as NM_BPR, 
	0 as link,
	0 as link_up
FROM DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink

-- Блок TO
SELECT 	TOFK 	  as KOD_TOFK, 
	TOFK_NAME as NM_TOFK, 
	'' as KOD_BPR,
	'' as NM_BPR,
	0 as link,
	0 as link_up
FROM dbo.DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink
	


select  @iPeriod = FIN_SMETA_PER - 1 from workmode
set @iPeriodType = 0

-- Блок RL

select 	PERIOD		= convert(varchar(1),@iPeriod),
	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,
	IST		= '',
	YEAR_GOD	= F.FSUMMA,
	PRIM		= '',
	VID_IZM		= '',
	LINK		= F.LINK,
	LINK_UP		= F.LINK

from dbo.FINANS_LIMIT_AND_ASSIGN F
where F.link in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())


if @cObjCode = 'FINANS_ASSIGN'
	select 	LINK		= F.LINK,
			LINK_UP		= F.LINK,
			NOM_OSNOV	= O.NUMBER,
			DATE_OSNOV	= O.DATE,
			OSNOV		= O.[TYPE],
			PRIM		= O.COMMENT
	from dbo.FINANS_ASSIGN F
	inner join dbo.BD_OSNOV O on F.LINK_OSNOV = O.LINK
	where F.CHANGE = 1 and
			exists (select * from dbo.BufferGetTableByID(@cBuffId) where LINK = F.link)

if @cObjCode = 'FINANS_ASSIGN_SVOD'
	select 	LINK		= F.LINK,
			LINK_UP		= F.LINK,
			NOM_OSNOV	= O.NUMBER,
			DATE_OSNOV	= O.DATE,
			OSNOV		= O.[TYPE],
			PRIM		= O.COMMENT
	from dbo.FINANS_ASSIGN_SVOD F
	inner join dbo.BD_OSNOV O on F.LINK_OSNOV = O.LINK
	where F.CHANGE = 1 and
			exists (select * from dbo.BufferGetTableByID(@cBuffId) where LINK = F.link)


-- Блок RLST
select 	GLAVA		= case KBK.TYPE when 1 then VKR.CODE_FKR_M else '' end,
	RAZDEL		= case KBK.TYPE when 1 then VKR.CODE_FKR_D else '' end,
	STATIA		= case KBK.TYPE when 1 then VKR.CODE_FKR_T else '' end,
	VID		= case KBK.TYPE when 1 then VKR.CODE_FKR_E else '' end,
	E_KLASS		= EKR.CODE,
	KKIVNF		= case KBK.TYPE when 8 then KBK.CODE else '' end,
	KKIVF		= case KBK.TYPE when 4 then KBK.CODE else '' end,
	KOD_DOH		= case KBK.TYPE when 2 then KBK.CODE else '' end,
	ADD_KLASS	= DCL.CODE,
	[LOCAL]		= '',
	SUM1		= case 	when @iPeriod = 0 and @iPeriodType = 0 or @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_YEAR02	= FT.Y2,
	SUM_YEAR03	= FT.Y3,
	PRIM_STR	= '',
	LINK		= FT.LINK,
	LINK_UP		= FT.LINK_UP
from dbo.FINANSE FT
inner join dbo.FINANSE_HEAD FH on FH.LINK = FT.LINK_UP
left join dbo.BI_DICTION_VKR VKR on VKR.LINK_KBK = FT.VKR 
left join dbo.KL_KBK KBK on KBK.LINK = FT.VKR --and KBK.TYPE <> 1 
left join dbo.DOP_CLASSIF DCL on DCL.LINK = FT.DOP_CL 
left join dbo.KOSGU EKR on EKR.LINK = FT.EKR 
where FT.LINK_UP in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())




GO


GRANT EXECUTE ON dbo.[FB_EXPORT_BR] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_86N_002_ANALYZE]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_86N_002_ANALYZE]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011
   
   Вход: Созданные таблицы и заполненные:
               CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                                       ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета
         
               CREATE TABLE #tab002
               (
                  ID       UNIQUEIDENTIFIER
                  ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
                  ,[versionNumber]   VARCHAR(50)-- Номер версии
                  ,[financialYear]  INT         -- Текущий финансовый год
                  ,[nextFinancialYear] INT      -- Очередной финансовый год
                  ,[planFirstYear] INT          --Первый год планового периода
                  ,[planLastYear] INT           --Второй год планового периода
               )
               -- Услуги
               CREATE TABLE #tab002_SERVICE
               (
                  ID       UNIQUEIDENTIFIER
                  ,[CODE]  VARCHAR(50)    -- Код услуги
                  ,[NUM]   VARCHAR(50)    -- Порядковый номер раздела, соответствующий услуге
                  ,[NAME]  VARCHAR(1000)  -- Наименование услуги, указанной в данном разделе
                  ,[KAT]   VARCHAR(1000)  -- Категория потребителей (наименование)   
               )
               -- Показатели качества услуг 
               CREATE TABLE #tab002_QUALITY
               (
                  ID       UNIQUEIDENTIFIER
                  ,[CODE]  VARCHAR(50)       -- Код услуги
                  ,[NAME]     VARCHAR(8000)  -- Наименование показателя качества услуги  
                  ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
                  ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
                  ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя качества услуги за отчетный финансовый год
                  ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя качества услуги на текущий финансовый год 
                  ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя качества услуги на очередной финансовый год  
                  ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя качества услуги на первый год планового периода  
                  ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя качества услуги на второй год планового периода
                  ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя качества услуги за текущий финансовый
                  ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя качества 
               )
               -- Показатели объема услуги
               CREATE TABLE #tab002_VOLUME
               (
                  ID       UNIQUEIDENTIFIER
                  ,[CODE]  VARCHAR(50)       -- Код услуги
                  ,[NAME]     VARCHAR(8000)  -- Наименование показателя объема услуги   
                  ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
                  ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
                  ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя объема услуги за отчетный финансовый год
                  ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя объема услуги на текущий финансовый год 
                  ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя объема услуги на очередной финансовый год  
                  ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя объема услуги на первый год планового периода  
                  ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя объема услуги на второй год планового периода
                  ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя объема услуги за текущий финансовый
                  ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя объема 
               )
               -- Возможность взимания платы за услугу
               CREATE TABLE #tab002_PRICE
               (
                  ID       UNIQUEIDENTIFIER
                  ,[CODE]  VARCHAR(50)       -- Код услуги
                  ,[SUMMA]   NUMERIC(20,2)   --Средневзвешенная цена за единицу услуги (руб.) 
                  ,[NPA_VID]   VARCHAR(8000) --Вид нормативного правового акта 
                  ,[NPA_NAME_ORGAN]   VARCHAR(8000) -- Наименование органа, утвердившего нормативный правовой акт 
                  ,[NPA_DATE]   VARCHAR(8000)--Дата нормативного правового акта
                  ,[NPA_NUM]   VARCHAR(8000) --Номер нормативного правового акта
                  ,[NPA_NAME]   VARCHAR(8000)--Наименование нормативного правового акта 
               )
               -- Сведения о работах   
               CREATE TABLE #tab002_WORK
               (
                  ID       UNIQUEIDENTIFIER
                  ,[CODE]  VARCHAR(50)       -- Код работы
                  ,[NUM]   NUMERIC(50)       --Порядковый номер раздела соответствующий работе
                  ,[NAME]   VARCHAR(8000)    --Наименование работы, указанной в данном разделе
               )
        
   Выход: Сообщения об ошибках

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_86N_002_ANALYZE]
   @bCancel          BIT  = NULL OUTPUT
AS

SET NOCOUNT ON

IF OBJECT_ID('tempdb..#tabExportLog') IS NULL -- значит не экспорт
BEGIN
   RETURN -1
END

DECLARE @tabErrorLog TABLE([ID] UNIQUEIDENTIFIER, [TXT] VARCHAR(8000),[ORDER] INT IDENTITY(1,1))

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не указана услуга(работа) с кодом ' + RTRIM(T.[CODE]) + ' для показателя качества'
FROM #tab002_QUALITY T
WHERE NOT EXISTS(SELECT * FROM #tab002_SERVICE T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])
     AND NOT EXISTS(SELECT * FROM #tab002_WORK T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])



INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не указана услуга(работа) с кодом ' + RTRIM(T.[CODE]) + ' для показателя объема'
FROM #tab002_VOLUME T
WHERE NOT EXISTS(SELECT * FROM #tab002_SERVICE T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])
      AND NOT EXISTS(SELECT * FROM #tab002_WORK T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует услуга(работа) с кодом ' + RTRIM(T.[CODE]) + ', для которой указана НПА'
FROM #tab002_PRICE T
WHERE NOT EXISTS(SELECT * FROM #tab002_SERVICE T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])
      AND NOT EXISTS(SELECT * FROM #tab002_WORK T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = T.[CODE])

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует наименование услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_SERVICE
WHERE NAME = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует порядковый номер для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_SERVICE
WHERE NUM = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверно заполнен порядковый номер ('+RTRIM(NUM)+' должно быть числом) для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_SERVICE
WHERE NUM <> '' AND ISNUMERIC(NUM)=0

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует наименование услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_WORK
WHERE NAME = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует порядковый номер для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_WORK
WHERE NUM = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверно заполнен порядковый номер ('+RTRIM(NUM)+' должно быть числом) для работы с кодом ' + RTRIM(CODE) 
FROM #tab002_WORK
WHERE NUM <> '' AND ISNUMERIC(NUM)=0

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отcутcтвует "Вид нормативного правового акта" для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_PRICE
WHERE NPA_VID = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует "Наименование нормативного правого акта" для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_PRICE
WHERE NPA_NAME = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует "Номер нормативного правого акта" для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_PRICE
WHERE NPA_NUM = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Отсутствует "Дата нормативного правого акта" для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_PRICE
WHERE NPA_DATE = ''

SET DATEFORMAT ymd   
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверный формат "Даты нормативного правого акта" ('+RTRIM(NPA_DATE) +') (формат даты должен быть - ГГГГ-ММ-ДД) для услуги с кодом ' + RTRIM(CODE) 
FROM #tab002_PRICE
WHERE ISDATE(NPA_DATE) <> 1 OR RTRIM(NPA_DATE) NOT LIKE '[12][09][019][0-9]-[01][0-9]-[0123][0-9]'
SET DATEFORMAT ydm
   
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не найден код по ОКЕИ для единицы измерения: ' + RTRIM(EI_SYMBOL) 
FROM #tab002_VOLUME T
WHERE EI_CODE=''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не найден код по ОКЕИ для единицы измерения: ' + RTRIM(EI_SYMBOL) 
FROM #tab002_QUALITY T
WHERE EI_CODE=''


IF EXISTS(SELECT * 
          FROM @tabErrorLog)
BEGIN
   SET @bCancel = 1

   INSERT #tabExportLog([TXT])
   SELECT [TXT]
   FROM 
      (SELECT -1 [order], [ID], 'Для организации с кодом ' + RTRIM(T.[VALUE]) + ' ' + ISNULL((SELECT d.name FROM dbo.departments d WHERE d.budg = T.[VALUE] AND 1 = (SELECT COUNT(*) FROM dbo.departments d1 WHERE d1.budg = T.[VALUE])), '') AS [TXT]  
      from #tab001 T 
      WHERE T.[CODE] = '000000'
         AND EXISTS(SELECT * FROM   @tabErrorLog T1 WHERE T.[ID] = T1.[ID])
      UNION ALL
      SELECT [ORDER], [ID], [TXT]
      FROM @tabErrorLog) A
   ORDER BY [ID], [ORDER]

   INSERT #tabExportLog([TXT])
   VALUES ('Выгрузка отменена. Устраните ошибки и повторите выгрузку.')
END
ELSE BEGIN
   SET @bCancel = 0
END
   

RETURN 0



GO
GRANT ALL ON dbo.[RO_EXPORT_FORM_86N_002_ANALYZE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))
*/



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(VGT.DATE_BEGIN,VGT.DATE_END)+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 sysobjects 
		  WHERE [ID] = OBJECT_ID(N'dbo.RA_EXPORT_FORM_LIST_ATR') AND 
				       OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE dbo.[RA_EXPORT_FORM_LIST_ATR]
END

GO
/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_LIST_ATR]
	@iLINK_SAVED_FORM INT
AS
DECLARE @lcFORM_CODE		     CHAR(20),
        @liFORM_LINK		     INT,
        @liYear				  INT,
        @ltPERIOD_TYPE		  TINYINT,
        @ltPERIOD_NUMBER	  TINYINT,
        @liLINK_ORGANIZATION INT,
        @liLINK_TYPE_SVOD	  INT
		
SELECT @lcFORM_CODE			 = [B].[CODE],
       @liFORM_LINK			 = [B].[LINK_FORM],
       @liYear				    = YEAR([A].[BEGIN_DATE]),
       @ltPERIOD_TYPE		 = [A].[PERIOD_TYPE],
       @ltPERIOD_NUMBER		 = [A].[PERIOD_NUMBER],
       @liLINK_ORGANIZATION = [A].[LINK_ORGANIZATION],
       @liLINK_TYPE_SVOD	 = [A].[LINK_TYPE_SVOD]		   
FROM dbo.[REPORT_SAVED_FORMS] [A]
JOIN dbo.[REPORT_FORMS]		   [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM

IF @lcFORM_CODE IN ('(72н)425','(72н)425M','(72н)0503125М','0503125G','0503125M','425G','425M','484M', '0503725G', '0503725M')
BEGIN
	SELECT -- [CODE] = @lcFORM_CODE,
 		   [ATR] = A.atr,--dbo.[RN_GET_ATR_VAL]([A].[LINK_SAVED_FORM],0,0), -- dbo.[RN_GET_ATR_VALUE]([A].[LINK_SAVED_FORM],'REPORTS_ATR_ACC')
		   [A].[LINK_SAVED_FORM]
	FROM dbo.[REPORT_SAVED_FORMS] [A]
	WHERE [LINK_ORGANIZATION] = @liLINK_ORGANIZATION				   AND
		   ISNULL([LINK_TYPE_SVOD],0) = ISNULL(@liLINK_TYPE_SVOD,0)	AND
		   [A].[LINK_FORM] = @liFORM_LINK							      AND			  
		   YEAR([A].[BEGIN_DATE])=@liYear							      AND
		   [A].[PERIOD_TYPE] = @ltPERIOD_TYPE						      AND
		   [A].[PERIOD_NUMBER] = @ltPERIOD_NUMBER					      AND
         [A].[DEL] = 0                                            AND			  
		   [VERSION] = (SELECT MAX([VERSION])
			  		       FROM dbo.[REPORT_SAVED_FORMS] [B]
					       WHERE [A].[LINK_ORGANIZATION] = [B].[LINK_ORGANIZATION]				     AND
                            [B].[DEL] = 0                                                   AND
							       ISNULL([A].[LINK_TYPE_SVOD],0) = ISNULL([B].[LINK_TYPE_SVOD],0) AND
							       [A].[LINK_FORM] = [B].[LINK_FORM]								        AND			  
							       YEAR([A].[BEGIN_DATE]) = YEAR([B].[BEGIN_DATE])				     AND
							       [A].[PERIOD_TYPE] = [B].[PERIOD_TYPE]							        AND
							       [A].[PERIOD_NUMBER] = [B].[PERIOD_NUMBER]					 	     AND			  
							       [A].atr = [B].atr)
END

RETURN

/*
exec dbo.[RA_EXPORT_FORM_LIST_ATR] 9820

sp_helptext bufferpush
 
select * from buffer where id='REPORT_ATR_EXPORT' and sid=user_id()

*/
GO
GRANT ALL ON dbo.RA_EXPORT_FORM_LIST_ATR 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].[XD_FORM_BO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[XD_FORM_BO]
GO





CREATE    PROCEDURE dbo.XD_FORM_BO
	@varKSparLINK	 int
AS
/* Определить что за объект */
DECLARE @LinkObjCode VARCHAR(30),
		@LinkObjName VARCHAR(254),
		@iLBO		 bit,
		@cDocInfo	 VARCHAR(254),
		@LinkAcc int,
		@LinkDep int
declare @tLog table (txt varchar(254), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

SELECT @LinkObjCode = CODE, 
	   @LinkObjName = NAME
FROM S_OBJECTS WHERE LINK = (SELECT OBJECT FROM G_PROV WHERE LINK = @varKSparLINK)

/* Найти соответствие в журнале документов оснований */


SELECT @cDocInfo = CONVERT(VARCHAR(254), dbo.JurnalProvGetDocKind (LINK, OBJECT) + 
					' № ' + LTRIM(RTRIM(NUMBER))+' от ' + CONVERT(VARCHAR(10),DATE,104)
		   	+ ' '+ ISNULL(LTRIM(RTRIM(CONVERT(VARCHAR(100), COMMENT))),''))
FROM dbo.G_PROV WHERE LINK = @varKSparLINK


insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
values('Формирование обязательств по документу ' + @cDocInfo,1,0,0)		

/* Определяем счет - если в документе его нет, то берем тот счет что указан для организации по умолчанию */

SELECT @LinkAcc = ACC,@LinkDep = DEP FROM G_PROV WHERE LINK = @varKSparLINK
IF @LinkAcc IS NULL
  SELECT @LinkAcc = MAIN_LINK FROM DEPARTMENTS WHERE LINK = @LinkDep 
IF @LinkAcc IS NULL
BEGIN
	insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
	values('Не сформированы обязательства. Некорректрый счет организации.',1,2,1)
	select txt, NEW_ROW, nSTATUS, nTAB from @tLog order by ord
	return 0
		
END

BEGIN TRAN

DECLARE @LinkOsnov int
SELECT @LinkOsnov = LINK FROM dbo.BD_OSNOV WHERE DOC_LINK = @varKSparLINK

IF EXISTS(SELECT * FROM JURN_BO WHERE LINK_DOC = @LinkOsnov)
BEGIN
	/* Грохаем проводки по принятым БО*/
	/*update G_PROV
	set date_prov = null
	--set date_prov = date
	WHERE LINK IN (SELECT GP1.LINK_UP FROM G_PROV1 GP1
	 WHERE GP1.LINK IN (SELECT GP2.LINK_UP FROM G_PROV2 GP2 
	   WHERE GP2.LINK IN (SELECT PROV_LINK FROM BD_JURN_BO WHERE AP1 = @LinkOsnov)))*/

	update G
	set date_prov = null
	from dbo.G_PROV G
	inner join G_PROV1 G1 on G1.LINK_UP = G.LINK
	inner join G_PROV2 G2 on G2.LINK_UP = G1.LINK
	inner join JURN_BO BO on BO.LINK_PO_PROV = G2.LINK and BO.LINK_DOC = @LinkOsnov
	
	DELETE FROM G_PROV
	from dbo.G_PROV G
	inner join G_PROV1 G1 on G1.LINK_UP = G.LINK
	inner join G_PROV2 G2 on G2.LINK_UP = G1.LINK
	inner join JURN_BO BO on BO.LINK_PO_PROV = G2.LINK and BO.LINK_DOC = @LinkOsnov
	
	/*WHERE LINK IN (SELECT GP1.LINK_UP FROM G_PROV1 GP1
	 WHERE GP1.LINK IN (SELECT GP2.LINK_UP FROM G_PROV2 GP2 
	   WHERE GP2.LINK IN (SELECT PROV_LINK FROM BD_JURN_BO WHERE AP1 = @LinkOsnov)))*/

	/* Грохаем из журнала зарегистрированные по данному обязаетльству БО */
	DELETE FROM JURN_BO WHERE LINK_DOC = @LinkOsnov

END
--	print @LinkOsnov
--	print @varKSparLINK




IF @@ROWCOUNT = 0
BEGIN	
  IF NOT EXISTS(SELECT * FROM dbo.OSNOV_VID WHERE OBJECT = @LinkObjCode)
	INSERT INTO dbo.OSNOV_VID(NAME,TYPE,OBJECT,[SYSTEM]) 	
	VALUES(@LinkObjName,1,@LinkObjCode,1)
	
	INSERT INTO dbo.OSNOV(TYPE_LINK,LINK_G_PROV) 
	SELECT TOP 1 LINK AS TYPE_LINK, @varKSparLINK AS LINK_G_PROV FROM dbo.OSNOV_VID WHERE OBJECT = @LinkObjCode
	SET @LinkOsnov = @@IDENTITY
END


DECLARE @Curs CURSOR,
        @dDate_Prov datetime,
     	@nSUMMA numeric(18,2),
		@iIstFin tinyint,
		@iCode varchar(8),  
		@iKBK int,
        @iSGU int,
		@iDOP int,
		@iDO  tinyint,
		@cComment varchar(254),
		@iLinkProv int,
		@iLinkBO int,
		@iEKR251 int,
		@iSign tinyint,
		@cDtCode varchar(10),
		@cKtCode varchar(10),
		@cProvErr varchar(100)

select @iEKR251 = LINK from dbo.KOSGU where CODE = '251'

SET @Curs = CURSOR FORWARD_ONLY FOR 
SELECT G.DATE_PROV,
		KBK = case EO.BO_DT_KT when 0 then isnull(GD.KBK, GK.KBK) else isnull(GK.KBK, GD.KBK) end,
		SGU = case EO.BO_DT_KT when 0 then isnull(case SD.AP_EKR when 1 then GD.EKR else GD.SGU end, case SK.AP_EKR when 1 then GK.EKR else GK.SGU end) 
										else isnull(case SK.AP_EKR when 1 then GK.EKR else GK.SGU end, case SD.AP_EKR when 1 then GD.EKR else GD.SGU end) end,
		DOP = case EO.BO_DT_KT when 0 then isnull(GD.AP2, GK.AP2) else isnull(GK.AP2, GD.AP2) end,
		IstFin = CONVERT(TINYINT,LEFT(SD.cSource,1)),
		DO = 0,
		COMMENT = 'Основание: ' + coalesce(G1.NAME_OPER, G2.NAME, ' не заполнен комментарий к проводке '),
		SUMMA = case EO.BO_MIN when 0 then G2.SUMMA else - G2.SUMMA end,
		DT_CODE = SD.CODE,
		KT_CODE = SK.CODE
FROM dbo.G_PROV G
inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK
inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK
inner join dbo.XOZ_OPER EO on G2.ECON_OPER = EO.LINK and EO.BO = 1 
inner join dbo.G_PROV_AP GD on GD.LINK_UP = G2.LINK AND GD.DB_KR = 0
inner join dbo.G_PROV_AP GK on GK.LINK_UP = G2.LINK AND GK.DB_KR = 1 
inner join dbo.S_ACCOUNTS SD on SD.LINK = GD.ACCOUNT
inner join dbo.S_ACCOUNTS SK on SK.LINK = GK.ACCOUNT
where G.DATE_PROV is not null and 
		G.LINK = @varKSparLINK and (SK.CODE LIKE '1.501._3' and GK.EKR = @iEKR251 or (SK.CODE not LIKE '1.501._3' and SK.CODE <> '1.502.11'))
union all
SELECT G.DATE_PROV,
		KBK = case EO.DO_DT_KT when 0 then isnull(GD.KBK, GK.KBK) else isnull(GK.KBK, GD.KBK) end,
		SGU = case EO.BO_DT_KT when 0 then isnull(case SD.AP_EKR when 1 then GD.EKR else GD.SGU end, case SK.AP_EKR when 1 then GK.EKR else GK.SGU end) 
										else isnull(case SK.AP_EKR when 1 then GK.EKR else GK.SGU end, case SD.AP_EKR when 1 then GD.EKR else GD.SGU end) end,
		DOP = case EO.DO_DT_KT when 0 then isnull(GD.AP2, GK.AP2) else isnull(GK.AP2, GD.AP2) end,
		IstFin = CONVERT(TINYINT,LEFT(SD.cSource,1)),
		DO = 1,
		COMMENT = 'Основание: ' + coalesce(G1.NAME_OPER, G2.NAME, ' не заполнен комментарий к проводке '),
		SUMMA = case EO.DO_MIN when 0 then G2.SUMMA else - G2.SUMMA end,
		DT_CODE = SD.CODE,
		KT_CODE = SK.CODE
FROM dbo.G_PROV G
inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK
inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK
inner join dbo.XOZ_OPER EO on G2.ECON_OPER = EO.LINK and EO.DO = 1 
inner join dbo.G_PROV_AP GD on GD.LINK_UP = G2.LINK AND GD.DB_KR = 0
inner join dbo.G_PROV_AP GK on GK.LINK_UP = G2.LINK AND GK.DB_KR = 1 
inner join dbo.S_ACCOUNTS SD on SD.LINK = GD.ACCOUNT
inner join dbo.S_ACCOUNTS SK on SK.LINK = GK.ACCOUNT
where G.DATE_PROV is not null and G.LINK = @varKSparLINK


OPEN @Curs
FETCH NEXT FROM @Curs INTO @dDate_Prov, @iKBK, @iSGU, @iDOP, @iIstFin, @iDO, @cComment, @nSUMMA, @cDtCode, @cKtCode
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @iLinkBO = NULL
	SET @iLinkProv = NULL
	
	/* Не хватает данных для формирования БО */
	IF (@iSGU IS NULL OR @iKBK IS NULL) 
	BEGIN
		insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
		values('Не сформировано ' + case @iDO when 1 then 'денежное' else 'бюджетное' end + ' обязательство по проводке ' + @cDtCode + ' - ' + @cKtCode + ' на сумму ' + ltrim(str(@nSUMMA,20,2)) + '. Незаполнена классификация.',1,2,1)		
	END
	else		
	begin
		
		INSERT INTO dbo.JURN_BO(LINK_DOC,DATE_DOC,LINK_KBK,LINK_SGU,SUMMA,LINK_ACCOUNT,IST_FIN,LINK_DOP,COMMENT, DO)
		VALUES(@LinkOsnov,@dDate_Prov,@iKBK,@iSGU,@nSUMMA,@LinkAcc,@iIstFin,@iDOP,@cComment, @iDO)
		
		SET @iLinkBO = @@IDENTITY
		if @iLinkBO is null
			insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
			values('Не сформировано ' + case @iDO when 1 then 'денежное' else 'бюджетное' end + ' обязательство по проводке ' + @cDtCode + ' - ' + @cKtCode + ' на сумму ' + ltrim(str(@nSUMMA,20,2)) + '. Ошибка при формировании.',1,2,1)		
		ELSE
		begin
			insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
			values('Cформировано ' + case @iDO when 1 then 'денежное' else 'бюджетное' end + ' обязательство по проводке ' + @cDtCode + ' - ' + @cKtCode + ' на сумму ' + ltrim(str(@nSUMMA,20,2)),1,0,1)		
			
			/* Сформируем проводки*/
			EXEC BD_JURN_BO_FORM_PROV @iLinkProv OUTPUT, @iLinkBO, @cProvErr OUTPUT 
			if @iLinkProv is null
				insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
				values('Не сформирована проводка по принятию обязательства. ' + isnull(@cProvErr,'Ошибка при формировании.'),1,2,2)		
			else
				insert into @tLog(txt, NEW_ROW, nSTATUS, nTAB) 
				values('Cформирована проводка по принятию обязательства. ',1,0,2)		
			
		end
		
		
	end
	FETCH NEXT FROM @Curs INTO @dDate_Prov, @iKBK, @iSGU, @iDOP, @iIstFin, @iDO, @cComment, @nSUMMA, @cDtCode, @cKtCode
END
CLOSE @Curs
DEALLOCATE @Curs

COMMIT TRAN 
select txt, NEW_ROW, nSTATUS, nTAB from @tLog order by ord
return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.XD_FORM_BO 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_get_tree_kbk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ro_get_tree_kbk]
GO

-- create table #TreeKBK (Link int, Link_Self int, Code_Row varchar(50), Link_Table int, Calc tinyint, cOrderTable varchar(10))

CREATE              PROCEDURE dbo.ro_get_tree_kbk
  @LF  int, @cTables varchar(100) = '', @LSF INT =NULL 
AS

	declare @ExecStr nvarchar(4000), @LC int, @LT int, @Dict varchar(8000), @OT tinyint, @NT varchar(254), @CodeForm VARCHAR(30), @link_org INT ,@link_budg INT, @begin_date DATETIME

   SELECT @link_org = rsf.[Link_Organization],
         @link_budg = ISNULL(rsf.[Link_Type_Svod], 0),
         @begin_date = rsf.[Begin_Date]
   FROM dbo.report_saved_forms rsf
   WHERE [Link_Saved_Form] = @LSF 
   
   SELECT @CodeForm = Code FROM dbo.[REPORT_FORMS] rf WHERE  rf.[Link_Form] = @LF
	set @ExecStr = ''
	select @ExecStr = @ExecStr + '
insert #TreeKBK (Link, Link_Self, Code_Row, Link_Table, Calc, cOrderTable) select distinct T.Link, T.Link_Self, T.Code, ' + LTRIM(STR(RT.Link_Table)) + ', childrens = convert(bit, case when T1.Link is NULL then 1 else 0 end), ''' + '№' + isnull(ltrim(STR(RT.orders)),'') + ' (' + RTRIM(RT.Name) + ')' + ''' from (select * from dbo.' + LTRIM(RC.Dictionary) + CASE WHEN RC.[Dictionary_Where] <> '' THEN ' where ' + REPLACE(REPLACE(REPLACE(RC.[Dictionary_Where], '%link_org%', LTRIM(STR(@link_org))), '%link_budg%', LTRIM(STR(@link_budg))), '%date%', '''' + CONVERT(VARCHAR(10), @begin_date, 112) + '''') ELSE '' END  
   + ') T left join (select * from dbo.' + LTRIM(RC.Dictionary)+ CASE WHEN RC.[Dictionary_Where] <> '' THEN ' where ' + REPLACE(REPLACE(REPLACE(RC.[Dictionary_Where], '%link_org%', LTRIM(STR(@link_org))), '%link_budg%', LTRIM(STR(@link_budg))), '%date%', '''' + CONVERT(VARCHAR(10), @begin_date, 112) + '''') ELSE '' END + ') T1 on T1.Link_Self = T.Link'
	from report_tables RT join report_coloumns RC on RT.Link_Code_Col = RC.Link_Col
	where RT.Link_Form = @LF and Doschet_Tree = 1 and isnull(RC.Dictionary, '') <> '' and (CHARINDEX(',' + LTRIM(RTRIM(STR(RT.Link_Table))) + ',', ',' + REPLACE(@cTables, ' ', '') + ',') > 0 or @cTables = '')
		and COLUMNPROPERTY(object_id('[dbo].' + LTRIM(RTRIM(RC.Dictionary))), 'Link_Self', 'AllowsNull') is NOT NULL

	exec sp_executesql @ExecStr
	
  -- исключения
   INSERT #TreeExclude (Code, Link_COl)
   SELECT NAME, (SELECT [Link_COl] FROM dbo.[REPORT_COLOUMNS] WHERE [Link_Table] = T.[Link_Table] AND [Orders] = CONVERT(INT,add_info))
   FROM dbo.[REPORT_KBK] K
         JOIN (SELECT [DICTIONARY], [RC].[Link_Table]  
                              FROM dbo.[REPORT_COLOUMNS] RC JOIN dbo.[REPORT_TABLES] RT ON RC.[Link_Table] = RT.[Link_Table] AND RC.[Link_Col] = RT.[Link_Code_Col] 
                              WHERE RT.[Link_Table] IN (SELECT DISTINCT [Link_Table] FROM #TreeKBK)) T ON K.[Code_str] = T.[Dictionary] 
   WHERE [Code_Form] = 'R_SPR_TREE_EXCLUDE' AND (isnull(long_name, @CodeForm) = @CodeForm OR ISNULL(long_name, '') = '')


GO
GRANT ALL ON dbo.[ro_get_tree_kbk] 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].[BK_FORM_SAVE_DOCUMENT_ZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BK_FORM_SAVE_DOCUMENT_ZB]
GO
/*
© Кейсистемс (Keysystems), 2005
*/


CREATE PROCEDURE dbo.BK_FORM_SAVE_DOCUMENT_ZB
	@varKScCode varchar(30),
	@varKSRealCode varchar(30) = null,
	@varKSDocType smallint = 0		
AS
BEGIN
	IF @varKSRealCode is null
		SET @varKSRealCode = @varKScCode
	DECLARE
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSRefLINK	int,
		@varKSCurCODE	varchar(30),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(100),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(8000),
		@varKSCur_Str	varchar(8000),
		@varKSADDTYPE	varchar(100),
		@varKScResCode	varchar(100),
		@varKSchrNAME	varchar(100),
		@varKSObjectName	varchar(254)

	DECLARE 
		@varKSpartParams		varchar(8000),
		@varKSpartDiction	varchar(8000),
		@varKSpartDictionApp	varchar(8000),
		@varKSpartDictionRef	varchar(8000),
		@varKSpartBanks		varchar(8000),
		@varKSpartDepartments	varchar(8000),
		@varKSpartOsnov		varchar(8000),
		@varKSpartDep_ACCT	varchar(8000),
		@varKSpartSubdiv	varchar(8000),
		@varKSSaveMethod	varchar(8000),
		@varKSpartTest		varchar(8000),
		@varKSpartAdditions	varchar(8000),
		@varKSpartS_ACCOUNTS	varchar(8000),
		@varKSchrCodeType	varchar(100),
		@varKSchrNameType	varchar(100),
		@varKSchrRefField	varchar(100),
		@varKSOLDPartNum	int,
		@varKShostTypeObject 	varchar(30),
		@varKSchrRefDict	varchar(30),

		@varKSpartEmpl	varchar (8000),
		@varKSpartKBK	varchar (8000),
		@varKSpartINVENTORY	varchar (8000),
		@varKSpartMENU_DECOMPOSE varchar (8000),
		@varKSpartFINANSE	varchar(8000),
		@varKSpartCOMISSION	VARCHAR (8000)

	SELECT @varKSnLink = LINK, @varKSObjectName = NAME FROM S_OBJECTS WHERE CODE = @varKScCode

PRINT '---------------'+@varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END
	Select @varKSType=NAME FROM S_OBJECTS WHERE CODE=@varKScCode
	print '('+@varKSType+')'

	DECLARE SEL_CURSOR CURSOR STATIC LOCAL
	FOR SELECT LINK, CODE, NAME
		FROM S_OBJECTS SO
		WHERE LINK_SELF=@varKSnLink AND (SELECT CODE FROM S_OBJECTS WHERE LINK=SO.LINK_CLASS)='EDIT_FIELD_CLASS'
		ORDER BY ORDERS

SET	@varKSpartParams	= ''
SET	@varKSpartTest	= ''
SET	@varKSpartDictionApp	= ''
SET	@varKSpartDictionRef	= ''
SET	@varKSchrCodeType	= ''
SET	@varKSchrNameType	= ''
SET @varKSpartBanks	= ''
SET @varKSpartDepartments	= ''
SET @varKSpartOsnov	= ''
SET @varKSpartDep_ACCT	= ''
SET @varKSpartSubdiv = ''

SET @varKSpartS_ACCOUNTS = ''
SET @varKSpartEmpl  = ''
SET @varKSpartKBK = ''
SET @varKSpartINVENTORY = ''
SET @varKSpartMENU_DECOMPOSE = ''
SET @varKSpartFINANSE = ''

IF exists(select * from workmode where @varKScCode like 'FINANS_ASSIGN%' OR @varKScCode like 'FINANS_LIMIT%')
BEGIN
	SET @varKSpartFINANSE = '
		-- Финансовые документы могут быть тока в единственном экземпляре за период
	IF exists(Select * From G_PROV where link <> @varKSpLINK AND object = ' + LTRIM(STR(@varKSnLink)) + ' and date_prov is not null 
		and year(date) = year(@varKSpDATE) AND Get_Store = @varKSPMonth and DEP = @varKSpDEP_LINK )
		RETURN 1
	'
END

EXECUTE X_FORM_SAVE_DOCUMENT_ADDTIONS @varKScCode, @varKSpartAdditions OUTPUT
IF @varKSRealCode = @varKScCode
	SET	@varKSSaveMethod		= 'NUMBER, '+CASE WHEN @varKSDocType = 1 THEN 'SQLNULL(YEAR)' ELSE 'SQLNULL(DATE)' END+', SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL (ACC_LINK)' 
			+ CASE WHEN exists(Select * FROM DICTIONARY_STORAGE_DOCUMENTS
						WHERE DOC_CODE = @varKScCode)
					THEN ', GET_STORE'
				ELSE '' END	
ELSE
	SET	@varKSSaveMethod		= ''

/*
IF @varKSDocType = 3
	SET @varKSSaveMethod = @varKSSaveMethod + 
		',"+" SQLNULL(CHAIRMAN), SQLNULL(MEMB1), SQLNULL(MEMB2), SQLNULL(MEMB3), SQLNULL(MEMB4), SQLNULL(MEMB5), SQLNULL(MEMB6), SQLNULL(DOC_NUM), SQLNULL(DOC_DATE)'
*/
	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_SAVE_DOCUMENT_ZB 
--'+LTRIM(convert(char, getdate()))+'
PROCEDURE dbo.X_SAVE_'+@varKScCode

	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSchrRefField OUTPUT
		IF Convert(int, @varKSInALIAS)&1 = 1
			AND (@varKSStorage = 'VALUE' 
				OR @varKSStorage IN( 'DICTION', 'G_PROV', 'BANKS', 'DEPARTMENTS', 'OSNOV', 'DEPARTMENT_ACCOUNTS', 'SUBDIV',
					'INVENTORY', 'KL_KBK', 'EMPL', 'KOSGU', 'MENU_DECOMPOSE', 'S_ACCOUNTS')
			AND @varKSchrRefField = 'LINK' )
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT',  @varKSchrRefDict OUTPUT

			SET @varKShostTypeObject = @varKSCurCODE
			IF @varKSStorage = 'DICTION' AND @varKSchrRefField <> 'LINK'
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, OBJECT_VALUES OVF, OBJECT_VALUES OVS,
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = (Select LINK from S_OBJECTS where CODE = @varKSchrRefDict)
						AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSchrRefField
						AND OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION'
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'DICTION_APP'
			BEGIN
				SET @varKShostTypeObject = @varKSchrRefField

				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END

			EXECUTE X_GET_PROP  @varKSCurCODE, 'TYPE_FIELD_DICT', @varKSType OUTPUT
			SET @varKSType = UPPER(LTRIM(RTRIM(@varKSType)))
			IF @varKSType = 'DATETIME'
				SET @varKSADDTYPE=',104'
			ELSE
				SET @varKSADDTYPE=''
			
		
			IF 
				@varKSStorage = 'VALUE' OR 
				(
					(@varKSStorage = 'G_PROV' 
					OR @varKSStorage = 'DICTION' 
					OR @varKSStorage = 'BANKS' 
					OR @varKSStorage = 'DEPARTMENTS' 
					OR @varKSStorage = 'OSNOV' 
					OR @varKSStorage = 'DEPARTMENT_ACCOUNTS' 
					OR @varKSStorage = 'SUBDIV'
					OR @varKSStorage = 'EMPL'
					OR @varKSStorage = 'KL_KBK'
					OR @varKSStorage = 'KOSGU'
					OR @varKSStorage = 'INVENTORY'
					OR @varKSStorage = 'MENU_DECOMPOSE'
					OR @varKSStorage = 'S_ACCOUNTS'
					) 
					AND @varKSchrRefField = 'LINK'
				)
			BEGIN

				IF 	(				
					@varKSStorage = 'G_PROV' 
					OR @varKSStorage = 'DICTION' 
					OR @varKSStorage = 'BANKS' 
					OR @varKSStorage = 'DEPARTMENTS' 
					OR @varKSStorage = 'OSNOV' 
					OR @varKSStorage = 'DEPARTMENT_ACCOUNTS' 
					OR @varKSStorage = 'SUBDIV'
					OR @varKSStorage = 'EMPL'
					OR @varKSStorage = 'KL_KBK'
					OR @varKSStorage = 'KOSGU'
					OR @varKSStorage = 'INVENTORY'
					OR @varKSStorage = 'MENU_DECOMPOSE'
					OR @varKSStorage = 'S_ACCOUNTS'
				) SET @varKSType = 'INT'
				SET @varKSpartParams = @varKSpartParams + ',' + CHAR(13) + CHAR(10) + '	@varKSp' + @varKSShortCode + SPACE(15-LEN(@varKSShortCode)) + @varKSType + ' = null'

				SET @varKSOLDPartNum = FLOOR(LEN(@varKSSaveMethod)/200)
				IF (@varKSStorage = 'DICTION' 
					OR @varKSStorage = 'BANKS' 
					OR @varKSStorage = 'DEPARTMENTS' 
					OR @varKSStorage = 'OSNOV' 
					OR @varKSStorage = 'DEPARTMENT_ACCOUNTS' 
					OR @varKSStorage = 'SUBDIV'
					OR @varKSStorage = 'EMPL'
					OR @varKSStorage = 'KL_KBK'
					OR @varKSStorage = 'KOSGU'
					OR @varKSStorage = 'INVENTORY'
					OR @varKSStorage = 'MENU_DECOMPOSE'
					OR @varKSStorage = 'S_ACCOUNTS'
				) AND @varKSchrRefField = 'LINK' OR @varKSType = 'DATETIME'
					SET @varKSSaveMethod = @varKSSaveMethod + CASE WHEN @varKSSaveMethod = '' THEN '' ELSE ', ' END +'SQLNULL(' + @varKSShortCode + ')'
				ELSE
					SET @varKSSaveMethod = @varKSSaveMethod + CASE WHEN @varKSSaveMethod = '' THEN '' ELSE ', ' END + @varKSShortCode

				IF FLOOR(LEN(@varKSSaveMethod)/200) > @varKSOLDPartNum
					SET @varKSSaveMethod = @varKSSaveMethod + '"+"'
			END

			IF @varKSShortCode is null OR LTRIM(@varKSShortCode)=''
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			ELSE
			BEGIN
				IF @varKSStorage='VALUE'
					SET @varKSpartDictionApp = @varKSpartDictionApp + '
	--'+ @varKSchrNAME + CASE 
					WHEN UPPER(LTRIM(RTRIM(@varKSType))) LIKE '%CHAR%' THEN '
	EXEC @varKSERROR = dbo.X_UPDATE_G_PROV_VALUE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
					ELSE '
	SET @varKSstrVALUE = Convert(varchar(7000), @varKSp' + @varKSShortCode + @varKSADDTYPE + ')
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_VALUE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSstrVALUE
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				END

			IF @varKSStorage = 'DICTION' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDictionRef = @varKSpartDictionRef +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_DICTION @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'BANKS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartBanks = @varKSpartBanks +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_BANK @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'DEPARTMENTS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDepartments = @varKSpartDepartments +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_DEPARTMENT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'OSNOV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartOsnov = @varKSpartOsnov +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_OSNOV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'DEPARTMENT_ACCOUNTS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDep_ACCT = @varKSpartDep_ACCT +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_DEP_ACCT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'SUBDIV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartSubdiv = @varKSpartSubdiv +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_SUBDIV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
			IF @varKSStorage = 'EMPL' AND @varKSchrRefField = 'LINK'
				SET @varKSpartEmpl = @varKSpartEmpl +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_EMPL @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'KL_KBK' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKBK = @varKSpartKBK +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_KBK @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'KOSGU' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKBK = @varKSpartKBK +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_SGU @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'INVENTORY' AND @varKSchrRefField = 'LINK'
				SET @varKSpartINVENTORY = @varKSpartINVENTORY +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_INVENTORY @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'MENU_DECOMPOSE' AND @varKSchrRefField = 'LINK'
				SET @varKSpartMENU_DECOMPOSE = @varKSpartMENU_DECOMPOSE +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.PV_UPDATE_G_PROV_MENU_DECOMPOSE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'S_ACCOUNTS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartS_ACCOUNTS = @varKSpartS_ACCOUNTS +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_S_ACCOUNTS @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			IF @varKSStorage = 'G_PROV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDictionRef = @varKSpartDictionRef +'
	--'+ @varKSchrNAME + '
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_REF @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
			END
			
			IF Convert(int, @varKSInALIAS)&2 = 2
			BEGIN
				SET @varKSpartTest = @varKSpartTest + '	IF @varKSp' + @varKSShortCode + ' IS NULL'
				IF @varKSStorage = 'DICTION_REF'
					SET @varKSpartTest = @varKSpartTest + ' OR @varKSp' + @varKSShortCode + ' = 0'
				ELSE
				BEGIN
					SET @varKSpartTest = @varKSpartTest + 
					CASE 
					WHEN LEFT(@varKSType, 7) = 'NUMERIC'
					  THEN ' OR @varKSp' + @varKSShortCode	+ ' = 0.0'
					WHEN @varKSType = 'DATETIME'
					  THEN ' OR @varKSp' + @varKSShortCode	+ ' = ''19000101'''
					WHEN @varKSType IN ('INT', 'TINYINT', 'BIGINT', 'SMALLINT', 'MONEY', 'SMALLMONEY')
					  THEN ' OR @varKSp' + @varKSShortCode	+ ' = 0'
					WHEN LEFT(@varKSType, 7) = 'VARCHAR' OR LEFT(@varKSType, 4) = 'CHAR'
					  THEN ' OR @varKSp' + @varKSShortCode	+ ' = '''''
					END
				END
				SET @varKSpartTest = @varKSpartTest + 
'
	BEGIN
		ROLLBACK
		RETURN 5
	END
'
			END
		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	END
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR

	
	SET @varKScResCode = 'X_SAVE_' + @varKScCode
	IF object_id(@varKScResCode) is not null
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str



	SET @varKSSel_Str = @varKSSel_Str + 
'
	@varKSpLINK		int	OUTPUT'+
CASE WHEN @varKScCode = @varKSRealCode THEN ',
	@varKSpNUMBER	char(25) = null,
	'+CASE WHEN @varKSDocType = 1 THEN '@varKSpYEAR		int'  ELSE '@varKSpDATE		datetime' END +' = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment	varchar(254) = null,
	@varKSpDEP_LINK	INT	=	NULL,
	@varKSpACC_LINK INT	=	NULL'

/*+ CASE WHEN @varKSDocType = 3 THEN ',
	@varKSpCHAIRMAN	int = null,
	@varKSpMEMB1	int = null,
	@varKSpMEMB2	int = null,
	@varKSpMEMB3	int = null,
	@varKSpMEMB4	int = null,
	@varKSpMEMB5	int = null,
	@varKSpMEMB6	int = null,
	@varKSpDOC_NUM VARCHAR(30) = null,
	@varKSpDOC_DATE DATETIME = null'
ELSE '' END
*/
+CASE WHEN exists(Select * FROM DICTIONARY_STORAGE_DOCUMENTS WHERE DOC_CODE = @varKScCode) THEN ',
	@varKSpGET_STORE tinyint = 0' ELSE '' END
	ELSE ''
	END 
	SET @varKSSel_Str = @varKSSel_Str + @varKSpartParams 
+CASE WHEN @varKSDocType = 2 THEN ',
	@varKSPMonth		tinyint = null' else '' end + '
AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKStrancount	int'+CASE WHEN @varKSDocType = 1 THEN',
		@varKSpDATE		datetime
SET @varKSpDATE = Convert(datetime, RTRIM(STR(@varKSpYEAR)) + right(''0''+ltrim(rtrim(str(coalesce(@varKSPMonth,1)))),2) + ''01'', 112)' ELSE '' END +'
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
' + CASE WHEN @varKScCode = @varKSRealCode THEN 
'	--Проверка рабочего периода'+CASE WHEN @varKSDocType = 1 THEN '
	IF not exists(Select * from admin_info Where @varKSpYEAR BETWEEN YEAR(BEGINDATE) AND YEAR(ENDDATE) OR YEAR(ENDDATE) = @varKSpYEAR + 1)'
ELSE '
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)'
END+'
	BEGIN
		ROLLBACK
		RETURN 15
	END
' + @varKSpartAdditions + '
	--Проверка обязательных реквизитов
'+ @varKSpartTest + 
case when @varKSDocType = 2 THEN '
	SET @varKSPMonth = @varKSPMonth + 100
'  ELSE '' END + 
@varKSpartFINANSE + 
'
	--Вставка/обновление G_PROV
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV @varKSpLINK OUTPUT, @varKSpNUMBER, @varKSpDATE, ' + LTRIM(STR(@varKSnLink)) + ',@varKSpDATE_PROV, @varKSpSumma, @varKSpComment'
+CASE WHEN @varKSDocType = 2 THEN ',@varKSPMonth, @varKSpDEP_LINK'
	WHEN exists(Select * FROM DICTIONARY_STORAGE_DOCUMENTS WHERE DOC_CODE = @varKScCode) THEN ', @varKSpGET_STORE, @varKSpDEP_LINK, @varKSpACC_LINK'
	ELSE ', 0, @varKSpDEP_LINK, @varKSpACC_LINK'
END+
'
	IF @varKSERROR <> 0
		RETURN @varKSERROR'
ELSE '' END +
'	--Вставка/обновление G_PROV_VALUE'
 + @varKSpartDictionApp + 

'
	--Вставка/обновление G_PROV_DICTION
' + @varKSpartDictionRef 
+ 

'
	--Вставка/обновление G_PROV_BANK
' + @varKSpartBanks 

+ 
'
	--Вставка/обновление G_PROV_DEPARTMENT
' + @varKSpartDepartments

+
'
	--Вставка/обновление G_PROV_OSNOV
' + @varKSpartOsnov

+ 
'
	--Вставка/обновление G_PROV_DEP_ACCT
' + @varKSpartDep_ACCT 

+ 
'
	--Вставка/обновление G_PROV_SUBDIV
' + @varKSpartSubdiv 

+ 
'
	--Вставка/обновление G_PROV_EMPL
' + @varKSpartEmpl

+ 
'
	--Вставка/обновление G_PROV_KBK
' + @varKSpartKBK

+ 
'
	--Вставка/обновление G_PROV_INVENTORY
' + @varKSpartINVENTORY
+
'
	--Вставка/обновление G_PROV_MENU_DECOMPOSE
' + @varKSpartMENU_DECOMPOSE
+
'
	--Вставка/обновление G_PROV_S_ACCOUNTS
' + @varKSpartS_ACCOUNTS
+
CASE WHEN @varKScCode = @varKSRealCode THEN
'
	--Событие системного журнала
	SET @varKSEventText = '''+RTRIM(@varKSObjectName)+''' + '' №'' + RTRIM(@varKSpNUMBER) + '
		+CASE WHEN @varKSDocType = 1 THEN ''' за '' + convert(varchar, @varKSpYEAR) + '' год'''
		ELSE ''' от '' + convert(varchar, @varKSpDATE, 104)' END +'
	EXECUTE WF_GENERATEEVENT ''Сохранение документа'', @varKSEventText, ' + LTRIM(STR(@varKSnLink)) + ', ''G_PROV'', @varKSpLINK'
	ELSE '' END + '
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0
'
	
	
	EXECUTE (@varKSSel_Str)
	DECLARE @varKSprocname varchar(254), @varKSmakeby varchar(254),
		@strSAVE_METHOD	VARCHAR (8000)

	SELECT @varKSprocname = 'X_SAVE_'+@varKScCode, @varKSmakeby = 'EXECUTE BK_FORM_SAVE_DOCUMENT_ZB ''' + @varKScCode+''', '+case when @varKSRealCode is null then 'null, ' else ''''+@varKSRealCode+''', ' end + convert(varchar, @varKSDocType)
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKSprocname, @varKSmakeby

	SELECT @strSAVE_METHOD =  CASE WHEN @varKSDocType = 3
			THEN 'BK_SAVE_DOC_WITH_COMISSION (''X_SAVE_'+@varKScCode+''', m.cAlias,"'+@varKSSaveMethod+
				'", "SQLNULL(BC_LINK), SQLNULL(LINK_PRED), SQLNULL(DOC_DATE), SQLNULL(DOC_NUM)", "'
				+ @varKScCode+'")' 
			ELSE 'X_SAVE(''X_SAVE_'+@varKScCode+''', m.cAlias,"'+@varKSSaveMethod+'","'+@varKScCode+'")' 
		END

	UPDATE OBJECT_VALUES
	SET VALUE = @strSAVE_METHOD,
		INHERITED = 0
	WHERE OBJECT = @varKSnLink
			AND PROPERTY = (SELECT LINK FROM S_PROPERTY WHERE CODE = 'SAVE_OBJECT_METHOD')
			AND (VALUE IS NULL OR VALUE ='' OR INHERITED = 1)
	IF @@ROWCOUNT = 0
		PRINT @strSAVE_METHOD

	UPDATE S_DBObjects SET Rights = 0xA WHERE Object=@varKSnLink AND DBObject=@varKScResCode
	IF @@ROWCOUNT = 0	
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScResCode, 0xA)

	UPDATE OBJECT_VALUES
	SET VALUE = 'I_DELETE_RECORDS (m.cAlias,"' +@varKScCode+ '", "BV_DELETE_DOCUMENTS", 4, .F., .F.)',
		INHERITED = 0
	WHERE OBJECT = @varKSnLink
			AND PROPERTY = (SELECT LINK FROM S_PROPERTY WHERE CODE = 'REMOVE_OBJECT_METHOD')
			AND (VALUE IS NULL OR VALUE ='' OR INHERITED = 1)

	IF @@ROWCOUNT = 0
		PRINT 'I_DELETE_RECORDS (m.cAlias,"' +@varKScCode+ '", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'

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].[RO_WEB_CHANGE_STATUS_gotov]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_CHANGE_STATUS_gotov]
GO




/*
© Кейсистемс (Keysystems), 2006
	Вызов в тонком процедуры изменения статуса
*/
CREATE  PROCEDURE dbo.RO_WEB_CHANGE_STATUS_gotov
	@varKStableName varchar(100), -- таблица с линками отчетов для внутридокументной проверки
	@varDocCode	varchar(30) = NULL, -- код объекта
	@cText varchar(254) = '' output -- список возвращаемых полей
AS
	set @cText  = 'Результат'

	declare @text varchar(250), @varKSsFLink varchar(8000), @ExecStr varchar(8000), @iMinECP INT
   DECLARE @t_not_ECP TABLE  (lsf INT)
	set @text = ''
   SET @iMinECP = ISNULL((SELECT val_int FROM dbo.report_options WHERE razdel = 'ECP' AND Code = 'MinECP'), 0)
	create table #ListForms(lsf int)
	
	if RTRIM(ISNULL(@varKStableName,'')) <> '' and (select object_id('tempdb..' + @varKStableName)) is NOT NULL
	begin
		set @ExecStr = 'insert #ListForms (lsf) select * from ' + @varKStableName + ' drop table ' + @varKStableName
		execute(@ExecStr)
	END
   
   INSERT @t_not_ECP (lsf)
   SELECT lsf
   FROM #ListForms LF WHERE ISNULL((SELECT COUNT(*) FROM dbo.report_sign RS WHERE RS.[lsf] = LF.lsf), 0) < @iMinECP

   IF EXISTS(SELECT * FROM @t_not_ECP) AND isnull((select sert_name from user_sert where sid = suser_sid()),'') <> ''
   BEGIN
      SELECT
         res
      FROM
         (SELECT 'Необходимо подписать отчеты. Следующие отчеты не имеют <B> ' + LTRIM(RTRIM(STR(@iMinECP))) + '</B> ЭЦП:' AS RES, 1 AS orders 
         UNION 
         SELECT RTRIM(RF.Code) + ' ' + RTRIM(rsf.[atr]), 2 AS orders
         FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN @t_not_ECP T ON rsf.[Link_Saved_Form] = T.[lsf]
            JOIN dbo.report_forms RF ON RF.[Link_Form] = rsf.[Link_Form]) A
      ORDER BY orders 
      RETURN 1 
   END

	set @varKSsFLink = ''
	select @varKSsFLink = @varKSsFLink + LTRIM(STR(lsf)) + ' '
	from #ListForms

	drop table #ListForms
	exec dbo.RO_CHANGE_STATUS 1, @varKSsFLink, 1

GO
GRANT ALL ON RO_WEB_CHANGE_STATUS_gotov 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].[RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE]
GO



/*
c Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE  
	@res varchar(250) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	DECLARE @intPER_TYPE	INT,
		@intPER_NUM	INT

	set @res = ''
	if @varcStr = 'ОКАТО'
	begin
		SELECT @Res = REPLACE(DEP.OKATO, ' ', '') FROM DICTIONARY_DEPARTMENT DEP inner join report_saved_forms RSF on RSF.Link_Saved_Form = @variLSF and DEP.link = RSF.Link_Organization
		return 0
	end
	if @varcStr = 'БЛОК1'
	begin
		SELECT @res = CASE WHEN LEN(ISNULL(DOH_CODE, '')) = 0 THEN '-' ELSE DOH_CODE END FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '160'
	begin
		SELECT @res = ISNULL(CODE520, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '200'
	begin
		SELECT @res = ISNULL(CODE200, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '210'	
	begin
		SELECT @res = ISNULL([PERCENT], 0.00) FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '240'
	begin
		SELECT @res = ISNULL(CODE240, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = 'Т.Н.ДОХ.КОД'
	begin
		SELECT @Res = ISNULL(TDOH_CODE, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end

	-- Код налогового периода --
	IF @varcStr = 'КОД_НАЛ_ПЕР'
	BEGIN
		SELECT @intPER_TYPE	=	PERIOD_TYPE,
			@intPER_NUM	=	PERIOD_NUMBER
		FROM dbo.REPORT_SAVED_FORMS RSF 
		WHERE RSF.Link_Saved_Form = @variLSF
		
		IF @intPER_TYPE	= 1
			SET @Res = '34'

		IF @intPER_TYPE	= 2
			SET @Res =
				CASE
					WHEN @intPER_NUM = 1 THEN '21'
					WHEN @intPER_NUM = 2 THEN '31'
					WHEN @intPER_NUM = 3 THEN '33'
					ELSE '34'
				END	
		RETURN 0
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE to public
GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_REP_SAL_GOS_EMPLS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_REP_SAL_GOS_EMPLS]

GO

CREATE PROC dbo.SA_REP_SAL_GOS_EMPLS (@DATE DATETIME, @TR tinyint = 0)
---
AS

SET @DATE = (CASE WHEN DAY(@DATE) = 1 THEN @DATE - 1 ELSE @DATE END)

DECLARE @DEP_LINK INT
EXEC dbo.xd_whats_zb @DEP_LINK OUTPUT

CREATE TABLE #SAL_CJ (GR_ID INT, kat_gs_code VARCHAR(2), gr_gs_code VARCHAR(2), kl_chin VARCHAR(2),
			NAME_POST VARCHAR(254), WAY_CALC tinyint, NAME_PAYS VARCHAR(254),
			MON tinyint, SUMMA NUMERIC(20,2)
			)

DECLARE @LinkEKR211 INT
SET @LinkEKR211 = (SELECT LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211')

INSERT INTO #SAL_CJ (kat_gs_code, gr_gs_code, kl_chin, NAME_POST, WAY_CALC, NAME_PAYS, MON, SUMMA)
SELECT 
	kat_gs_code, gr_gs_code, kl_chin, NAME_POST, WAY_CALC, NAME_PAYS, MONTH_BEGIN as MON, ROUND(SUM(SUMMA) / (CASE WHEN @TR = 1 THEN 1000 ELSE 1 END),2) as SUMMA
FROM 
	dbo.GetGSGREmplToDepAndDate(@DEP_LINK,@DATE,1) E inner join dbo.SALARY_JURNAL_CALCULAT S on E.empl_link = S.link_empl
WHERE 
	LINK_DEP = @DEP_LINK
	and YEAR_BEGIN =YEAR(@DATE) and MONTH_BEGIN <= MONTH(@DATE)
	and typ_oper = 1 
	AND COALESCE(S.LINK_EKR,@LinkEKR211) = @LinkEKR211
GROUP BY
	kat_gs_code, gr_gs_code, kl_chin, NAME_POST, WAY_CALC, NAME_PAYS, MONTH_BEGIN
--группы
CREATE TABLE #GRP (ID INT NOT NULL IDENTITY(1,1), kat_gs_code VARCHAR(2), gr_gs_code VARCHAR(2), kl_chin VARCHAR(2), NAME_POST VARCHAR(254))
INSERT INTO #GRP (kat_gs_code, gr_gs_code, kl_chin, NAME_POST)
SELECT DISTINCT kat_gs_code, gr_gs_code, kl_chin, NAME_POST FROM #SAL_CJ 

UPDATE #SAL_CJ
SET GR_ID = G.[ID]
FROM 
	#GRP G INNER JOIN #SAL_CJ S ON 
		LTRIM(RTRIM(COALESCE(G.kat_gs_code,''))) = LTRIM(RTRIM(COALESCE(S.kat_gs_code,''))) 
		AND LTRIM(RTRIM(COALESCE(G.gr_gs_code,''))) = LTRIM(RTRIM(COALESCE(S.gr_gs_code,''))) 
		AND LTRIM(RTRIM(COALESCE(G.kl_chin,''))) = LTRIM(RTRIM(COALESCE(S.kl_chin,'')))
		AND LTRIM(RTRIM(COALESCE(G.NAME_POST,''))) = LTRIM(RTRIM(COALESCE(S.NAME_POST,'')))


--Зарплата кроме должнотного оклада и оклада за кланый чин
CREATE TABLE #NADB (GR_ID INT, NP VARCHAR(254), S NUMERIC(20,2))
--Вся зарплата  начала года
CREATE TABLE #ZP (GR_ID INT, S NUMERIC(20,2))
--Должнотной оклад
CREATE TABLE #OKLAD (GR_ID INT, S NUMERIC(20,2))
--Оклад за кл. чин 1 класса
CREATE TABLE #CHIN1 (GR_ID INT, S NUMERIC(20,2))
--Оклад за кл. чин 2 класса
CREATE TABLE #CHIN2 (GR_ID INT, S NUMERIC(20,2))
--Оклад за кл. чин 3 класса
CREATE TABLE #CHIN3 (GR_ID INT, S NUMERIC(20,2))
--Оклад за кл. чин без класса
CREATE TABLE #CHIN4 (GR_ID INT, S NUMERIC(20,2))

----
INSERT INTO #NADB
SELECT 
	GR_ID, NAME_PAYS, sum(SUMMA)
FROM 
	#SAL_CJ 
WHERE 
	WAY_CALC not in (select code from way_calc where type = 1 and oklad = 1)
	AND 
	NAME_PAYS not like '%чин%'
	AND
	MON <= MONTH(@DATE)
GROUP BY 
	GR_ID, NAME_PAYS

----
INSERT INTO #NADB
SELECT 
	G.[ID], T.NP, 0
FROM 
	#GRP G, (SELECT TOP 1 NP FROM #NADB) T
WHERE 
	G.[ID] not in (select GR_ID from #NADB)

---
DECLARE @varKSTABLE_N VARCHAR(100)
EXEC X_GET_TABLE_NAME @varKSTABLE_N OUTPUT

DECLARE @varKSCNT_N INT

EXEC M_CROSS_TABLE
	'GR_ID', 
	'NP', 'VARCHAR(254)', 
	'S', 'NUMERIC(20,2)', 'SUM(S) AS S',
	'#NADB', @varKSTABLE_N

DECLARE @CNT_N int
SELECT @CNT_N = COUNT(DISTINCT NP) FROM #NADB 

--Вся зарплата  начала года
INSERT INTO #ZP
SELECT 
	GR_ID, sum(SUMMA)
FROM 
	#SAL_CJ 
GROUP BY 
	GR_ID

--Должнотной оклад
INSERT INTO #OKLAD
SELECT 
	GR_ID, sum(SUMMA)
FROM 
	#SAL_CJ 
WHERE 
	WAY_CALC in (select code from way_calc where type = 1 and oklad = 1)
GROUP BY 
	GR_ID

--Оклад за кл. чин 1 класса
INSERT INTO #CHIN1
SELECT 
	GR_ID, sum(SUMMA)
FROM 
	#SAL_CJ C INNER JOIN #GRP G ON C.GR_ID=G.[ID]
		INNER JOIN dbo.DICTIONARY_CHIN D ON G.kl_chin = D.CODE
WHERE 
	NAME_PAYS like '%чин%' and D.[CODE]  = 1
GROUP BY 
	GR_ID

--Оклад за кл. чин 2 класса
INSERT INTO #CHIN2
SELECT 
	GR_ID, sum(SUMMA)
FROM 
	#SAL_CJ C INNER JOIN #GRP G ON C.GR_ID=G.[ID]
		INNER JOIN (Select distinct CODE from dbo.DICTIONARY_CHIN) D ON G.kl_chin = D.CODE
WHERE 
	NAME_PAYS like '%чин%' and D.[CODE] = 2
GROUP BY 
	GR_ID

--Оклад за кл. чин 3 класса
INSERT INTO #CHIN3
SELECT 
	GR_ID, sum(SUMMA)

FROM 
	#SAL_CJ C INNER JOIN #GRP G ON C.GR_ID=G.[ID]
		INNER JOIN (Select distinct CODE from dbo.DICTIONARY_CHIN) D ON G.kl_chin = D.CODE
WHERE 
	NAME_PAYS like '%чин%' and D.[CODE] = 3
GROUP BY 
	GR_ID

--Оклад за кл. чин без класса
INSERT INTO #CHIN4
SELECT 
	GR_ID, sum(SUMMA)
FROM 
	#SAL_CJ C INNER JOIN #GRP G ON C.GR_ID=G.[ID]
		LEFT JOIN (Select distinct CODE from dbo.DICTIONARY_CHIN) D ON G.kl_chin = D.CODE
WHERE 
	NAME_PAYS like '%чин%' and D.[CODE] is null
GROUP BY 
	GR_ID
---

DECLARE @SQL1 varchar(8000), @SQL2 varchar(8000), @i int, @TMP VARCHAR(100)

IF @CNT_N = 0 BEGIN
	EXEC (' ALTER TABLE ' + @varKSTABLE_N + ' ADD NP_0 VARCHAR(254), S_0 numeric(20,2) ')
	SET @SQL1 = ' NP_0'
	SET @SQL2 = 'S_0 = SUM(S_0)'
END
ELSE BEGIN
	SET @i = 1
	WHILE @i <= @CNT_N BEGIN
		SET @SQL1 = CASE WHEN LEN(@SQL1) > 0 THEN @SQL1 + ', ' ELSE '' END  
		SET @SQL2 = CASE WHEN LEN(@SQL2) > 0 THEN @SQL2 + ', ' ELSE '' END  

		SET @SQL1 = @SQL1 + ' NP_' + LTRIM(RTRIM(CONVERT(VARCHAR(4),@i)))
		SET @TMP = 'S_' + LTRIM(RTRIM(CONVERT(VARCHAR(4),@i)))
		SET @SQL2 = @SQL2 + ' ' + @TMP + ' = SUM(' + @TMP + ')'

		SET @i = @i + 1
	END
END

---
DECLARE @SQL VARCHAR(8000)
SET @SQL = 
'SELECT GR.CODE, GR.NAME, G.NAME_POST, SUM(Z.S) as Z, SUM(O.S) as O, SUM(C1.S) as C_1, SUM(C2.S) as C_2, SUM(C3.S) as C_3, SUM(C4.S) as C_4, ' + @SQL1 + ', ' + @SQL2 + '
FROM	
	#GRP G INNER JOIN dbo.GR_GOS GR ON G.gr_gs_code = GR.CODE
	LEFT JOIN ' + @varKSTABLE_N + ' N ON G.ID = N.GR_ID
	LEFT JOIN #ZP Z ON G.ID = Z.GR_ID 
	LEFT JOIN #OKLAD O ON G.ID = O.GR_ID
	LEFT JOIN #CHIN1 C1 ON G.ID = C1.GR_ID
	LEFT JOIN #CHIN2 C2 ON G.ID = C2.GR_ID
	LEFT JOIN #CHIN3 C3 ON G.ID = C3.GR_ID
	LEFT JOIN #CHIN4 C4 ON G.ID = C4.GR_ID
GROUP BY 
	GR.CODE, GR.NAME, G.NAME_POST, ' + @SQL1 + '
ORDER BY 
	GR.CODE'

EXEC (@SQL)


DROP TABLE #SAL_CJ
DROP TABLE #GRP
DROP TABLE #NADB
DROP TABLE #ZP
DROP TABLE #OKLAD
DROP TABLE #CHIN1
DROP TABLE #CHIN2
DROP TABLE #CHIN3
EXEC ('DROP TABLE ' + @varKSTABLE_N)

RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_REP_SAL_GOS_EMPLS] 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].[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE16]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE16]
GO




/*
c Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.RSD_REPORT_FORMULA_AVPAT3_P22_VALUE16  
	@cres char(20) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	declare @cStr varchar(250), @res1 float, @res2 float, @res3 float
	exec dbo.RI_Report_Formula_itog @res1 output, '150', @vardBegin, @vardEnd, @variCol, @variRow, @variLSF
	exec dbo.RI_Report_Formula_itog @res2 output, '170', @vardBegin, @vardEnd, @variCol, @variRow, @variLSF	
	select @variCol = link_Col from report_coloumns A where orders = 5 and link_table = (select top 1 link_table from report_coloumns where link_col = @variCol)
	set @res3 = isnull((select dbo.BB_CREDIT_KOEFF_CONVERT(Str_val) from REPORT_STRING 
	where Link_Saved_Form = @variLSF and Link_Col = @variCol and Link_Row in
		(select Link_Row from I_Report_Rows where Link_Table = (select top 1 link_table from report_coloumns where link_col = @variCol and CODE = '210'))),1)

	IF @res3 = 0
		set @res3 = 1

	set @cres = str((@res1 - @res2)/@res3,20)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_ANALITICS_TREE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_ANALITICS_TREE]
GO

CREATE procedure dbo.[RT_ANALITICS_TREE]
	@varKSnLINK_SELF		INT = NULL, 
	@varKSnPLink    		INT = NULL, -- линк на период выборки
	@varKSnPERIODIC			INT,
	@varKSnPeriodBegindate  DATETIME,
	@varKSnBPeriodNumeric	INT,
	@varKSnPeriodEnddate	DATETIME,
	@varKSnEPeriodNumeric	INT,
	@varKSnSvod				INT,
	@varKSnStatus			INT
as

if @varKSnLINK_SELF = 0
	set @varKSnLINK_SELF = NULL

create table #rep_tree (link int identity(1,1),
			link_self int,
			[name] varchar(250),
			orders int,
			imageindex varchar(20),
			tab_accessory int,
			tab_link int,
			childrens bit,
			link_f int,
			link_t int,
			link_c int,
			expanded tinyint,
			[col_type] tinyint,
			atr_code varchar(1000),
			atr_name varchar(1000))

if @varKSnPERIODIC = 1 begin
	set @varKSnPeriodBegindate = cast(cast(datepart(yyyy,@varKSnPeriodBegindate) as varchar(4))+'1231' as datetime)
	set @varKSnPeriodEnddate = cast(cast(datepart(yyyy,@varKSnPeriodEnddate) as varchar(4))+'1231' as datetime)
end

insert into #rep_tree ([name],imageindex,orders,tab_accessory,tab_link,childrens,link_f,link_t,link_c,expanded,[col_type],atr_code,atr_name)
select 
	rtrim(rf.[code])+' '+ltrim(rtrim((select [name] from dbo.report_forms where link_form = rf.link_form))),
	'FOLDER',
	0,
	0,
	rf.link_form,
	convert(bit,0), 
	rf.link_form, 
	null, 
	null, 
	(case when raf.code is not null then 1 else 0 end), 
	null, 
	(select atributs from dbo.report_forms where link_form = rf.link_form),
	dbo.RT_GET_ATR_NAME(rf.link_form)
from (
	select 
		min(rf0.link_form) as link_form,
		rf0.code as code
	from dbo.report_forms as rf0
    inner join (
	    select 
		    min(rf2.start_date) as start_date,
		    rf2.code as code
	    from dbo.report_forms as rf2
	    where rf2.link_form in (
		    select distinct link_form 
		    from report_saved_forms rsf1 
		    where 
            rsf1.begin_date between @varKSnPeriodBegindate and @varKSnPeriodEnddate
		    and (rsf1.period_type = @varKSnPERIODIC or @varKSnPERIODIC = 8)
		    and (rsf1.period_number = @varKSnBPeriodNumeric or rsf1.period_number = @varKSnEPeriodNumeric or @varKSnPERIODIC = 8)
		    and ((rf2.end_date is null) or rf2.end_date >= rsf1.begin_date) 
		    and rsf1.IsSvod in (
			    case when @varKSnStatus&0x10 = 0x10 then 1 else -1 end,
			    case when @varKSnStatus&0x20 = 0x20 then 0 else -1 end)--@varKSnSvod
		    and rsf1.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)
	    )
	    group by rf2.code, rf2.start_date 
    ) as rf1
        on rf0.code = rf1.code and rf0.start_date = rf1.start_date
	where rf0.link_form in (
		select distinct link_form 
		from report_saved_forms rsf 
		where 
        rsf.begin_date between @varKSnPeriodBegindate and @varKSnPeriodEnddate
		and (rsf.period_type = @varKSnPERIODIC or @varKSnPERIODIC = 8)
		and (rsf.period_number = @varKSnBPeriodNumeric or rsf.period_number = @varKSnEPeriodNumeric or @varKSnPERIODIC = 8)
		and ((rf0.end_date is null) or rf0.end_date >= rsf.begin_date) 
		and rsf.IsSvod in (
			case when @varKSnStatus&0x10 = 0x10 then 1 else -1 end,
			case when @varKSnStatus&0x20 = 0x20 then 0 else -1 end)--@varKSnSvod
		and rsf.IsRO in (
			case when @varKSnStatus&0x01 = 0x01 then 0 else -1 end,
			case when @varKSnStatus&0x02 = 0x02 then 1 else -1 end,
			case when @varKSnStatus&0x04 = 0x04 then 2 else -1 end,
			case when @varKSnStatus&0x08 = 0x08 then 3 else -1 end,
			case when @varKSnStatus&0x40 = 0x40 then 4 else -1 end,
			case when @varKSnStatus&0x80 = 0x80 then 5 else -1 end)
	)
	group by rf0.code
    
) as rf
left join (
	select (select code from dbo.report_forms where link_form = L.link_f) as code
	from dbo.report_analitics_forms as L
	group by L.link_f,L.link_up 
	having L.link_up = @varKSnPLink
) raf 
on raf.code = rf.code
order by rf.code
---
-- select * from #rep_tree 
---
insert into #rep_tree (link_self,[name],imageindex,orders,tab_accessory,tab_link,childrens,link_f,link_t,link_c,expanded,[col_type],atr_code,atr_name)
select 
    [link_self] = (select link from #rep_tree where link_f = rt.link_form and tab_accessory = 0),
	rt.[name],
    'FOLDER',
    rt.orders,
    1,
    rt.link_table,
    convert(bit,0), 
    rt.link_form, 
    rt.link_table, 
    null, 
    (case when raf.code is not null then 1 else 0 end),
    null, 
    (select atributs from dbo.report_forms where link_form = rt.link_form),
    dbo.RT_GET_ATR_NAME(rt.link_form)
from report_tables as rt 
left join 
    (select
        (select code from dbo.report_forms where link_form = (select link_form from dbo.report_tables where link_table = L.link_t)) as code,
        (select orders from dbo.report_tables where link_table = L.link_t) as orders
    from dbo.report_analitics_forms as L
    group by L.link_t,L.link_up 
    having L.link_up = @varKSnPLink) raf 
on raf.code = (select code from dbo.report_forms where link_form = (select link_form from dbo.report_tables where link_table = rt.link_table))
and raf.orders = rt.orders
where rt.link_form in (select link_f from #rep_tree)
order by rt.link_form, rt.orders
---

---
insert into #rep_tree (link_self,[name],imageindex,orders,tab_accessory,tab_link,childrens,link_f,link_t,link_c,expanded,[col_type],atr_code,atr_name)
select 
    [link_self] = (select link from #rep_tree where link_t = rc.link_table and tab_accessory = 1),
	rc.[name],
    case when rc.col_type = 0 then 'ACCOUNT' else 'UNCN' end,
    rc.orders,
    2,
    rc.link_col,
    convert(bit,0),
	(select link_form from report_tables where link_table = rc.link_table), 
    rc.link_table, 
    rc.link_col,
    0,
    rc.col_type,
    (select atributs from dbo.report_forms where link_form = (select link_form from dbo.report_tables where link_table = rc.link_table)),
    (select dbo.RT_GET_ATR_NAME(link_form) from dbo.report_tables where link_table = rc.link_table)
from report_coloumns rc 
where rc.link_table in (select link_t from #rep_tree) --and rc.col_type = 0
order by rc.link_table, rc.orders

update #rep_tree
set	childrens = convert(bit,1)
where not exists(select * from #rep_tree t where t.link_self = #rep_tree.link)

select 
    (case when raf.link_c is not null then 1 else 0 end) as checked,
    (case when raf.link_c is not null then 1 else 0 end) as upd, 
    0 as del, 
    t.* 
from #rep_tree t 
left join dbo.report_analitics_forms raf 
on raf.link_up = @varKSnPLink 
and 
    (select code from dbo.report_forms where link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = t.link_c)))=
    (select code from dbo.report_forms where link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = raf.link_c)))
and 
    (select orders from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = t.link_c))=
    (select orders from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = raf.link_c))
and
    (select [name] from dbo.report_coloumns where link_col = t.link_c)=
    (select [name] from dbo.report_coloumns where link_col = raf.link_c)

where (@varKSnLINK_SELF IS NULL AND t.link_self IS NULL) OR (t.link_self = @varKSnLINK_SELF)  
order by t.orders

drop table #rep_tree
GO
GRANT EXECUTE ON dbo.[RT_ANALITICS_TREE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO

GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_RR_104N_CREATE_PROV]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_RR_104N_CREATE_PROV]
GO

-- Формирование проводок в расходном расписании

CREATE	PROCEDURE dbo.FB_RR_104N_CREATE_PROV
	@iLinkDoc 	int,
	@iDel		tinyint = 0	
as

declare @iTypLink 	int,
	@iLink 		int,
	@iLinkUp 	int,
	@cNameOper 	varchar(250),
	@nSumma 	numeric(28,2),
	@iType 		int,
	@iKBK 		int,
	@iEKR 		int, 
	@iDopCl		int, 
	@iDep 		int, 
	@iDepAcc	int, 
	@iLinkGp1 	int,
	@iOrders 	int,
	@cNameG2 	varchar(254),
 	@xRet		int,
	@cErrTxt 	varchar(60),
	@cCodeObj 	varchar(60),
	@iLinkObj	int,
	@cTypeBudg 	char(1),
	@iDepPol 	int,
	@iAccPol 	int,
	@iYear		int,
	@inYear		int,
	@iAssign	int,
	@iAccType	tinyint
	

if @iLinkDoc is null or @iLinkDoc <= 0
	return -1	

-- Хозяин документа и счет
select 	@iYear	 = F.FYEAR, 
	@iDepPol = DA.LINK_UP, 
	@iAccPol = F.DEST_ACC,
	@iAccType = DA.[TYPE]
from dbo.FIN_RR F
inner join dbo.DEPARTMENT_ACCOUNTS DA on F.LINK_G_PROV = @iLinkDoc and F.DEST_ACC = DA.LINK 


-- Получатель и счет
select 	@iDep  	  = GP.DEP, 
	@iDepAcc  = GP.ACC,
	@iLinkObj = GP.OBJECT
from dbo.G_PROV GP
where GP.LINK = @iLinkDoc

select 	@cCodeObj = CODE
from dbo.S_OBJECTS
where LINK = @iLinkObj

-- Елси расходное расписание не исходящее то получ = владец
--if @cCodeObj <> 'FIN_RR'
--select @iDepPol = @iDep, @iAccPol = @iDepAcc



-- Источник финансирования в зависимости от счета
select @cTypeBudg = (case type 	when 4 then '2' else '1' end) 
from dbo.DEPARTMENT_ACCOUNTS
where LINK = @iAccPol


-- Суммы по классификации в курсор
declare GRID_CUR cursor local static read_only for
select LINK,LINK_UP, KBK, EKR, DOP_CL, SUMMA_Y1 AS SUMMA, case TYPE when 2 then 0 else 1 end, 1  
from  dbo.FINANSE_RR_TABLE
where LINK_UP = @iLinkDoc and SUMMA_Y1 <> 0 and TYPE <> 3
union
select LINK,LINK_UP, KBK, EKR, DOP_CL, SUMMA_Y2, case TYPE when 2 then 0 else 1 end, 2 
from  dbo.FINANSE_RR_TABLE
where LINK_UP = @iLinkDoc and SUMMA_Y2 <> 0 and TYPE <> 3
union
select LINK,LINK_UP, KBK, EKR, DOP_CL, SUMMA_Y3, case TYPE when 2 then 0 else 1 end, 3  
from  dbo.FINANSE_RR_TABLE
where LINK_UP = @iLinkDoc and SUMMA_Y3 <> 0 and TYPE <> 3
-- Удаляем проводки
if @iDel = 1
	delete from dbo.G_PROV1 where LINK_UP = @iLinkDoc


-- Добываем типовую операцию
/*select @iTypLink = LINK_OPER 
from DOC_NASTR_T1
where LINK_UP = @iLinkObj and OSN = 1*/

select @iTypLink = case @iAccType when 3 then TYP_LINK1 else TYP_LINK end from dbo.FIN_RR_104N_OPTIONS

if @iTypLink is null or @iTypLink <= 0
	return - 2


select @cNameOper = G1.NAME_OPER,
	 @cNameG2 = XO.NAME
from G_PROV1 G1
left join dbo.XOZ_OPER XO on G1.OPER = XO.LINK   
where G1.LINK = @iTypLink
if @cNameG2 is null
	set @cNameG2 = 'Автосформировано'
/*	select @cNameG2 = case @cCodeObj when 'FIN_RR'	    then 'Переданы лимиты БО'
					 when 'FIN_RR_IN'   then 'Получены лимиты БО'
					 when 'FIN_RR_SVOD' then 'Получены сводные лимиты БО'
					 else '' end */

--SELECT @varKSdCALC_DATE = DATE + 1 FROM G_PROV WHERE LINK = @varKSnLINK_DOC



open GRID_CUR
fetch next from GRID_CUR into @iLink, @iLinkUp, @iKBK, @iEKR, @iDopCl, @nSumma, @iAssign, @inYear
while @@FETCH_STATUS = 0
begin
	set @iOrders = @iOrders + 1
	set @iLinkGP1 = NULL
	exec X_UPDATE_G_PROV1 @iLinkGP1 output, @iLinkDoc, @iTypLink, @cNameOper, @iOrders

	if @iLinkGP1 is null
		RETURN -3	
	exec @xRet = dbo.FB_SAVE_G_PROV2_AP_LIMIT @iLinkGP1, @iTypLink, @nSumma, /*@dCalcDate*/null, @iKBK, @iEKR, @iDopCl, null, @iDEP, @iDepAcc, @cNameG2, @cTypeBudg,@iDepPol, @iAccPol, null, @inYear, @iAssign
	if @xRet <> 0
	  begin
	    	set @cErrTxt = case @xRet when -1 then '"Не задан линк операции"' end
  	  	print 'Ошибка при записи проводки по Финансированию: '
		PRINT  -4	
	 end
	fetch next from GRID_CUR into @iLink, @iLinkUp, @iKBK, @iEKR, @iDopCl, @nSumma, @iAssign, @inYear
END

close GRID_CUR
deallocate GRID_CUR

exec dbo.X_SALDO_COMMITCHANGES	


return 0

GO

grant all on dbo.FB_RR_104N_CREATE_PROV to public
GO
 
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE19]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE19]
GO




/*
c Кейсистемс (Keysystems), 2005
*/
CREATE   PROCEDURE dbo.RSD_REPORT_FORMULA_AVPAT3_P22_VALUE19  
	@cres char(20) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	declare @res1 float , @res2 float, @cStr varchar(250), @percent float
	exec dbo.RI_Report_Formula_itog @res1 output, '190', @vardBegin, @vardEnd, @variCol, @variRow, @variLSF
	select @variCol = link_Col from report_coloumns A where orders = 4 and link_table = (select top 1 link_table from report_coloumns where link_col = @variCol)
	exec dbo.RI_Report_Formula_itog @percent output, '210', @vardBegin, @vardEnd, @variCol, @variRow, @variLSF
	select @variCol = link_Col from report_coloumns A where orders = 5 and link_table = (select top 1 link_table from report_coloumns where link_col = @variCol)
	set @res2 = isnull((select dbo.BB_CREDIT_KOEFF_CONVERT(Str_val) from REPORT_STRING 
	where Link_Saved_Form = @variLSF and Link_Col = @variCol and Link_Row in
		(select Link_Row from I_Report_Rows where Link_Table = (select top 1 link_table from report_coloumns where link_col = @variCol and CODE = '210'))),1)

	IF @res2 = 0
		SET @res2 = 1

	set @cres = str(ROUND(@res2 * @res1 * @percent/100, 0),20)
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].[I_REPORT_SAVE_DINAMIC_ROW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[I_REPORT_SAVE_DINAMIC_ROW]
GO



/*
© Кейсистемс (Keysystems), 2005

*/

CREATE	PROCEDURE dbo.I_REPORT_SAVE_DINAMIC_ROW
	@varKSLINK_SAVED_FORM	int	= null,
	@varKSLink_Col	int	= null,
	@varKSCode_ROW	varchar(50)	= '',
	@varKSSumma	float	= 0,
	@varKSString	varchar(254) = ''
AS


--перенос формы из архивной базы
--exec RN_MOVE_FORM_FROM_ARH @varKSLINK_SAVED_FORM

--update report_saved_forms
--set modify_date = getdate()
--where Link_saved_form = @varKSLINK_SAVED_FORM

DECLARE @Code VARCHAR(50), @Date DATETIME 

SELECT @Code = rf.code, @Date = rsf.[Begin_Date]
  FROM dbo.[REPORT_FORMS] rf JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
WHERE rsf.[Link_Saved_Form] = @varKSLINK_SAVED_FORM

--IF left(@Code,7) IN ( '0503075', '0503074')
--BEGIN
--   DELETE dbo.[REPORT_DINAMICS]
--   WHERE Link_Sf = @varKSLINK_SAVED_FORM
--         AND LEFT(code_row, CHARINDEX('#', Code_Row) - 1) NOT IN 
--         (SELECT [Shifr] 
--                       FROM  dbo.REPORT_FORM14_RAZD_NAME 
--                       WHERE (begin_date is NULL or begin_date <= @Date) 
--                              and (end_date is NULL or end_date >= @Date ))   
--END

-- 2006-11-27 убрала специально, чтобы не было лишних проверок (проверяться будет на верхнем уровне)
/*declare @Status int, @access int
select @Status = coalesce((select max(ISRO) from report_saved_forms where link_saved_form = @varKSLINK_SAVED_FORM),0)
select @access = access from dbo.Report_Status where Status = @Status
if @access & 2 = 0
	return -1

if dbo.RO_AccessColByLink(@varKSLink_Col) <= 0 -- нет доступа к колнке
	return 0*/

DECLARE	@varKSiColType	tinyint

SET @varKSString = LEFT(@varKSString,250)
select @varKSiColType = Col_Type from report_coloumns where link_col = @varKSLink_Col

--SET LOCK_TIMEOUT 5000
--SET IMPLICIT_TRANSACTIONS ON
DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int
SET @varKStrancount = @@TRANCOUNT
--SET IMPLICIT_TRANSACTIONS ON
--BEGIN TRAN
--COMMIT TRAN

	IF @varKSiColType = 0 
		SET @varKSString = ''
	ELSE 
		SET @varKSSumma = 0

	IF exists (Select * from REPORT_DINAMICS where Link_SF = @varKSLINK_SAVED_FORM and
				    Link_Col = @varKSLink_Col and Code_Row = @varKSCode_ROW)
	BEGIN
		UPDATE REPORT_DINAMICS
			SET Float_Val = @varKSSumma,
				Str_Val = @varKSString
		  WHERE	Link_SF = @varKSLINK_SAVED_FORM and
			Link_Col = @varKSLink_Col and 
			Code_Row = @varKSCode_ROW
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
--		IF @varKSERROR <> 0
--		BEGIN
--			ROLLBACK
--			RETURN 7
--		END
--		IF @varKSRowCount = 0
--		BEGIN
--			ROLLBACK
--			RETURN 2
--		END
	END
	ELSE 
		INSERT INTO REPORT_DINAMICS (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
			VALUES (@varKSLINK_SAVED_FORM, @varKSLink_Col, @varKSCode_ROW, @varKSSumma, @varKSString)

--IF @@TRANCOUNT > @varKStrancount
--	COMMIT TRAN
RETURN 0


GO
GRANT ALL ON dbo.[I_REPORT_SAVE_DINAMIC_ROW] 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].[BK_FORM_VIEW_DOCUMENT_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BK_FORM_VIEW_DOCUMENT_TABLE]
GO




/*
© Кейсистемс (Keysystems), 2005
*/


CREATE   PROCEDURE dbo.BK_FORM_VIEW_DOCUMENT_TABLE
	@varKScCode varchar(30)
AS
	DECLARE 
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSCurLINK2	int,
		@varKSFirst		int,
		@varKSCurCODE	varchar(30),
		@varKSRefDict	varchar(30),
		@varKSRefField	varchar(30),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(30),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(7000),
		@varKSCur_Str	varchar(1000),
		@varKSEMP		varchar(1),
		@varKSRefLINK	int,
		@varKSintval		int,
		@varKShostTypeObject	varchar(30)
--	
	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END

	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK, CODE 
	FROM S_OBJECTS WHERE LINK_SELF=@varKSnLink 


print '---------------------------------------'+@varKScCode+'(таблица)'
	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_VIEW_DOCUMENT_TABLE 
--'+LTRIM(convert(char, getdate()))+'
VIEW dbo.' + LTRIM (@varKScCode) + ' AS
SELECT 
	OTR.LINK,
	OTR.LINK_UP,
	OTR.ORDERS'

	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		
		IF Convert(int, @varKSInALIAS) = 1 AND @varKSStorage<>''
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSRefField OUTPUT
			SET @varKSRefField = RTRIM(LTRIM(@varKSRefField))
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			SET @varKSCurCODE = RTRIM(LTRIM(@varKSCurCODE))
			IF LEN(@varKSShortCode)>10
				print 'ПРЕДУПРЕЖДЕНИЕ: Длина поля SHORT_CODE_OBJ больше 10 символов!!!'

			SET @varKShostTypeObject = @varKSCurCODE
			IF @varKSStorage IN('DICTION', 'SUBDIV') AND @varKSRefField <> 'LINK'
			BEGIN
				Declare @varKSOVHValue varchar(254)
				Select @varKSOVHValue = RTRIM(Value)
				From OBJECT_VALUES OVH
				Where OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT')
					AND OVH.OBJECT = (select LINK from s_objects where code = @varKSRefDict)

				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, OBJECT_VALUES OVF,
						OBJECT_VALUES OVS, S_OBJECTS SOH
					WHERE SOH.CODE = @varKSOVHValue
						AND SO.LINK_SELF = SOH.LINK

						AND OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'SHORT_CODE_OBJ') AND OVF.VALUE = @varKSRefField
						AND OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION'
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'DICTION_APP'
				SET @varKShostTypeObject = @varKSRefField

			EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT

			SET @varKSType = UPPER(LTRIM(@varKSType))
DECLARE	@varKSCNE	varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT
			
			SET @varKSINFO='	'+convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

			IF LTRIM(@varKSShortCode)='' OR @varKSShortCode is null
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			
 			IF @varKSStorage  ='DICTION_REF'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSintval = CHARINDEX(',', @varKSRefField)
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = RTRIM(SUBSTRING(@varKSRefField, 1, @varKSintval-1))
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefField = RTRIM(LTRIM(SUBSTRING(@varKSRefField, @varKSintval + 1, LEN(@varKSRefField) - @varKSintval)))
				IF @varKSRefField=''
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSRefField <> 'LINK'
				BEGIN
					SELECT @varKShostTypeObject = SO.CODE
						FROM S_OBJECTS SO, 
							OBJECT_VALUES OVH, S_OBJECTS SOH
						WHERE OVH.OBJECT = @varKSRefLINK
							AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
							AND SOH.CODE = RTRIM(OVH.VALUE)
							AND SO.LINK_SELF = SOH.LINK
							AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
							AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
					IF @@ROWCOUNT = 0
						print '******* Ошибка! Не найден базовый тип данных!'
				END
				print 'WAS '+@varKSType
				EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT
				print 'IS '+@varKSType
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+ 'Convert('+@varKSType+', (SELECT D.'+@varKSRefField
					SET @varKSCur_Str=@varKSCur_Str+
						' FROM DICTION_REF DR, DICTION D, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DR.REF_PRIMARY=OTD.DICTION AND DR.OBJECT = '+LTRIM(STR(@varKSRefLINK))+' AND D.LINK = DR.REF_FOREIGN)'

					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'

				SET @varKSCur_Str=@varKSCur_Str + ')'

				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='DICTION_APP'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefField
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+', DA.VALUE'
					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'
					SET @varKSCur_Str=@varKSCur_Str+')'+
						' FROM DICTION_APP DA, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DA.LINK_UP = OTD.DICTION AND DA.OBJECT = '+LTRIM(STR(@varKSRefLINK))+')'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='DICTION'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DICTION FROM OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM DICTION D, OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DICTION)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='ACCOUNT'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT ACCOUNT FROM dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str= @varKSCur_Str+'(SELECT Convert (' +@varKSType + ', ' + @varKSRefField +
						CASE
							WHEN @varKSType = 'DATETIME' THEN ', 104'
							ELSE ''
						END +
					') FROM dbo.S_ACCOUNTS SA, dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND SA.LINK=OTA.ACCOUNT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


 			IF @varKSStorage  ='DEPARTMENTS'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DEPARTMENT FROM OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.DEPARTMENTS D, dbo.OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DEPARTMENT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='SUBDIV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null

						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT SUBDIV FROM OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.SUBDIV D, dbo.OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.SUBDIV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


			IF @varKSCurCODE <> @varKShostTypeObject
				print '-------->' + @varKShostTypeObject + ' ' + @varKSType

			IF @varKSStorage IN ('SUMMA', 'DATE', 'STRING')
			BEGIN
				IF @varKSType = ''
					SET @varKSCur_Str = '['+@varKSShortCode+'] = (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
					SET @varKSCur_Str = '['+@varKSShortCode+'] = CONVERT('+@varKSType+', (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+'))'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),' - ') +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),' - ')+@varKSINFO
			END

 			IF @varKSStorage  = 'INVENTORY'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT INVENTORY FROM dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.INVENTORY INV, dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTI.INVENTORY)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'NOMENCLATURE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT NOMENCLATURE FROM dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.NOMENCLATURE INV, dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTN.NOMENCLATURE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'EMPL'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT EMPL FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','
					IF @varKSRefField = 'NAME_EMPL'
					BEGIN
						SET @varKSCur_Str=@varKSCur_Str+' dbo.sd_GetEmplName (OTE.EMPL))'+ 
							' FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+ ')'
					END
					ELSE
					BEGIN						
						SET @varKSCur_Str=@varKSCur_Str + @varKSRefField
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						ELSE	
							SET @varKSCur_Str=@varKSCur_Str+')'+
								' FROM dbo.EMPL EMP, dbo.OUT_TABLE_EMPL OTE'+
								' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+
								' AND EMP.LINK=OTE.EMPL)'
					END

				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KL_KBK'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KBK FROM dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KL_KBK KBK, dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KBK.LINK=OTKBK.KBK)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KOSGU'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KOSGU FROM dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KOSGU KSGU, dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KSGU.LINK = OTSGU.KOSGU)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'G_PROV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT G_PROV FROM dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.G_PROV GP, dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND GP.LINK = OTGP.G_PROV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'FIN_SOURCE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT FIN_SOURCE FROM dbo.OUT_TABLE_FIN_SOURCE OTFS'+
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.FIN_SOURCE FS, dbo.OUT_TABLE_FIN_SOURCE OTFS' +
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND FS.LINK = OTFS.FIN_SOURCE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage NOT IN ('SUMMA', 'DATE', 'STRING', 'DICTION', 'DICTION_APP', 'DICTION_REF',
					'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
					'INVENTORY', 'NOMENCLATURE', 'EMPL', 'KL_KBK', 'KOSGU', 'G_PROV',
					'FIN_SOURCE')
			BEGIN
				SET @varKSCur_Str=''
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE

			END 
			
			IF @varKSCur_Str is null
				SET @varKSCur_Str=''
			IF @varKSCur_Str<>''
			BEGIN
				SET  @varKSSel_Str=@varKSSel_Str+',
	'+@varKSCur_Str
			END
		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	END		
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR
	IF RIGHT(@varKSSel_Str,1)=','
		SET @varKSSel_Str=LEFT(@varKSSel_Str,LEN(@varKSSel_Str)-1)
	SET  @varKSSel_Str=@varKSSel_Str+'
	FROM dbo.OUT_TABLE_ROW OTR
	WHERE OTR.OBJECT = '+LTRIM(STR(@varKSnLink))
	
	IF EXISTS(SELECT * From sysobjects Where name=@varKScCode)
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str
	
	EXECUTE (@varKSSel_Str)

--print @varKSSel_Str

	DECLARE @varKSscriptstr varchar(7000)
	SET @varKSscriptstr = 'EXECUTE BK_FORM_VIEW_DOCUMENT_TABLE '''+@varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKScCode, @varKSscriptstr

	


	UPDATE S_DBObjects SET Rights = 0x11 WHERE Object=@varKSnLink AND DBObject=@varKScCode
	IF @@ROWCOUNT = 0
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScCode, 0x11)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KJ_INFO_CHISL_GOS_GR_SLUG]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KJ_INFO_CHISL_GOS_GR_SLUG]

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE dbo.KJ_INFO_CHISL_GOS_GR_SLUG
	@date_doc	datetime,
	@option		int
AS
DECLARE @temptable table(dep_name varchar(100), date_doc datetime,
			col1_1 int , col1_2 int , col1_3 int , col1_4 int , col1_5 int ,
			col2_1 int , col2_2 int , col2_3 int , col2_4 int , col2_5 int ,
			col3_1 int , col3_2 int , col3_3 int , col3_4 int , col3_5 int ,
			col4_1 int , col4_2 int , col4_3 int , col4_4 int , col4_5 int ,
			col5_1 int , col5_2 int , col5_3 int , col5_4 int , col5_5 int ,
			col6_1 int , col6_2 int , col6_3 int , col6_4 int , col6_5 int ,
			col7_1 int , col7_2 int , col7_3 int , col7_4 int , col7_5 int ,
			col8_1 int , col8_2 int , col8_3 int , col8_4 int , col8_5 int ,
			col9_1 int , col9_2 int , col9_3 int , col9_4 int , col9_5 int ,
			col10_1 int, col10_2 int, col10_3 int, col10_4 int, col10_5 int,
			col11_1 int, col11_2 int, col11_3 int, col11_4 int, col11_5 int,
			col12_1 int, col12_2 int, col12_3 int, col12_4 int, col12_5 int,
			col13_1 int, col13_2 int, col13_3 int, col13_4 int, col13_5 int,
			col14_1 int, col14_2 int, col14_3 int, col14_4 int, col14_5 int,
			col15_1 int, col15_2 int, col15_3 int, col15_4 int, col15_5 int,
			col16_1 int, col16_2 int, col16_3 int, col16_4 int, col16_5 int,
			col17_1 int, col17_2 int, col17_3 int, col17_4 int, col17_5 int,
			col18_1 int, col18_2 int, col18_3 int, col18_4 int, col18_5 int,
			col19_1 int, col19_2 int, col19_3 int, col19_4 int, col19_5 int
			)
DECLARE @dep_name varchar(100)
DECLARE @dep_link varchar(100)
set @dep_link = (SELECT DEP_LINK FROM USER_DEP)
SET @dep_name = (SELECT FULL_NAME FROM DEPARTMENTS WHERE LINK = @dep_link)

DECLARE @GsEmpl table(empl_link int, kat_gs_code varchar(2), gr_gs_code varchar(2), kl_chin varchar(2))
INSERT INTO @GsEmpl
SELECT empl_link, kat_gs_code, gr_gs_code, kl_chin FROM GetGSGREmplToDepAndDate(@dep_link,@date_doc, 0)

INSERT	@temptable(dep_name,date_doc)
VALUES	(@dep_name,@date_doc)
IF @option = 1 				-- ПРИ ВЫБОРЕ ФОРМЫ 1
UPDATE	@temptable
SET	 
-- ВСЕГО СЛУЖАЩИХ
	col1_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1),
	col1_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2),
	col1_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3),
	col1_4 = (select count(*) from @GsEmpl where kl_chin is NULL),
	col1_5 = 0,
-- РУКОВОДИТЕЛИ
	col2_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 1),
	col2_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 1),
	col2_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 1),
	col2_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 1),
	col2_5 =  0,
-- высшие
	col3_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 1 and gr_gs_code = 1),
	col3_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 1 and gr_gs_code = 1),
	col3_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 1 and gr_gs_code = 1),
	col3_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 1 and gr_gs_code = 1),
	col3_5 = 0,
-- главные
	col4_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 1 and gr_gs_code = 2),
	col4_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 1 and gr_gs_code = 2),
	col4_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 1 and gr_gs_code = 2),
	col4_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 1 and gr_gs_code = 2),
	col4_5 = 0,
-- ведущие
	col5_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 1 and gr_gs_code = 3),
	col5_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 1 and gr_gs_code = 3),
	col5_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 1 and gr_gs_code = 3),
	col5_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 1 and gr_gs_code = 3),
	col5_5 = 0,
-- ПОМОЩНИКИ (СОВЕТНИКИ)
	col6_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 2),
	col6_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 2),
	col6_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 2),
	col6_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 2),
	col6_5 = 0,
-- высшие
	col7_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 2 and gr_gs_code = 1),
	col7_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 2 and gr_gs_code = 1),
	col7_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 2 and gr_gs_code = 1),
	col7_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 2 and gr_gs_code = 1),
	col7_5 = 0,
-- главные
	col8_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 2 and gr_gs_code = 2),
	col8_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 2 and gr_gs_code = 2),
	col8_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 2 and gr_gs_code = 2),
	col8_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 2 and gr_gs_code = 2),
	col8_5 = 0,
-- ведущие
	col9_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 2 and gr_gs_code = 3),
	col9_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 2 and gr_gs_code = 3),
	col9_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 2 and gr_gs_code = 3),
	col9_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 2 and gr_gs_code = 3),
	col9_5 = 0,
-- СПЕЦИАЛИСТЫ
	col10_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 3),
	col10_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 3),
	col10_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 3),
	col10_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 3),
	col10_5 = 0,
-- высшие
	col11_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 3 and gr_gs_code = 1),
	col11_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 3 and gr_gs_code = 1),
	col11_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 3 and gr_gs_code = 1),
	col11_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 3 and gr_gs_code = 1),
	col11_5 = 0,
-- главные
	col12_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 3 and gr_gs_code = 2),
	col12_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 3 and gr_gs_code = 2),
	col12_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 3 and gr_gs_code = 2),
	col12_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 3 and gr_gs_code = 2),
	col12_5 = 0,
-- ведущие
	col13_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 3 and gr_gs_code = 3),
	col13_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 3 and gr_gs_code = 3),
	col13_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 3 and gr_gs_code = 3),
	col13_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 3 and gr_gs_code = 3),
	col13_5 = 0,	
-- старшие
	col14_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 3 and gr_gs_code = 4),
	col14_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 3 and gr_gs_code = 4),
	col14_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 3 and gr_gs_code = 4),
	col14_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 3 and gr_gs_code = 4),
	col14_5 = 0,
-- ОБЕСПЕЧИВАЮЩИЕ СПЕЦИАЛИСТЫ
	col15_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 4),
	col15_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 4),
	col15_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 4),
	col15_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 4),
	col15_5 = 0,
-- главные
	col16_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 4 and gr_gs_code = 2),
	col16_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 4 and gr_gs_code = 2),
	col16_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 4 and gr_gs_code = 2),
	col16_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 4 and gr_gs_code = 2),
	col16_5 = 0,
-- ведущие
	col17_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 4 and gr_gs_code = 3),
	col17_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 4 and gr_gs_code = 3),
	col17_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 4 and gr_gs_code = 3),
	col17_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 4 and gr_gs_code = 3),
	col17_5 = 0,
-- старшие
	col18_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 4 and gr_gs_code = 4),
	col18_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 4 and gr_gs_code = 4),
	col18_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 4 and gr_gs_code = 4),
	col18_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 4 and gr_gs_code = 4),
	col18_5 = 0,
-- младшие
	col19_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and kat_gs_code = 4 and gr_gs_code = 5),
	col19_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and kat_gs_code = 4 and gr_gs_code = 5),
	col19_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and kat_gs_code = 4 and gr_gs_code = 5),
	col19_4 = (select count(*) from @GsEmpl where kl_chin is NULL and kat_gs_code = 4 and gr_gs_code = 5),
	col19_5 = 0
ELSE					-- ПРИ ВЫБОРЕ ФОРМЫ 2
UPDATE	@temptable
SET	
-- ВСЕГО СЛУЖАЩИХ
	col1_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1),
	col1_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2),
	col1_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3),
	col1_4 = (select count(*) from @GsEmpl where kl_chin is NULL),
	col1_5 = 0,
-- ВСЕГО ПО ИСПОЛНИТЕЛЬНОЙ ВЛАСТИ
	col2_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1),
	col2_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2),
	col2_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3),
	col2_4 = (select count(*) from @GsEmpl where kl_chin is NULL),
	col2_5 =  0,
-- высшие
	col3_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and gr_gs_code = 1),
	col3_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and gr_gs_code = 1),
	col3_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and gr_gs_code = 1),
	col3_4 = (select count(*) from @GsEmpl where kl_chin is NULL and gr_gs_code = 1),
	col3_5 = 0,
-- главные
	col4_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and gr_gs_code = 2),
	col4_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and gr_gs_code = 2),
	col4_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and gr_gs_code = 2),
	col4_4 = (select count(*) from @GsEmpl where kl_chin is NULL and gr_gs_code = 2),
	col4_5 = 0,
-- ведущие
	col5_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and gr_gs_code = 3),
	col5_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and gr_gs_code = 3),
	col5_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and gr_gs_code = 3),
	col5_4 = (select count(*) from @GsEmpl where kl_chin is NULL and gr_gs_code = 3),
	col5_5 = 0,
-- старшие
	col6_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and gr_gs_code = 4),
	col6_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and gr_gs_code = 4),
	col6_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and gr_gs_code = 4),
	col6_4 = (select count(*) from @GsEmpl where kl_chin is NULL and gr_gs_code = 4),
	col6_5 = 0,
-- младшие
	col7_1 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=1 and gr_gs_code = 5),
	col7_2 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=2 and gr_gs_code = 5),
	col7_3 = (select count(*) from @GsEmpl where rtrim(ltrim(kl_chin))=3 and gr_gs_code = 5),
	col7_4 = (select count(*) from @GsEmpl where kl_chin is NULL and gr_gs_code = 5),
	col7_5 = 0

SELECT	*
FROM	@temptable



GO


GRANT EXECUTE ON dbo.[KJ_INFO_CHISL_GOS_GR_SLUG] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE      PROCEDURE dbo.SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE
	@varKSOUT_VAL NUMERIC(20) OUTPUT,
	@varKSstart_date DATETIME, 	
	@varKSEND_DATE DATETIME, 
	@varKSDepLink INT
AS BEGIN

	DECLARE @varKSSTART_YEAR DATETIME, @varKSDATE1 DATETIME, @varKOEFF NUMERIC(20,2)
	SET @varKSSTART_YEAR  = dbo.DateBeginOfYear(@varKSstart_date)
	SET @varKSDATE1 = @varKSSTART_YEAR

	EXEC dbo.BufferCLEAR

	DECLARE @varKSPART2 VARCHAR(100),
		@varKSPART21 VARCHAR(100),
		@varKSPART23 VARCHAR(100),
		
		@intCODE	INT,	
		@strCODE	VARCHAR (3)

	EXEC X_GET_TABLE_NAME @varKSPART2 OUTPUT

	SELECT @varKOEFF = [PERCENT] FROM AVANSE_ASSETS_OPTIONS
	IF @varKOEFF IS NULL OR @varKOEFF < 0
		SET @varKOEFF = 0

	CREATE TABLE #RES2 (CODE_STR VARCHAR(3),
				SM1 NUMERIC(20),
				SM2 NUMERIC(20),
				SM3 NUMERIC(20),
				SM4 NUMERIC(20))

	SELECT @intCODE  = 20,
		@varKSDATE1 = @varKSSTART_YEAR

	WHILE @intCODE <= 140
	BEGIN
		SET @strCODE = RIGHT ('000' + CONVERT (VARCHAR (3), @intCODE), 3)

		IF DATEADD (MONTH, 1, @varKSEND_DATE) >= @varKSDATE1
			INSERT INTO #RES2
			SELECT @strCODE,
				SUM(OST_SUM),
				SUM(CASE WHEN GRP_CODE LIKE '10[1, 3]_[1-3]' THEN OST_SUM ELSE 0 END),
				SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END),
				SUM(CASE WHEN NO_NALOG = 1 AND GRP_CODE LIKE '10[1, 3]_[1-3]' THEN OST_SUM ELSE 0.00 END)
			FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)
		ELSE
			INSERT INTO #RES2
			SELECT @strCODE, 0, 0, 0, 0

		SELECT @intCODE = @intCODE + 10,
			@varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
	END

	-- На конец года стоимость недв. имущества --
	INSERT INTO #RES2
	SELECT '141',
		SM2,
		SM2,
		SM4,
		SM4
	FROM #RES2
	WHERE CODE_STR = '140'
/*
	INSERT INTO #RES2
	SELECT '020', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
	FROM dbo.CalcNalogBalanceOS(@varKSSTART_YEAR, @varKSDepLink)

	SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
	INSERT INTO #RES2
	SELECT '030', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
	FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

	SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
	INSERT INTO #RES2
	SELECT '040', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
	FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

	SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
	INSERT INTO #RES2
	SELECT '050', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
	FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

	IF MONTH(@varKSEND_DATE) > 3 BEGIN
		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT '060', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT '070', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT 
			'080', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

	END
	ELSE BEGIN
		INSERT INTO #RES2
		SELECT '060', 0.0, 0.0, 0.0
		UNION
		SELECT '070', 0.0, 0.0, 0.0
		UNION
		SELECT '080', 0.0, 0.0, 0.0
		SET @varKSDATE1 = DATEADD(MONTH, 3,  @varKSDATE1)
	END

	IF MONTH(@varKSEND_DATE) > 6 BEGIN
		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT '090', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT 
			'100', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)
	
		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT 
			'110', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)
	END
	ELSE BEGIN
		INSERT INTO #RES2
		SELECT '090', 0.0, 0.0, 0.0
		UNION
		SELECT '100', 0.0, 0.0, 0.0
		UNION
		SELECT '110', 0.0, 0.0, 0.0
		SET @varKSDATE1 = DATEADD(MONTH, 3,  @varKSDATE1)
	END

	IF MONTH(@varKSEND_DATE) > 9 BEGIN
		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT 
			'120', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

		SET @varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
		INSERT INTO #RES2
		SELECT 
			'130', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)

		SET @varKSDATE1 = dbo.DateEndOfYear(@varKSDATE1)
		SET @varKSDATE1 = DATEADD (DAY, 1, @varKSDATE1)		--- Чтобы расчет амортизации 31 декабря попадал
		INSERT INTO #RES2
		SELECT 
			'140', SUM(OST_SUM), SUM(CASE WHEN CHARINDEX('10101,10102,10301,10302,10303',GRP_CODE) = 0 THEN 0.00 ELSE OST_SUM END), SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END)
		FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)
	END
	ELSE BEGIN
		INSERT INTO #RES2
		SELECT '120', 0.0, 0.0, 0.0
		UNION
		SELECT '130', 0.0, 0.0, 0.0
		UNION
		SELECT '140', 0.0, 0.0, 0.0
		SET @varKSDATE1 = DATEADD(MONTH, 3,  @varKSDATE1)
	END
*/
	EXEC ('SELECT * INTO ' + @varKSPART2 + ' FROM #RES2 ORDER BY CODE_STR ')
	EXEC dbo.BufferPush -1, @varKSPART2



END

GO


GRANT EXECUTE ON dbo.[SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE] TO PUBLIC

GO


--Расширенные свойства--


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_SPR_MAKE_VIEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_SPR_MAKE_VIEW]
GO




/*
c Кейсистемс (Keysystems), 2010

	создание вьюхи для справочника
*/
CREATE            proc 	dbo.RO_SPR_MAKE_VIEW
	 @varKSiLink int, -- линк сохранного справочника в REPORT_SPR
	@varKSiTypeSpr tinyint  = 1 -- 1 - наследуемый справочник, 0 - новый справочник
as
	declare @cRunStr varchar(8000), @codeSpr varchar(50), @nameSpr varchar(254), @cRunStr1 varchar(8000),@cRunStr2 varchar(8000), @cGroupBy varchar(8000), @Link_Self varchar(254),
      @cBeginDate VARCHAR(8000), @cBeginDateG VARCHAR(8000), @cEndDate VARCHAR(8000), @cEndDateG VARCHAR(8000)      
	create table #RunStr (st varchar(8000), orders int IDENTITY(1,1))
-- данные о справочнике
	select @codeSpr = rtrim(Code), @nameSpr = rtrim(name) from dbo.REPORT_SPR where link = @varKSiLink
-------------------------------------------------------------------------------------------------
-- создаем вьюху
	set @cRunStr = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @codeSpr + ']'') and OBJECTPROPERTY(id, N''IsView'') = 1)
drop view [dbo].[' + @codeSpr + ']'
	execute(@cRunStr)

set @cRunStr1 = '/*******************************************************************************
	© Кейсистемс (Keysystems), ' + convert(varchar(10), getdate(), 104) + '
	справочник ' + @nameSpr + ' (сгенерировано Редактором справочников)
*******************************************************************************/
CREATE     VIEW dbo.[' + @codeSpr + ']
AS
'
	insert #RunStr (st)
	values (@cRunStr1)

	-- колонки
	set @cRunStr = ''
	select @cRunStr = @cRunStr + case when Const = '' then 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end 
			else rtrim(Const) end + ' as [' + UPPER(rtrim(Code)) + '],'
	from report_spr_col 
	where Link_Spr = @varKSiLink and (CHARINDEX('Name', Source) = 0 or Const <> '')
	order by orders

	set @cGroupBy = ''
	select @cGroupBy = @cGroupBy + case when LEFT(Source,1) = '''' and CHARINDEX('+', Source) = 0 then '' else 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end + ',' end
	from report_spr_col 
	where Link_Spr = @varKSiLink and Const = '' and CHARINDEX('Name', Source) = 0
	order by orders
   
   IF @cGroupBy LIKE '%select%'
      SET @cGroupBy = 'code,'

	select @cRunStr = @cRunStr + 'max(' + 
				case when First > 0 then  'SUBSTRING(' + rtrim(Source) + ',' + LTRIM(STR(First)) + ',' + case when Cnt > 0 then LTRIM(STR(Cnt)) + ')' else '254)' end 
				else case when Cnt > 0 then 'LEFT(' + RTRIM(Source) + ',' +  LTRIM(STR(Cnt)) + ')' else rtrim(Source) end  end 
			+ ') as [' + UPPER(rtrim(Code)) + '],'
	from report_spr_col 
	where Link_Spr = @varKSiLink and CHARINDEX('Name', Source) > 0
	order by orders

	if @varKSiTypeSpr = 0 -- новый справочник
	begin
			set @cRunStr2 = 'SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,' + @cRunStr + ' begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = ''' + @CodeSpr + ''' GROUP BY ' + @cGroupBy + ' begin_date, end_date' 
			print @cRunStr1 + @cRunStr2
			execute(@cRunStr1 + @cRunStr2)
	end
	else begin
		declare @TableFrom varchar(1000), @Filter varchar(1000), @Value varchar(8000), @orders int, @cLink_Self varchar(1000)
		set @cLink_Self = ', max(Link_Self) as Link_Self'
		declare cur_Spr cursor local static for
			select rtrim(Table_From), rtrim(Filter) from report_SPR_DATA where link_Spr = @varKSiLink

		open cur_Spr

		fetch next from cur_Spr into @TableFrom, @Filter

		while @@fetch_status = 0
		BEGIN
			IF COL_LENGTH(@TableFrom, 'begin_date') is NULL AND @TableFrom NOT LIKE '%report_kbk%'
         begin
				set @cBeginDate = ',convert(datetime, ''19000101'', 112) as begin_date'
            SET @cBeginDateG = ''
         END 
			ELSE begin
				set @cBeginDate =  ',begin_date'
            SET @cBeginDateG = ',begin_date'
         END 

			IF COL_LENGTH(@TableFrom, 'end_date') is NULL AND @TableFrom NOT LIKE '%report_kbk%'
         begin
				set @cEndDate = ',convert(datetime, ''30000101'', 112) as end_date'
            SET @cEndDateG = ''
         END 
			ELSE begin
				set @cEndDate = ',end_date'
            SET @cEndDateG = ',end_date'
         END 

			IF COLUMNPROPERTY(object_id(@TableFrom), 'Link_Self', 'AllowsNull') is NULL
				set @cLink_Self = ', 0 as Link_Self'
			else
				set @cLink_Self = ', max(Link_Self) as Link_Self'

         SET @TableFrom = REPLACE(REPLACE(REPLACE(@TableFrom, 'REPORT_KBK',  '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK]'), '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] K', '[dbo].[RO_KBK_HIST_VIEW] K'), '[dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK]_', 'REPORT_KBK_')
         SET @Filter = REPLACE(REPLACE(REPLACE(@Filter, '[bd]', 'begin_date'), '[ed]', 'end_date'), '[rk]', 'report_kbk')
                  
			set @cRunStr1 = 'SELECT max(LINK) as Link' + @cLink_Self +  ',' + LEFT(@cRunStr, LEN(@cRunStr)-1)
         + @cBeginDate
         + @cEndDate         
         + ' FROM ' + @TableFrom  + case when @Filter = '' then '' else  ' WHERE ' + @Filter end 
         + case when @cGroupBy <> '' then ' GROUP BY ' + LEFT(@cGroupBy, LEN(@cGroupBy)-1) + @cBeginDateG + @cEndDateG else '' end

			insert #RunStr (st) values (@cRunStr1)
			insert #RunStr (st) values ('
	UNION
	')
			fetch next from cur_Spr into @TableFrom, @Filter
		end

		deallocate cur_Spr

		if @cGroupBy = ''
			update #RunStr set st = REPLACE(st, 'max(', '(')

		-- добавленные значения
		declare cur_Value cursor local static for
			select Value, orders, Link_Self from report_spr_Value where  link_Spr = @varKSiLink

		open cur_Value

		fetch next from cur_Value into @Value, @orders, @Link_Self

		while @@fetch_status = 0
		begin
         if @Link_Self <> ''
			   set @cRunStr1 = 'select -' + LTRIM(STR(@orders)) + ' as Link, isnull((' + @Link_Self + '),0) as Link_Self'
         else
            set @cRunStr1 = 'select -' + LTRIM(STR(@orders)) + ' as Link, 0 as Link_Self'

			select @cRunStr1 = @cRunStr1 + ',''' +  dbo.[RA_GETWORDNUM](@Value, orders, '#') + ''' as ' + UPPER(Code)
			from report_spr_col
			where Link_Spr =  @varKSiLink
			order by orders
         
         
			set @cRunStr1 = @cRunStr1 + ',convert(datetime, ''19000101'', 112) as begin_date'
         set @cRunStr1 = @cRunStr1 + ',convert(datetime, ''30000101'', 112) as end_date'

			insert #RunStr (st) values (@cRunStr1)
			insert #RunStr (st) values ('
	UNION
	')

			fetch next from cur_Value into @Value, @orders, @Link_Self
		end
		
		close cur_Value
		deallocate cur_Value

		delete #RunStr where orders = (select max(orders) from #RunStr)

		exec ssp_execresultset @varKScmd = 'select st from #RunStr order by orders'--, @varKSdebug = 1

		drop table #RunStr 
	end

	set @cRunStr = 'GRANT SELECT ON dbo.[' + @codeSpr + '] TO PUBLIC'
	execute (@cRunStr)

GO
GRANT ALL ON dbo.[RO_SPR_MAKE_VIEW] TO PUBLIC
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_371]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_371]
GO

/*
© Кейсистемс (Keysystems), 2010
*/

CREATE PROCEDURE dbo.[RO_PRINT_371]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
	create table #ist (COL1 varchar(50), COL2 varchar(50), COL3 varchar(50), COL4 varchar(50), COL5 NUMERIC(20,2), COL6 varchar(8000), COL7 varchar(8000), COL8 VARCHAR(8000), CODE varchar(50), DEL bit, ITOG int, orders int )
	create table #rash (COL1 varchar(50), COL2 varchar(50), COL3 varchar(50), COL4 varchar(50), COL5 VARCHAR (50), COL6 varchar(8000), COL7 NUMERIC(20,2), COL8 VARCHAR(254), COL9 VARCHAR(8000), COL10 VARCHAR(8000), CODE varchar(50), DEL bit, ITOG int, orders int)

	declare @table varchar(100), @RunStr varchar(8000), @DelRows tinyint


	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, 0 as DEL, 0, Orders from ' + @table 
	insert #ist execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)


	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL8, CODE, 0 as DEL, 0, orders from ' + @table 
	insert #rash execute(@RunStr)
	set @RunStr = 'drop table ' + @table
	execute(@RunStr)
   
   UPDATE #ist
   SET COL5 = #ist.COL5 + R.COL7
   FROM #rash R
   WHERE #ist.Code = R.Code
   
   DELETE #rash
   WHERE EXISTS(SELECT * FROM #ist WHERE #ist.Code = #rash.Code) 

   SELECT * FROM #ist

   SELECT * FROM #rash

	drop table #rash
   drop table #ist
GO
GRANT ALL ON dbo.[RO_PRINT_371] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_DELETE_COUNTRY]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_DELETE_COUNTRY]

GO
CREATE  PROCEDURE dbo.BK_DELETE_COUNTRY
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = 'Страны мира' + ' ' + CODE1 + ' ' + [NAME]
	FROM dbo.KL_COUNTRY WITH (UPDLOCK)
	WHERE LINK = @varKSintLINK

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.KL_COUNTRY
	WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK
		FROM dbo.S_OBJECTS
		WHERE CODE = 'DICTIONARY_COUNTRY'
		EXECUTE dbo.WF_GENERATEEVENT
			'Удаление из справочника',
			@varKSEventText,
			@varKSObjectLink,
			'KL_COUNTRY',
			@varKSintLINK
		COMMIT TRAN
	END
RETURN 0




GO


GRANT EXECUTE ON dbo.[BK_DELETE_COUNTRY] 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(50)='', --требуется для подсчета подитогов 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_name varchar(10),
	@RGB_name_dinamic varchar(10),
	@RGB_simple varchar(10),
    @orders_col int,
	@is_dinamic INT,
   @DictWhere VARCHAR(1000)
 
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
	
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(50),@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(50), 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 R1.rows,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

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(50), 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)) + '], '
		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)) + '], '
			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)) + '], '
				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)) + '], '
				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)) + '], '
				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(50))
	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 '%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(50), 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(50),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((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')
		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 + ',
'		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 '+dbo.rn_getwordnum(@order_rule_curr,1,'#')
					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(*) '

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(50))
--create table #code_row (code_row varchar(50),link_col int)
----create table #i_report_dinamic_rows(Link_SF int,CODE_ROW varchar(50),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(50))
--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(50) 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
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BK_FORM_VIEW_DOCUMENT_ZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BK_FORM_VIEW_DOCUMENT_ZB]
GO

CREATE PROCEDURE dbo.BK_FORM_VIEW_DOCUMENT_ZB
  @varKScCode varchar(30),
  @varKSRealCode varchar(30) = null,
  @varKSDocType smallint = 0, 
  @varKSSummaType tinyint = 0,
  @varKSTaskDivided tinyint = 0


AS
  IF @varKSRealCode is null
    SET @varKSRealCode = @varKScCode
  DECLARE 
    @varKSnLink   int,
    @varKSCurLINK int,
    @varKSCurLINK2  int,
    @varKSFirst   int,
    @varKSCurCODE varchar(30),
    @varKSRefDict varchar(30),
    @varKSRefField  varchar(254),
    @varKSShortCode varchar(30),
    @varKSInALIAS varchar(10),
    @varKSType    varchar(30),
    @varKSStorage varchar(30),
    @varKSSel_Str varchar(7000),
    @varKSCur_Str varchar(1000),
    @varKSEMP   varchar(1),
    @varKSVisible varchar(10),
    @varKShostTypeObject  varchar(30)
  
  SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
  print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
  Return
END

  DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
  FOR SELECT DISTINCT LINK, CODE 
  FROM S_OBJECTS WHERE LINK_SELF=@varKSnLink
    AND LINK_CLASS =(SELECT LINK 
        FROM S_OBJECTS 
        WHERE CODE = 'EDIT_FIELD_CLASS')
  ORDER BY CODE



DECLARE @varKSADDTYPE VARCHAR(100)
print '---------------------------------------'+@varKScCode+'(список для документа)'
  SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_VIEW_DOCUMENT_ZB 
--'+LTRIM(convert(char, getdate()))+'
VIEW dbo.' + LTRIM (@varKScCode) + '
AS
  SELECT  
    G.LINK'+CASE WHEN @varKScCode = @varKSRealCode THEN ',
    G.NUMBER,
'+
CASE WHEN @varKSSummaType = 0 THEN
'   [SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
'
ELSE
'   [FSUMMA] = ISNULL(dbo.CalcFinDocSumma(G.LINK), 0),
    [SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
'
END+
'   G.COMMENT,
    '+CASE WHEN @varKSDocType = 1 THEN 'YEAR(DATE) as YEAR,' 
      when @varKSDocType = 2 THEN 'G.DATE,
    F.FYEAR,
    F.PER_NUM,
    '+CASE  WHEN @varKScCode like '%_ASSIGN%' or @varKScCode like '%_SMETA%' THEN '''год'''
      WHEN @varKScCode = 'FB_RESULT_FINANS' or @varKScCode = 'FB_REESTR_RESULT'  THEN '(select period from periods where ord = F.PER_NUM)'
      ELSE '(case when W.FIN_LIM_TYPE=0 then ''год'' 
      else (case when W.FIN_LIM_PER=1 then ''год''
           when W.FIN_LIM_PER=2 then (select period from periods where ord = (F.PER_NUM-1)/3+13)
           else (select period from periods where ord = F.PER_NUM) end) end)' end + ' as period, 
    F.PARAM,
    (case when PARAM & 0x1 = 1 then ''Документ изменение''
      else ''Основной документ'' end) as CHANGE_LONG,
    [CHANGE] = ISNULL((PARAM & 0x1) ,1),
    [KAP_LIM] = ISNULL((PARAM & 0x2),0) / 2,
    [TYPE] = ISNULL((PARAM & 0x4),0) / 4,
    [F2] = ISNULL((PARAM & 0x8),0) / 8,
    [FDEP_LINK] = (SELECT REF_LINK_D FROM DICTIONARY_ACCOUNTS WHERE LINK = F.ACCOUNT),
    [FDEP_CODE] = CONVERT(VARCHAR(10),(SELECT FD.CODE FROM dbo.DEPARTMENTS FD, DICTIONARY_ACCOUNTS FDA  WHERE FD.LINK = FDA.REF_LINK_D AND FDA.LINK = F.ACCOUNT)),
    [FDEP_NAME] = CONVERT(varchar(100),(SELECT FD.NAME FROM dbo.DEPARTMENTS FD, DICTIONARY_ACCOUNTS FDA  WHERE FD.LINK = FDA.REF_LINK_D AND FDA.LINK = F.ACCOUNT)),
    [FACC_LINK] = F.ACCOUNT,
    [FACC_CODE] =   CONVERT(varchar(20), (SELECT CODE FROM DICTIONARY_ACCOUNTS WHERE LINK = F.ACCOUNT)),
    [FACC_NAME] =   CONVERT(varchar(80), (SELECT ANAME FROM DICTIONARY_ACCOUNTS WHERE LINK = F.ACCOUNT)),
    [LINK_REESTR] = F.LINK_REESTR,
    [NUM_REESTR]  =   CONVERT(varchar(25), (SELECT NUMBER FROM G_PROV WHERE LINK = F.LINK_REESTR)),
    [LINK_OSNOV] = F.LINK_OSNOV,
    [INFO_OSNOV] = CONVERT(varchar(250), (SELECT INFO FROM dbo.BD_OSNOV WHERE LINK = F.LINK_OSNOV))'    

    ELSE 'G.DATE' END + ', 
    G.DATE_PROV,
    [FLAG_JC] = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END' ELSE '' END 

+     ',
    [DEP_LINK]  = G.DEP,
    [DEP_CODE]  = DEP.CODE,
    [DEP_NAME]  = DEP.NAME'
+
    ',
    [ACC_LINK]  = G.ACC,
    [ACC_CODE]  =  CONVERT(varchar(20), (SELECT CODE FROM DICTIONARY_ACCOUNTS WHERE LINK = G.ACC)),
    [ACC_NAME]  =  CONVERT(varchar(80), (SELECT ANAME FROM DICTIONARY_ACCOUNTS WHERE LINK = G.ACC))'    

+
    CASE WHEN @varKSDocType = 3 THEN  
',
	[LINK_PRED] = GPCH.EMP_PRED,
	[TAB_PRED] = EMP.TAB,
	[FIO_PRED] = CONVERT(VARCHAR(60), (SELECT dbo.SD_GetEmplName(EMP.LINK))),
	[DOC_NUM] = CONVERT(VARCHAR(30), GPCH.DOC_NUM),
	[DOC_DATE] = CONVERT(DATETIME, GPCH.DOC_DATE),

	[BC_LINK]	= BHC.LINK,
	[BC_CODE]	= CONVERT (VARCHAR (5), BHC.CODE),
	[BC_NAME]	= BHC.COMMENT'
	
    ELSE '' END +
    CASE WHEN exists(Select * FROM DICTIONARY_STORAGE_DOCUMENTS WHERE DOC_CODE = @varKScCode) THEN ',
    G.GET_STORE' ELSE '' END

  
  OPEN SEL_CURSOR
  FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
    EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
    EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVisible OUTPUT
    
    IF Convert(int, @varKSInALIAS)&1 = 1 AND @varKSStorage<>'' 
    BEGIN
      EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD',  @varKSRefField OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ',    @varKSShortCode OUTPUT
      IF LEN(@varKSShortCode)>10
        print 'ПРЕДУПРЕЖДЕНИЕ: Длина поля SHORT_CODE_OBJ больше 10 символов!!!'

      SET @varKShostTypeObject = @varKSCurCODE
      IF (@varKSStorage = 'DICTION')AND @varKSRefField <> 'LINK'
      BEGIN
        SELECT @varKShostTypeObject = SO.CODE
          FROM S_OBJECTS SO, 
            OBJECT_VALUES OVH, S_OBJECTS SOH
          WHERE OVH.OBJECT = (Select LINK from S_OBJECTS where CODE = @varKSRefDict)
            AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
            AND SOH.CODE = RTRIM(OVH.VALUE)
            AND SO.LINK_SELF = SOH.LINK
            AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
            AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
        IF @@ROWCOUNT = 0
          print '******* Ошибка! Не найден базовый тип данных!'
      END
      IF @varKSStorage = 'DICTION_APP'
        SET @varKShostTypeObject = @varKSRefField
      EXECUTE X_GET_PROP  @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT
DECLARE @varKSCNE varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
      EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
      EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT
      
      SET @varKSINFO='  '+convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

      IF LTRIM(@varKSShortCode)='' OR @varKSShortCode is null
        print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
      
      IF @varKSStorage='DICTION'
      BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE
        BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPD.DICTION FROM dbo.G_PROV_DICTION GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.DICTION as D WITH (NOLOCK), dbo.G_PROV_DICTION GPD'+
            ' WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.DICTION)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='DEPARTMENT_ACCOUNTS' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPDA.ACCOUNT FROM dbo.G_PROV_DEP_ACCT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.DEPARTMENT_ACCOUNTS as D WITH (NOLOCK), dbo.G_PROV_DEP_ACCT GPD'+
            ' WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.ACCOUNT)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='DEPARTMENTS' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.DEPARTMENTS as D WITH (NOLOCK), dbo.G_PROV_DEPARTMENT GPD'+
            ' WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.DEPARTMENT)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='OSNOV' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPO.OSNOV FROM dbo.G_PROV_OSNOV GPO WHERE GPO.DOC_LINK = G.LINK AND GPO.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.BD_OSNOV as D WITH (NOLOCK), dbo.G_PROV_OSNOV GPO'+
            ' WHERE GPO.DOC_LINK = G.LINK AND GPO.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPO.OSNOV)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='BANKS' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPDA.BANK FROM dbo.G_PROV_BANK GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.BANKS as D WITH (NOLOCK), dbo.G_PROV_BANK GPD'+
            ' WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.BANK)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='SUBDIV' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPDA.SUBDIV FROM dbo.G_PROV_SUBDIV GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.SUBDIV as D WITH (NOLOCK), dbo.G_PROV_SUBDIV GPD'+
            ' WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.SUBDIV)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END


      IF @varKSStorage='G_PROV'
      BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
        END
        ELSE
        BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPR.DOC_REF_FOREIGN FROM dbo.G_PROV_REF GPR WHERE GPR.DOC_REF_PRIMARY = G.LINK AND GPR.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' 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='+LTRIM(STR(@varKSCurLINK))+' AND GR.LINK = GPR.DOC_REF_FOREIGN)'
          END

        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END
      IF @varKSStorage='VALUE' 
      BEGIN
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
          SET @varKSCur_Str = ' ['+@varKSShortCode+'] = CONVERT('+@varKSType+
              ', (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK) '+
              ' WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT='+LTRIM(STR(@varKSCurLINK))+')'
          IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
            SET @varKSCur_Str=@varKSCur_Str+',104'
          SET @varKSCur_Str=@varKSCur_Str+')'
          print  convert(char(10),@varKSShortCode)+'   VALUE                ' +convert(char(20),@varKSType)+' '+convert(char(20),@varKSStorage)+'-      '+@varKSINFO

      END
      IF @varKSStorage='DICTION_APP'
      BEGIN
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        IF LTRIM(@varKSType)='' OR @varKSType is null
          print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        SELECT @varKSCurLINK=LINK FROM S_OBJECTS  WHERE CODE=@varKSRefDict
        IF  @@ROWCOUNT=0
          print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
        SELECT @varKSCurLINK2=LINK FROM S_OBJECTS  WHERE CODE=@varKSRefField
        IF @@ROWCOUNT=0
          print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
        SET @varKSCur_Str = '['+@varKSShortCode+']= CONVERT('+@varKSType+
            ', (SELECT VALUE FROM DICTION_APP DA WITH (NOLOCK) WHERE LINK_UP=
              (SELECT LINK FROM  DICTION as D, G_PROV_DICTION as GPD WITH (NOLOCK) '+
            '  WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPD.DICTION) AND  DA.OBJECT='+LTRIM(STR(@varKSCurLINK2))+')'
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'
        SET @varKSCur_Str=@varKSCur_Str+')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        
      END

      IF @varKSStorage='EMPL' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPEM.EMPL FROM dbo.G_PROV_EMPL GPEM WHERE GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          WHEN @varKSRefField = 'NAME_EMPL' THEN 
          ' (SELECT dbo.sd_GetEmplName (GPE.EMPL) FROM dbo.G_PROV_EMPL GPE'+
            ' WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT='+LTRIM(STR(@varKSCurLINK))+')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.EMPL as D WITH (NOLOCK), dbo.G_PROV_EMPL GPE'+
            ' WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPE.EMPL)'

          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='KL_KBK' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPKBK.KBK FROM dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.KL_KBK as D WITH (NOLOCK), dbo.G_PROV_KBK GPKBK'+
            ' WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPKBK.KBK)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='KOSGU' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPSGU.SGU FROM dbo.G_PROV_SGU GPSGU WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.KOSGU as D WITH (NOLOCK), dbo.G_PROV_SGU GPSGU'+
            ' WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPSGU.SGU)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='INVENTORY' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null


            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPINV.INVENTORY FROM dbo.G_PROV_INVENTORY GPINV WHERE GPINV.DOC_LINK = G.LINK AND GPINV.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.INVENTORY as D WITH (NOLOCK), dbo.G_PROV_INVENTORY GPINV'+
            ' WHERE GPINV.DOC_LINK = G.LINK AND GPINV.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPINV.INVENTORY)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage='MENU_DECOMPOSE' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPMD.MENU_DECOMPOSE FROM dbo.G_PROV_MENU_DECOMPOSE GPMD WHERE GPMD.LINK_DOC = G.LINK AND GPMD.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.PA_MENU_DECOMPOSE as D WITH (NOLOCK), dbo.G_PROV_MENU_DECOMPOSE GPMD'+
            ' WHERE GPMD.LINK_DOC = G.LINK AND GPMD.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPMD.MENU_DECOMPOSE)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

      IF @varKSStorage = 'CALCULATE' BEGIN
        IF UPPER(LTRIM(RTRIM(@varKSType)))='DATETIME'
          SET @varKSADDTYPE=',104'

        ELSE
          SET @varKSADDTYPE=''

        IF @varKSRefField IS NOT NULL
          SET @varKSCur_Str = '['+@varKSShortCode+'] = convert(' + @varKSType +', '+@varKSRefField + @varKSADDTYPE+')' 
        ELSE BEGIN
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
          SET @varKSCur_Str = '' 
        END

      END

      IF @varKSStorage='S_ACCOUNTS' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPSA.ACCOUNT FROM dbo.G_PROV_S_ACCOUNTS GPSA WHERE GPSA.DOC_LINK = G.LINK AND GPSA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.S_ACCOUNTS as D WITH (NOLOCK), dbo.G_PROV_S_ACCOUNTS GPSA'+
            ' WHERE GPSA.DOC_LINK = G.LINK AND GPSA.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPSA.ACCOUNT)'
          END
        IF LTRIM(RTRIM(UPPER(@varKSType)))='DATETIME'
          SET @varKSCur_Str=@varKSCur_Str+',104'

        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

	IF @varKSStorage='CREDIT_TYPES' BEGIN
        SET @varKSCur_Str = '['+@varKSShortCode+']= '
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
        BEGIN
          SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
          IF @@ROWCOUNT=0
            print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
          SET @varKSCur_Str =@varKSCur_Str+ 'CONVERT('+@varKSType+','
          IF LTRIM(@varKSType)='' OR @varKSType is null
            print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
        END
        ELSE BEGIN
          SET @varKSType=' - '
          SET @varKSRefDict=' - '
        END
        IF LTRIM( @varKSRefField)='' OR @varKSRefField is null
          print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
        
        SET @varKSCur_Str=@varKSCur_Str + CASE WHEN @varKSRefField = 'LINK' THEN
          ' (SELECT GPSGU.SGU FROM dbo.G_PROV_SGU GPSGU WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
          ELSE
          ' (SELECT '+@varKSRefField+ ' FROM dbo.CREDIT_TYPES as D WITH (NOLOCK), dbo.G_PROV_CREDIT_TYPES GPCT'+
            ' WHERE GPCT.DOC_LINK = G.LINK AND GPCT.OBJECT='+LTRIM(STR(@varKSCurLINK))+' AND D.LINK = GPCT.TYPE)'
          END
        
        IF @varKSRefField<>RTRIM(LTRIM('LINK'))
          SET @varKSCur_Str = @varKSCur_Str + ')'
        print convert(char(10),@varKSShortCode)+'  '+ convert(char(35),@varKSRefDict) +'  '+convert(char(20),@varKSType)+'  '+convert(char(10),@varKSStorage)+' '+convert(char(30),@varKSRefField)+@varKSINFO
        IF @varKShostTypeObject <> @varKSCurCODE
          print '-------->' + @varKShostTypeObject + @varKSType
      END

        IF  NOT (@varKSStorage IN ('DICTION', 'DICTION_APP', 'VALUE', 'CALCULATE', 'G_PROV', 'DEPARTMENT_ACCOUNTS', 'DEPARTMENTS', 'OSNOV',
         'BANKS', 'SUBDIV', 'EMPL', 'INVENTORY', 'KL_KBK', 'KOSGU', 'MENU_DECOMPOSE', 'S_ACCOUNTS', 'CREDIT_TYPES'))
      BEGIN
        SET @varKSCur_Str=''
        Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE
      END 
      
      IF @varKSCur_Str is null
        SET @varKSCur_Str=''
      IF @varKSCur_Str<>''
      BEGIN
        SET  @varKSSel_Str=@varKSSel_Str+',
  '+@varKSCur_Str
      END
    END
    FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
  END   
  
  CLOSE SEL_CURSOR
  DEALLOCATE SEL_CURSOR
  IF RIGHT(@varKSSel_Str,1)=','
    SET @varKSSel_Str=LEFT(@varKSSel_Str,LEN(@varKSSel_Str)-1)
  SET  @varKSSel_Str=@varKSSel_Str+'
  FROM dbo.G_PROV as G WITH (NOLOCK)
  INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = G.DEP)'
  
  
  
IF @varKSDocType = 2 
  SET  @varKSSel_Str=@varKSSel_Str+'
  INNER JOIN workmode W on 1=1
  LEFT JOIN FINANSE_HEAD F ON F.LINK = G.LINK'

IF @varKSDocType = 3 
	SET  @varKSSel_Str=@varKSSel_Str + CHAR (13) + CHAR (10) 
		+ '	LEFT JOIN dbo.G_PROV_COMISSION_HEAD GPCH ON (GPCH.DOC_LINK = G.LINK)' + CHAR (13) + CHAR (10) 
		+ '	LEFT JOIN dbo.BUH_COMISSION_HEAD BHC ON (BHC.LINK = GPCH.COMISSION)' + CHAR (13) + CHAR (10) 
		+ '	LEFT JOIN dbo.EMPL EMP ON (EMP.LINK = GPCH.EMP_PRED)'

SET  @varKSSel_Str=@varKSSel_Str+'
  WHERE G.OBJECT='+LTRIM(STR((SELECT LINK FROM S_OBJECTS WHERE CODE = @varKSRealCode)))

  
  IF Object_id(@varKScCode) is not null
    SET @varKSSel_Str='ALTER ' + @varKSSel_Str
  ELSE
    SET @varKSSel_Str='CREATE ' + @varKSSel_Str

EXECUTE (@varKSSel_Str)

--print (@varKSSel_Str)

  DECLARE @varKSscriptstr varchar(7000)
  SET @varKSscriptstr = 'EXECUTE BK_FORM_VIEW_DOCUMENT_ZB '''+@varKScCode+''', ''' + isnull(@varKSRealCode, 'null')
     + ''', ' + convert(varchar(7), @varKSDocType) + ', ' + convert(varchar(4), @varKSSummaType)
     + ', '+ convert(varchar(4), @varKSTaskDivided)
  EXEC U_UPDATE_SCRIPT_PROPERTY @varKScCode, @varKSscriptstr


  UPDATE S_DBObjects SET Rights = 0x01 WHERE Object=@varKSnLink AND DBObject=@varKScCode
  IF @@ROWCOUNT = 0 
    INSERT INTO S_DBObjects(Object, DBObject, Rights)
      VALUES (@varKSnLink, @varKScCode, 0x01)
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_TABLE_PRINT_DETAIL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_TABLE_PRINT_DETAIL]
GO




CREATE                PROCEDURE dbo.FB_TABLE_PRINT_DETAIL
	@varKSiLink		int,
	@varKSintSummaType	tinyint = 1
	
	

AS

DECLARE @varKSTempTable TABLE(
	DOC		int, 
	VKR 	INT,
	EKR 	INT, 
	DOP_CL 	INT, 
	SUMMA	[numeric](28, 2) NULL,
	DOP		INT, 
	ORD		int)

DECLARE	@varKSintLimType	tinyint,
		@varKSintLimPer		tinyint,
		@varKScObjCode		varchar(30),
		@varKSintDopEkr		tinyint,
		@varKSintAbs		tinyint,
		@varKSintFyear 		int, 
		@varKSdDate 		datetime, 
		@varKSintPer_num	int, 
		@varKScTypeBudg 	Char(1), 
		@varKScTypePer	 	TINYINT 

	

	
SELECT @varKSintFyear 	= FYEAR
	FROM FINANSE_HEAD F 
WHERE LINK = @varKSiLink

SELECT @varKSdDate 	= DATE FROM G_PROV WHERE LINK = @varKSiLink

IF @varKSintSummaType = 2 
	INSERT INTO @varKSTempTable
	SELECT  LINK_UP, VKR, EKR, DOP_CL, sum(P1), 0, 1
	FROM dbo.FINANS_TABLE_YEAR_1000 T
	WHERE (LINK_UP = @varKSiLink and @varKSiLink is not null 
			or @varKSiLink is null and exists(select * from dbo.BufferGetTableByID('REPORT_RBS') where LINK = T.LINK_UP))
			and TYPE_KBK = 1
	GROUP BY LINK_UP, VKR, EKR, DOP_CL
ELSE
	INSERT INTO @varKSTempTable
	SELECT LINK_UP, VKR, EKR, DOP_CL, sum(P1), 0, 1  
	FROM dbo.FINANS_TABLE_YEAR T 
	WHERE (LINK_UP = @varKSiLink and @varKSiLink is not null 
			or @varKSiLink is null and exists(select * from dbo.BufferGetTableByID('REPORT_RBS') where LINK = T.LINK_UP))
			and TYPE_KBK = 1
	GROUP BY LINK_UP, VKR, EKR, DOP_CL

INSERT INTO @varKSTempTable
SELECT  DOC, VKR, EKR, NULL, sum(SUMMA), case when exists(select * from @varKSTempTable where F1.DOC = DOC and F1.VKR = VKR and F1.EKR = EKR and DOP_CL is null) then 2 else 1 end, 2
FROM @varKSTempTable F1
WHERE exists(select * from @varKSTempTable where F1.VKR = VKR and F1.EKR = EKR and DOP_CL is not null) 
GROUP BY DOC, VKR, EKR

INSERT INTO @varKSTempTable
SELECT F1.DOC, F1.VKR, EKR2.LINK, null, sum(SUMMA), 1, 3
FROM @varKSTempTable F1 
INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '0'
INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '0' AND NOT EXISTS(SELECT EKR FROM @varKSTempTable T1 WHERE F1.DOC = T1.DOC and T1.VKR = F1.VKR and T1.EKR = EKR2.LINK)
WHERE DOP = 0  
GROUP BY F1.DOC, F1.VKR,EKR2.LINK 

INSERT INTO @varKSTempTable
SELECT F1.DOC, F1.VKR, EKR2.LINK, null, sum(SUMMA), 1, 4
FROM @varKSTempTable F1 
INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '00'
INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,1) + '00' AND NOT EXISTS(SELECT EKR FROM @varKSTempTable T1 WHERE F1.DOC = T1.DOC and T1.VKR = F1.VKR and T1.EKR = EKR2.LINK)
WHERE DOP = 0  
GROUP BY F1.DOC, F1.VKR,EKR2.LINK 

select T.*,
		ORGNAME = D.NAME, 
		ORGACC = DA.CODE,
		OKPO = D.OKPO,
		CH = ISNULL((F.PARAM & 0x1) ,1),
		F_2 = ISNULL((F.PARAM & 0x8),0) / 8,
		DOC_NUM = G.NUMBER,
		OSNOV = isnull(O.INFO,''),
		[YEAR] = F.FYEAR 
	
from (Select	F.DOC,
		DIV = substring(rtrim(replace(VKR.CODE,'.','')),4,4),
		CSR = substring(rtrim(replace(VKR.CODE,'.','')),8,7),
		[EXP] = right(rtrim(replace(VKR.CODE,'.','')),3),
		EKR = EKR.CODE,
		DOP_CL = isnull(DCL.CODE,''),
		NAME = rtrim(case when F.DOP_CL is null then EKR.NAME else DCL.NAME end) + case F.DOP when 2 then '(Итого)' else '' end,
		SUMMA, 
		ITOG = (select sum(summa) from @varKSTempTable where F.DOC = DOC and DOP = 0),
		ORD		
From @varKSTempTable F  
LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
left outer JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
union all
Select	F.DOC,
		DIV = substring(rtrim(replace(VKR.CODE,'.','')),4,4),
		CSR = substring(rtrim(replace(VKR.CODE,'.','')),8,7),
		[EXP] = right(rtrim(replace(VKR.CODE,'.','')),3),
		EKR = '000',
		DOP_CL = '',
		NAME = VKR.NAME,
		sum(SUMMA), 0, 5
From @varKSTempTable F  
INNER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
WHERE DOP = 0 
GROUP BY F.DOC, VKR.CODE, VKR.NAME
union all
Select	F.DOC,
		DIV = DIV.CODE,
		CSR = CSR.CODE,
		[EXP] = '000',
		EKR = '000',
		DOP_CL = '',
		NAME = CSR.NAME,
		sum(SUMMA), 0, 6
From @varKSTempTable F  
INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
INNER JOIN dbo.KL_TARGET_ITEM CSR ON VKR.Link_CSR = CSR.link
WHERE DOP = 0 
GROUP BY F.DOC, DIV.CODE, CSR.CODE, CSR.NAME
union all
Select	F.DOC,
		DIV = DIV.CODE,
		CSR = CSR1.CODE,
		[EXP] = '000',
		EKR = '000',
		DOP_CL = '',
		NAME = CSR1.NAME,
		sum(SUMMA), 0, 7
From @varKSTempTable F  
INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
INNER JOIN dbo.KL_TARGET_ITEM CSR ON VKR.Link_CSR = CSR.link
INNER JOIN dbo.KL_TARGET_ITEM CSR1 ON left(CSR.CODE,3) + '0000' = CSR1.CODE
WHERE DOP = 0 
GROUP BY F.DOC, DIV.CODE, CSR1.CODE, CSR1.NAME
union all
Select	F.DOC,
		DIV = DIV.CODE,
		CSR = '0000000',
		[EXP] = '000',
		EKR = '000',
		DOP_CL = '',
		NAME = DIV.NAME,
		sum(SUMMA), 0, 8
From @varKSTempTable F  
INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
WHERE DOP = 0 
GROUP BY F.DOC, DIV.CODE, DIV.NAME
union all
Select	F.DOC,
		DIV = DIV1.CODE,
		CSR = '0000000',
		[EXP] = '000',
		EKR = '000',
		DOP_CL = '',
		NAME = DIV1.NAME,
		sum(SUMMA),0, 9
From @varKSTempTable F  
INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
INNER JOIN dbo.KL_DIVISION DIV1 ON left(DIV.CODE,2) + '00' = DIV1.CODE
WHERE DOP = 0 
GROUP BY F.DOC, DIV1.CODE, DIV1.NAME) T
inner join dbo.G_PROV G on T.DOC = G.LINK
inner join dbo.FINANSE_HEAD F on T.DOC = F.LINK
inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = F.ACCOUNT
inner join dbo.DEPARTMENTS D on DA.LINK_UP = D.LINK
left join dbo.BD_OSNOV O on O.LINK = F.LINK_OSNOV
order by  1, 2, 3, 4, 5, 9 desc

--select @varKSintDopEkr,* from @varKSTempTableDopEkr2
RETURN 1





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.FB_TABLE_PRINT 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_FILL_WITH_DICT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_FILL_WITH_DICT]
GO

/*******************************************************************************
	c Кейсистемс (Keysystems), 2006
	Для импорта динамических таблиц: загрузка некоторых столбцов из справочников, 
	например, для 428 формы загрузка столбца "Наименование показателя".
	Вызывается из процедуры RO_IMPORT_REPORT_STANDART, есть доступ к таблице:
	#t_Result(TXT varchar(1000), error bit)

*******************************************************************************/
CREATE       procedure dbo.RN_FILL_WITH_DICT
	@LSF int, -- линк сохраненного отчета
    @LF int, --линк отчета
	@OrderTable tinyint ,-- порядковый номер таблицы
	@cTMP_Table varchar(10)='', -- '#' данные записываем #REPORT_DINAMICS
	@varKSiNotUpdate tinyint = 0,	-- нужно ли делать апдейт, 1 - не нужно
	@varKSTableAbcentCode varchar(100) = ''
AS
declare  @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
	@ExecStr nvarchar(4000), @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @property TINYINT, @vcDictWhere VARCHAR(1000)

    if @LF is NULL
        begin
			select @LF  = Link_Form from report_saved_forms where Link_Saved_Form = @LSF
        end

select @LC = Link_Code_Col, @LT = Link_Table from #report_tables where orders = @OrderTable and Link_Form = @LF

if @LC is NULL
begin
	return -2
end

select @property = property, @OrderCol = Orders, @Dict = LTRIM(RTRIM(Dictionary)), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List), @vcDictWhere =RTRIM(ISNULL(Dictionary_Where,'')) 
   from #report_coloumns where Link_Col = @LC

SELECT @vcDictWhere = REPLACE(REPLACE(REPLACE(@vcDictWhere, '%link_org%', LTRIM(STR([Link_Organization]))), '%link_budg%', LTRIM(STR(ISNULL([Link_Type_Svod], 0)))), '%date%', '''' + CONVERT(VARCHAR(10), [Begin_Date], 112) + '''')
FROM dbo.report_saved_forms 
WHERE [Link_Saved_Form] = @LSF 

if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
begin
	return 0 -- нет подключенных справочников
end
create table #t_CodeRow (Code varchar(50))
--create table #t_Abcent_CodeRow (Code varchar(50))
set @Cols = ''
set @Field =''
set @Fields = ''
set @Col = ''
declare @icount int
set @icount=1
set @Field=dbo.rn_getWordNum(@DictField,@icount,',')
while @Field <> '' 
begin
    set @Field=dbo.rn_getWordNum(@DictField,@icount,',')
    set @Col=dbo.rn_getWordNum(@DictCol,@icount,',')

	set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
	if @i = @OrderCol
	begin
		set @CodeCol = @Col -- ключевой столбец
		set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
	end
	else begin
		set @Fields = @Fields + @Field + ','
		set @Cols = @Cols + @Col + ','
	end
    set @icount=@icount+1
end

if @Fields = '' or @Cols = ''
begin
	return 0 -- нет полей, кроме ключевого столбца
end

set @Fields = LEFT(@Fields, LEN(@Fields) - 1)
set @Cols =  LEFT(@Cols, LEN(@Cols) - 1)

--добавление итоговых строк
        if EXISTS(select * from syscolumns where id = object_id (@DICT) and name = 'PROPERTY') and EXISTS(select * from syscolumns where id = object_id (@DICT) and name = 'CODE')
            begin
              	select @LinkCol = Link_Col from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@CodeCol, 'COL', ''))
                set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF,Link_Col,Code_Row)
               	select distinct ' + STR(@LSF) + ', ' + STR(@LinkCol) + ',RTRIM('+@FieldCol+') from dbo.'+@dict+' D where property&2>0 
                and not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  D.'+@FieldCol+')'
                 
            end
        --print @ExecStr
         exec sp_executesql @ExecStr

IF @cTMP_Table=''
    begin
            insert #t_CodeRow
         	select distinct RTRIM(Code_Row) from dbo.report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
    end
    ELSE
    begin
        insert #t_CodeRow
     	select distinct RTRIM(Code_Row) from #report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
    end
--select * from #t_CodeRow


exec dbo.RN_FILL_WITH_CODEROW @LSF,@LF,@ORDERTABLE

-----------------------
if @varKSTableAbcentCode <> '' --and isnull(@property,0)&4 = 4
begin
	 set @ExecStr = 'insert ' + @varKSTableAbcentCode + ' (Code)
	  select Code
	  from #t_CodeRow CR
	  where not exists(select * from dbo.'+@Dict + ' D where D.' + Ltrim(@FieldCol) + ' = CR.Code' + CASE WHEN @vcDictWhere = '' THEN '' ELSE ' and ' + @vcDictWhere END + ')'
	exec sp_executesql @ExecStr
end
------------------------------


while @Fields <> '' and @Cols <> ''
begin
	exec dbo.RO_FORMULA_FUNCTIONS 1, @Cols output, @Col output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @Fields output, @Field output, ','
	select @LinkCol = Link_Col from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@Col, 'COL', ''))
set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val) 
select ' + STR(@LSF) + ', ' + STR(@LinkCol) + ', CR.Code, 0, max(D.' + @Field + ')
from #t_CodeRow CR inner join (select distinct ' + @FieldCol + ', ' + @Field + ' from dbo.' + @Dict + CASE WHEN @vcDictWhere = '' THEN '' ELSE ' where ' + @vcDictWhere END + ') D on CR.Code = D.' + @FieldCol + '
where not exists(select top 1 * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  CR.Code)'
+ ' group by CR.Code'

--if @varKSiNotUpdate = 0
--begin
	set @ExecStr =  @ExecStr +'
update  '+@cTMP_Table+'report_dinamics set Str_Val= D.' + @Field + '
	from '+@cTMP_Table+'report_dinamics CR inner join dbo.' + @Dict + ' D on CR.Code_row = D.' + @FieldCol + '
	where CR.link_SF=' + STR(@LSF) + 'and Link_col=' + STR(@LinkCol)+ ' and str_val='''''
   + CASE WHEN @vcDictWhere = '' THEN '' ELSE ' and ' + @vcDictWhere END 
--end

print @ExecStr
 exec sp_executesql @ExecStr

/*	set @ExecStr = 'insert #t_Abcent_CodeRow (Code)
	select Code
	from #t_CodeRow CR
	where not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  CR.Code)'
	print @ExecStr
	execute(@ExecStr)*/
end

drop table #t_CodeRow
--drop table #t_Abcent_CodeRow

GO
GRANT ALL ON dbo.[RN_FILL_WITH_DICT] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_373]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_373]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_373]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '*|*****|***|***|********|', '8|88888|888|888|88888888|')
      WHERE TXT LIKE '%*|*****|***|***|********|%'
            and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=03')
         and [ORDER] < (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=04')

      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '*|*****|***|***|********|', '9|99999|999|999|99999999|')
      WHERE TXT LIKE '%*|*****|***|***|********|%'
         and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=04')

      UPDATE #IMPORT_TABLE
      SET TXT = ''
      WHERE TXT IN ('ТБ=02', 'ТБ=04')


      UPDATE #IMPORT_TABLE
      SET TXT = 'ТБ=02'
      WHERE TXT IN ('ТБ=03')
 
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_373] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_125M]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_125M]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_125M]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON
DECLARE @liReturn INT,
        @i        INT,
        @k        INT,
        @j        INT,
        @lbIsYear BIT,
        @lvcTXT   VARCHAR(8000),
        @liORDER  INT,
        @lvcWord  VARCHAR(50),
        @liRerurn INT,
		@vcKSBU	  VARCHAR(100)       
  
DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT)         
                        
DECLARE @tabHead TABLE ([TXT]   VARCHAR(1000), 
                        [ORDER] INT)

DECLARE @tabRD TABLE ([ORDER] INT,
                      [RD]    TINYINT)                             

DECLARE @tabHeap TABLE ([TXT]   VARCHAR(1000), 
                        [ORDER] INT)

SET @liRerurn = 0

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE] @lbSvodWEB,
                                                                 @liRepeatRequest,
                                                                 @tIsAppend,
                                                                 @bDinamicRows,
                                                                 @iLINK_SELF,
                                                                 @tMode
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ТипФорм=1С:СводОтчетов')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_125_1C] @lbSvodWEB,
                                             	@liRepeatRequest,
                                                @tIsAppend,
	                                             @bDinamicRows,
                                                @iLINK_SELF,
                                                @tMode
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] like '%<SchemaVersion Number="2" Owner="%" Application="%"/>%')
BEGIN

   EXEC @liReturn = dbo.[RO_IMPORT_FORM_125_SKIF] @lbSvodWEB,
                                             	@liRepeatRequest,
                                                @tIsAppend,
	                                             @bDinamicRows,
                                                @iLINK_SELF,
                                                @tMode
   RETURN @liReturn
END
IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE LEFT([TXT],5) = '<?xml')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_125_1C_XML] @lbSvodWEB,
                                             	    @liRepeatRequest,
                                                    @tIsAppend,
	                                                 @bDinamicRows,
                                                    @iLINK_SELF,
                                                    @tMode
   RETURN @liReturn
END



IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1')) OR
   ISNULL(@liRepeatRequest,0) > 0
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode
   RETURN @liRerurn
END


IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
   
BEGIN        
   INSERT @tabImport ([TXT], 
                      [ORDER])
   SELECT [TXT],
          [ORDER]
   FROM #IMPORT_TABLE
   ORDER BY [ORDER]     

   SET @i = 0

   SELECT @i = MIN([ORDER])
   FROM @tabImport
   WHERE [TXT] LIKE '%КСБУ=%'

   INSERT @tabHead([TXT],
                   [ORDER])
   SELECT [TXT],
          [ORDER]
   FROM @tabImport
   WHERE [ORDER] < @i          

   WHILE ISNULL(@i,0) > 0
   BEGIN
      IF OBJECT_ID('tempdb..#IMPORT_TABLE') IS NOT NULL
      BEGIN
         DROP TABLE #IMPORT_TABLE
      END        
                                     
      CREATE TABLE #IMPORT_TABLE([TXT] VARCHAR(1000), 
                                 [ORDER] INT IDENTITY(1,1))     
  
/*
      DELETE #IMPORT_TABLE
      DBCC CHECKIDENT ('#IMPORT_TABLE',RESEED,0)
*/                                 
      SELECT @k = MIN([ORDER])
      FROM @tabImport
      WHERE [TXT] LIKE '%КСБУ=%' AND
            [ORDER] > @i   

		select @vcKSBU = SUBSTRING(TXT,6,9) 
		from @tabImport
		WHERE [TXT] LIKE '%КСБУ=%' AND
            [ORDER] > @i   		
            
      INSERT #IMPORT_TABLE([TXT])
      SELECT [TXT]
      FROM @tabHead
      ORDER BY [ORDER]
    
      INSERT #IMPORT_TABLE([TXT])
      SELECT [TXT]
      FROM @tabImport 
      WHERE [ORDER] = @i
      
      DELETE @tabHeap
      DELETE @tabRD
      
      INSERT @tabHeap([TXT],
                      [ORDER])
      SELECT [TXT],
             [ORDER]
      FROM @tabImport 
      WHERE CHARINDEX('|',[TXT]) > 0 AND
            [ORDER] > @i AND
            ([ORDER] < @k OR @k IS NULL)
      
      SET @j = 0
      
      UPDATE @tabHeap
      SET [TXT] = RTRIM([TXT])+ISNULL(REPLICATE('0',3 - LEN(LTRIM(STR(@j)))),'') + LTRIM(STR(@j)),
          @j = @j + 1
      
      UPDATE @tabHeap
      SET [TXT] = RTRIM([TXT])+'ИП'
      WHERE dbo.[RA_GETWORDNUM]([TXT],9,'|') = '*'

      UPDATE @tabHeap
      SET [TXT] = LEFT(RTRIM([TXT]), CHARINDEX('|', TXT, CHARINDEX('|', TXT, 60) + 1 ))+'Итого'
      WHERE [TXT] LIKE  '***|********|**|***|**************|*|*****|***|*|*****|***|%'

      UPDATE @tabHeap
      SET [TXT] = RTRIM([TXT])+'ИД'
      WHERE TXT not like '%ИП' and TXT not like '%Итого'
			and (dbo.[RA_GETWORDNUM](TXT, 10, '|') in ('21002','30405') or dbo.[RA_GETWORDNUM](TXT, 11, '|') in ('510','610'))

      UPDATE @tabHeap
      SET [TXT] = RTRIM([TXT])+'ИН'
      WHERE TXT not like '%ИП' and TXT not like '%Итого' and TXT not like '%ИД'


		INSERT @tabRD([ORDER],[RD])
		select [ORDER], 4
		from @tabHeap 

--      DECLARE curHeap CURSOR FOR
--      SELECT [TXT],
--             [ORDER]
--      FROM @tabHeap
--      ORDER BY [ORDER]
--
--      OPEN curHeap
--      
--      FETCH NEXT
--      FROM curHeap
--      INTO @lvcTXT,
--           @liORDER
--            
--      WHILE @@FETCH_STATUS = 0
--      BEGIN
--         IF RIGHT(RTRIM(@lvcTXT),2) = 'ИП' and isnull(SUBSTRING(@vcKSBU,7,3), '000') = '000'
--         BEGIN
--            INSERT @tabRD([ORDER],[RD]) VALUES (@liORDER,4)
--         END
--         ELSE BEGIN
--			select @lvcTXT, dbo.[RA_GETWORDNUM](@lvcTXT,5,'|')
--            IF EXISTS (SELECT *
--                       FROM dbo.[RN_VIEW_DOH_14_2010]
--                       WHERE [CODE] = dbo.[RA_GETWORDNUM](@lvcTXT,5,'|'))  and SUBSTRING(@vcKSBU,7,1) in ('1')
--            BEGIN
--               INSERT @tabRD([ORDER],[RD]) VALUES (@liORDER,1)
--            END
--            ELSE BEGIN
--               IF EXISTS (SELECT *
--                          FROM dbo.[RN_VIEW_IST_125M_2010]
--                          WHERE [CODE] = dbo.[RA_GETWORDNUM](@lvcTXT,5,'|') ) and SUBSTRING(@vcKSBU,7,1) in ('7', '8')
--               BEGIN
--                  INSERT @tabRD([ORDER],[RD]) VALUES (@liORDER,3)
--               END                          
--               ELSE BEGIN
--                  INSERT @tabRD([ORDER],[RD]) VALUES (@liORDER,2)
--               END
--            END
--         END
--        
      
      /*
         select * from report_coloumns where link_table in (select link_table from report_tables where link_Form in (select link_form from report_forms where code='(72н)0503125М'))
         select * from RN_VIEW_KBK_0503125M01
         select * from RN_VIEW_KBK_0503125M03
      */
--         FETCH NEXT
--         FROM curHeap
--         INTO @lvcTXT,
--              @liORDER
--      END
--      
--      CLOSE curHeap
--      DEALLOCATE curHeap
      
      
--      select * from @tabRD
      
      SET @j = 1
      WHILE @j < 5
      BEGIN
         INSERT #IMPORT_TABLE([TXT]) VALUES ('#')
         INSERT #IMPORT_TABLE([TXT]) VALUES ('#@')
         INSERT #IMPORT_TABLE([TXT]) VALUES ('ТБ=0' + LTRIM(STR(@j)))
         INSERT #IMPORT_TABLE([TXT]) VALUES ('#$')

         INSERT #IMPORT_TABLE([TXT]) 
         SELECT [TXT]
         FROM @tabHeap [A]
         JOIN @tabRD   [B] ON [A].[ORDER] = [B].[ORDER]
         WHERE [B].[RD] = @j
         
         INSERT #IMPORT_TABLE([TXT]) VALUES ('#')
         INSERT #IMPORT_TABLE([TXT]) VALUES ('#%')
         SET @j = @j + 1
      END
      
/*            
      DELETE #IMPORT_TABLE 
      WHERE [TXT]='#%'
*/      

--	-- добавила, т.к. не импортировалось    
--    update #IMPORT_TABLE 
--	set TXT = '|'+dbo.[RA_GETWORDNUM](TXT, 12, '|')+'|'+dbo.[RA_GETWORDNUM](TXT, 13, '|')+'|'
--			+ case when dbo.[RA_GETWORDNUM](TXT, 10, '|') in ('21002','30405') or dbo.[RA_GETWORDNUM](TXT, 11, '|') in ('510','610') then '1' else '0' end + '|'
--			+dbo.[RA_GETWORDNUM](TXT, 1, '|')+left(dbo.[RA_GETWORDNUM](TXT, 2, '|')+'00000000000',11)+RIGHT('00'+dbo.[RA_GETWORDNUM](TXT, 3, '|'),2)+dbo.[RA_GETWORDNUM](TXT, 4, '|')+dbo.[RA_GETWORDNUM](TXT, 5, '|')+dbo.[RA_GETWORDNUM](TXT, 9, '|')+dbo.[RA_GETWORDNUM](TXT, 10, '|')+dbo.[RA_GETWORDNUM](TXT, 11, '|')+dbo.[RA_GETWORDNUM](TXT, 14, '|')
--	where TXT like '%|%' and [order] > (select [order] from #IMPORT_TABLE where TXT = 'ТБ=01')and [order] < (select [order] from #IMPORT_TABLE where TXT = 'ТБ=02')
--
--    update #IMPORT_TABLE 
--	set TXT = '|'+dbo.[RA_GETWORDNUM](TXT, 12, '|')+'|'+dbo.[RA_GETWORDNUM](TXT, 13, '|')+'|'
--			+ case when dbo.[RA_GETWORDNUM](TXT, 10, '|') in ('21002','30405') or dbo.[RA_GETWORDNUM](TXT, 11, '|') in ('510','610') then '1' else '0' end + '|'
--			+dbo.[RA_GETWORDNUM](TXT, 1, '|')+left(dbo.[RA_GETWORDNUM](TXT, 2, '|')+'00000000000',11)+RIGHT('00'+dbo.[RA_GETWORDNUM](TXT, 3, '|'),2)+dbo.[RA_GETWORDNUM](TXT, 4, '|')+dbo.[RA_GETWORDNUM](TXT, 5, '|')+dbo.[RA_GETWORDNUM](TXT, 9, '|')+dbo.[RA_GETWORDNUM](TXT, 10, '|')+dbo.[RA_GETWORDNUM](TXT, 11, '|')+dbo.[RA_GETWORDNUM](TXT, 14, '|')
--	where TXT like '%|%' and [order] > (select [order] from #IMPORT_TABLE where TXT = 'ТБ=03')and [order] < (select [order] from #IMPORT_TABLE where TXT = 'ТБ=04')


--select * from #IMPORT_TABLE
--
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode

      SET @i = @k                  
   END         
END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_125M] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REP_F417]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_F417]

GO

CREATE  PROCEDURE [dbo].SD_REP_F417
	@varKScYear VARCHAR(254),
	@varKSnLinkEmpl INT,
	@nCheck1 int = 0/* Объединять начисления */
AS 
BEGIN
	DECLARE @varKSnYear INT
	SELECT @varKSnYear = CAST(@varKScYear AS INT)
	DECLARE @varKSnLinkPers INT
	
	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output	

	SELECT @varKSnLinkPers = PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl

	DECLARE @varKSstart_date DATETIME, 
			@varKSEND_DATE DATETIME

	SELECT @varKSstart_date = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	SELECT @varKSEND_DATE  = dbo.DateEndOfYear(@varKSstart_date)

	DECLARE 
		@varKSCODE_FKR_D VARCHAR(10), @varKSNAME_FKR_D VARCHAR(254),
		@varKSCODE_FKR_T VARCHAR(10), @varKSNAME_FKR_T VARCHAR(254),
		@varKSCODE_FKR_E VARCHAR(10), @varKSNAME_FKR_E VARCHAR(254),
		@varKSDate datetime

	SELECT TOP 1
		@varKSCODE_FKR_D = CODE_FKR_D, @varKSNAME_FKR_D = NAME_FKR_D,
		@varKSCODE_FKR_T = CODE_FKR_T, @varKSNAME_FKR_T = NAME_FKR_T,
		@varKSCODE_FKR_E = CODE_FKR_E, @varKSNAME_FKR_E = NAME_FKR_E,
		@varKSDate = dpe.date_begin
	FROM 
		dbo.BI_DICTION_VKR VKR 
		INNER JOIN dbo.SAL_SFIN F ON F.KBK = VKR.LINK		
		INNER JOIN dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE ON DPE.LINK_KBK = F.LINK
	WHERE 
		DPE.DATE_BEGIN <= @varKSEND_DATE  
	ORDER BY 
		DPE.DATE_BEGIN DESC

	CREATE TABLE #PART1(SUBDIV VARCHAR(254),FIO VARCHAR(254),TAB_NUM VARCHAR(15),
						BIRTH DATETIME, KATEG VARCHAR(254), OBR VARCHAR(254), 
						ZV_STEP VARCHAR(254), EXPIR VARCHAR(40), 
						OSN_OKL NUMERIC(20,2), CHILDREN INT, IZHD INT, INV VARCHAR(20))
	
	INSERT INTO #PART1
	SELECT TOP 1
		[SUBDIV]  = EP.SUBDIV_NAME,
		[FIO] 	  = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
		[tab_num] = EP.TAB,
		[BIRTH]   = P.BIRTHDATE,
		[KATEG]   = '',
		[OBR] 	  = (SELECT NAME FROM EDUCTYPE WHERE LINK =  PE.EDUC_LINK),
		[ZV_STEP] = RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_STATUS WHERE LINK = P.ACAD_STATUS_LINK),'')) + ' ' 
					+ RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_DEGREE WHERE LINK = P.ACAD_DEGREE_LINK),'')),
		[EXPIR]   = '',
		[OSN_OKL] = (SELECT OKLAD FROM dbo.SALARY_OKLAD(@varKSEND_DATE,@varKSnLinkEmpl, DEFAULT, @DEP_LINK)),
		[CHILDREN] = (SELECT COUNT(*) FROM dbo.KU_PERS_FAMILY F WHERE 
									F.PERS_LINK = EP.PERS_LINK AND YEAR(F.[BIRTHDATE]) <= @varKSnYear
									AND FAMILY_NAME IN ('Сын','Дочь')),
		[IZHD] = (SELECT COUNT(*) FROM dbo.PERS_FAMILY F WHERE 
									F.PERS_LINK = EP.PERS_LINK  AND IZHD = 1 AND @varKSnYear BETWEEN YEAR(F.[IZHD_BEG]) AND ISNULL(YEAR(F.[IZHD_END]),@varKSnYear)),
		[INV] = (SELECT TOP 1 LTRIM(RTRIM(PV.GROUP_NAME)) FROM dbo.KU_PERS_INVALID PV
				 WHERE PV.PERS_LINK = P.LINK AND @varKSEND_DATE BETWEEN DATE_BEGIN AND ISNULL(DATE_END,@varKSEND_DATE))
	FROM 
		dbo.SD_EMPL_FN(@varKSnLinkEmpl, @varKSEND_DATE, DEFAULT, @DEP_LINK) EP  
		INNER JOIN dbo.PERSON P ON (EP.PERS_LINK = P.LINK)
		LEFT OUTER JOIN dbo.KU_PERS_EDUCATION PE ON (P.LINK = PE.PERS_LINK)

	--Вычисление категории
	DECLARE @varKSKATEG VARCHAR(4000), @varKSTMP_STR VARCHAR(254)
	SET @varKSKATEG = ''
	DECLARE #KAT_CURSOR CURSOR LOCAL FAST_FORWARD FOR

	SELECT TOP 1 ISNULL(QUALIFY, '') 
	FROM dbo.KU_PERS_EDUCATION PE
	WHERE PERS_LINK = @varKSnLinkPers AND YEAR(DATE_END) <= @varKSnYear
	ORDER BY SATISFY DESC
	
	OPEN #KAT_CURSOR
	FETCH #KAT_CURSOR INTO @varKSTMP_STR
	WHILE @@FETCH_STATUS = 0 BEGIN
		SET @varKSKATEG = @varKSKATEG + ' ' + RTRIM(@varKSTMP_STR)
		FETCH #KAT_CURSOR INTO @varKSTMP_STR
	END
	CLOSE #KAT_CURSOR
	DEALLOCATE #KAT_CURSOR

	UPDATE #PART1 SET KATEG = LTRIM(RTRIM(@varKSKATEG))

	--	
	declare @varKSdays int, @varKSmonths int, @varKSyears int, @varKScDate varchar(10)
	SELECT @varKSyears = years, @varKSmonths = months, @varKSdays = days from dbo.ku_EmplExpirTable(@varKSnLinkEmpl,@varKSEND_DATE, DEFAULT) ET WHERE ET.EXPIR_CODE = 'GEN'  

	UPDATE #PART1 SET EXPIR = 
		RTRIM(LTRIM(CAST (@varKSyears AS VARCHAR(4) ))) + ' лет '
		+ RTRIM(LTRIM(CAST (@varKSmonths AS VARCHAR(2) ))) + ' месяцев '
		+ RTRIM(LTRIM(CAST (@varKSdays AS VARCHAR(2) ))) + ' дней '

	CREATE TABLE #DPE (LINK_EMPL INT, LINK_PAYS INT, ORDER_DATE DATETIME, DATE_BEGIN DATETIME, DATE_END DATETIME, VALUE NUMERIC(18,4))
	
	INSERT INTO #DPE (LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE)
	SELECT LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE 
	FROM dbo.DICTIONARY_PAYS_EMPL_FN(DEFAULT,@varKSnLinkEmpl,0,DEFAULT,DEFAULT,DEFAULT)

	CREATE TABLE #PAYS_EMPL(
		LINK_PAY INT, cp varchar(10), NP VARCHAR(254), 
		date_begin datetime, date_end datetime,
		s numeric(20,2), parent_id int
	)

	-- На начало года
	INSERT INTO #PAYS_EMPL
	SELECT 
		ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), NULL, VALUE, 0
	FROM 
		#DPE DPE
		INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
		LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1 
	WHERE 
		LINK_EMPL = @varKSnLinkEmpl
		AND @varKSstart_date - 1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
		AND VALUE > 0

	-- Изменения в выбранном году
	INSERT INTO #PAYS_EMPL
	SELECT 
		ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), 
		ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), 
		DATE_END, VALUE, 0
	FROM 
		#DPE DPE
		INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
		LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
	WHERE 
		LINK_EMPL = @varKSnLinkEmpl
		AND YEAR(ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN)) = @varKSnYear
		AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
		AND VALUE > 0
		AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK) AND PE.date_begin = ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN))

	-- Прочие действующие сейчас начисления
	INSERT INTO #PAYS_EMPL
	SELECT 
		ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), NULL, NULL, VALUE, 0
	FROM 
		#DPE DPE
		INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
		LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
	WHERE 
		LINK_EMPL = @varKSnLinkEmpl
		AND DATE_BEGIN = (Select max(DATE_BEGIN) from dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE1 where DPE1.LINK_EMPL = DPE.LINK_EMPL and DPE1.LINK_PAYS = DPE.LINK_PAYS and DPE1.DATE_BEGIN <= @varKSEND_DATE AND ISNULL(DPE1.DATE_END, '30000101') >= @varKSstart_date) 
		AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
		AND VALUE > 0
		AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK))

	UPDATE #PAYS_EMPL
	SET DATE_BEGIN = NULL
	WHERE DATE_BEGIN < @varKSstart_date

	UPDATE R
	SET CP = CP + '*', NP = NP + '*'
	FROM
		#PAYS_EMPL R
		INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAY

	CREATE TABLE #TMP2 ( ID INT IDENTITY, ORDER_DATE datetime, ORDER_NUM VARCHAR(30), 
		SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
		KATEG VARCHAR(254), AVANSE NUMERIC(20, 2), REAL_REC BIT
	)
	
	--INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
	--	REAL_REC)
	--SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
	--FROM DICTIONARY_PURP_DISP_FACES 
	--WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) < @varKSnYear
	--ORDER BY DATE_PD DESC

	CREATE TABLE #STAFF_INFO(LINK_UP INT, SUBDIV_NAME VARCHAR(254), POST_NAME VARCHAR(254), DATE_BEGIN DATETIME, DATE_END DATETIME)
	INSERT INTO #STAFF_INFO(LINK_UP, SUBDIV_NAME, POST_NAME, DATE_BEGIN, DATE_END)
	SELECT 
		S.LINK_UP, 
		(SELECT TOP 1 [name] FROM subdiv WHERE link_up = s.subdiv_link and (s.date_begin between date_begin and date_end or s.date_begin < date_begin and s.date_end > date_end or s.date_end between date_begin and date_end)),
		DP.NAME,
		S.DATE_BEGIN, 
		S.DATE_END
	FROM 
		DBO.STAFF_HEAD SH
		INNER JOIN dbo.staff s ON s.link_up=sh.link
		LEFT OUTER JOIN dbo.POST DP ON DP.LINK = s.post_link
	
	--Приказы о приёме и переводе
	---------------------------
	-- Прием
	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
	SELECT 
		o.[DATE], o.NUMBER, 'ПРИНЯТ(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104), S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
	FROM 
		ITEM_MOVE im 
		INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE = 1
		LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
		
	WHERE 
		im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) <= @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
	ORDER BY 
		IM.DATE_BEGIN DESC
	---
	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,REAL_REC)
	SELECT NULL, NULL, NULL, NULL, '', '', 1
	WHERE EXISTS (
		SELECT * FROM #DPE DPE WHERE LINK_EMPL = @varKSnLinkEmpl
				AND @varKSstart_date-1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
				AND VALUE > 0	
		)		

	---		
	--Перевод
	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
	SELECT 
		o.[DATE], o.NUMBER, 
		case when ORD.obj_code = 'MOVES' then 'ПЕРЕВЕДЕН(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104)
			 else ORD.type_txt + ' ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104) end	, 
		S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
	FROM 
		ITEM_MOVE im 
		INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
		inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
		LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
		
	WHERE 
		im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
	
	union 
	 	SELECT DISTINCT DATE_BEGIN, null, '','','','',1
		FROM #PAYS_EMPL
		WHERE 
		DATE_BEGIN NOT IN (SELECT ISNULL(O.[DATE],'18000101') FROM ITEM_MOVE im 
							INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
							inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
							LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
								WHERE 
							im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear)
		AND DATE_BEGIN >= ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
							INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK /*and im.active=1*/ AND IM.NEW_FACE not in(2,1)
							inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
							LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
								WHERE 
							im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')
							
	/*ORDER BY 
		DATE_BEGIN ASC*/
	-----------------------------
		
	-- Приказы об увольнении
	DECLARE @DICTIONARY_PUV INT
	SET @DICTIONARY_PUV = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_PUV')

	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
	SELECT 
		o.[DATE], o.NUMBER, 'УВОЛЕН(А) ' + CONVERT(VARCHAR(10),DIS_DATE,104), LEFT(D.NAME,254), '', '', 1
	FROM 
		dbo.ITEM_DIS_FACE DF
		INNER JOIN dbo.ORDERS O ON DF.ORDER_LINK=o.LINK and DF.active=1
		INNER JOIN dbo.DICTION D ON D.LINK = DF.REASON
	WHERE 
		DF.EMPL_LINK = @varKSnLinkEmpl AND YEAR(DF.DIS_DATE) = @varKSnYear	
	ORDER BY 
		DF.DIS_DATE DESC		
		
	DECLARE @varKSDATE_MIN DATETIME, @varKSADVANCE NUMERIC(20, 2)

	SELECT @varKSADVANCE = OKL.OKLAD * ISNULL(AVANCE, 0) / 100.0 
	FROM EMPL E,dbo.salary_oklad(@varKSEND_DATE, @varKSnLinkEmpl, DEFAULT, @DEP_LINK) OKL  
	WHERE OKL.LINK_EMPL = @varKSnLinkEmpl AND E.LINK = OKL.LINK_EMPL 

	SET @varKSDATE_MIN = ISNULL((SELECT MIN(ORDER_DATE) FROM #TMP2), '18000101')

	/*INSERT INTO #TMP2(ORDER_DATE, REAL_REC)
	SELECT DISTINCT DATE_BEGIN, 1
	FROM #PAYS_EMPL
	WHERE 
		DATE_BEGIN NOT IN (SELECT ISNULL(ORDER_DATE,'18000101') FROM #TMP2)
		AND DATE_BEGIN >= @varKSDATE_MIN
	*/
	DECLARE #TMP_CUR CURSOR LOCAL FAST_FORWARD FOR 
		SELECT ID, ORDER_DATE
		FROM #TMP2
		ORDER BY ORDER_DATE DESC
	DECLARE @varKSID INT, @varKSORDER_DATE DATETIME
	
	OPEN #TMP_CUR
	FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
	WHILE @@FETCH_STATUS = 0 BEGIN
		UPDATE #PAYS_EMPL
		SET PARENT_ID = @varKSID 
		WHERE 
			PARENT_ID = 0 
			AND DATE_BEGIN >= @varKSORDER_DATE
		FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
	END
	CLOSE #TMP_CUR
	DEALLOCATE #TMP_CUR

	
	UPDATE #PAYS_EMPL
	SET PARENT_ID = @varKSID 
	WHERE 
		PARENT_ID = 0 

	UPDATE #TMP2 SET AVANSE = @varKSADVANCE WHERE ORDER_DATE = @varKSDATE_MIN
	DECLARE @varKSPAYS_EMPL VARCHAR(100), @varKSTMP2 VARCHAR(120)
	EXEC X_GET_TABLE_NAME @varKSPAYS_EMPL OUTPUT
	SET @varKSTMP2 = @varKSPAYS_EMPL + '_1'

	EXEC M_CROSS_TABLE 
		'PARENT_ID',
		'CP, NP',
		'VARCHAR(10)#VARCHAR(254)',
		'S',
		'NUMERIC(20,2)',
		'SUM(S) AS S',
		'#PAYS_EMPL',
		@varKSPAYS_EMPL


	INSERT INTO #TMP2(REAL_REC) VALUES(0)
	INSERT INTO #TMP2(REAL_REC) VALUES(0)
	INSERT INTO #TMP2(REAL_REC) VALUES(0)
	INSERT INTO #TMP2(REAL_REC) VALUES(0)
	INSERT INTO #TMP2(REAL_REC) VALUES(0)
	INSERT INTO #TMP2(REAL_REC) VALUES(0)

	CREATE TABLE #TMP_3 ( ID INT IDENTITY,
		ORD_DATE DATETIME,	ORD_NUM VARCHAR(15),
		VAC_TYPE VARCHAR(254),
		PERIOD_B DATETIME,	PERIOD_E DATETIME,
		VAC_BEG DATETIME,	VAC_END DATETIME,
		DAYS VARCHAR(254),
		REAL_REC BIT
		)

	INSERT INTO #TMP_3
	(
		ORD_DATE, ORD_NUM, 
		VAC_TYPE,
		PERIOD_B, PERIOD_E,
		VAC_BEG, VAC_END,
		DAYS, REAL_REC
	)
	SELECT 
		DATE, NUMBER,
		TYPE_NAME,
		PERIOD_BEGIN, PERIOD_END,
		DATE_BEGIN, DATE_END,
		dbo.W_DAYS(7, DATE_BEGIN,DATE_END),
		1
	FROM VACATION
	WHERE
		EMPL_LINK = @varKSnLinkEmpl
		AND YEAR([DATE_BEGIN]) = @varKSnYear



	
	CREATE TABLE #TMP_DED (
		ID INT IDENTITY, 
		DOC_NAME VARCHAR(254), DOC_NUM VARCHAR(50), DOC_DST VARCHAR(254), DOC_ADR VARCHAR(254), 
		link_tax int, NAME_TAX VARCHAR(254), DATE1 DATETIME, DATE2 DATETIME, 
		SUMMA_PROC NUMERIC(20,2), SUMMA NUMERIC(20, 2), REAL_REC BIT )

	INSERT INTO #TMP_DED (DOC_NAME, DOC_NUM, DOC_DST, DOC_ADR, link_tax, NAME_TAX, DATE1, DATE2, SUMMA_PROC, SUMMA, REAL_REC)
	SELECT 
		DOC_NAME, 
		DOC_NUM = '№ ' + DOC_NUM + ' от ' + CONVERT(VARCHAR(10),DOC_DATE,104),
		DOC_DST = D.NAME,
		DOC_ADR = 
			LEFT(
				(
				LEFT(ISNULL(dbo.GetAddressByKladr(D.KLADR_LINK), ''), 254) + 
				CASE WHEN LEN(ISNULL(HOUSE, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(HOUSE)) END 
				--+ CASE WHEN LEN(ISNULL(CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(CORP_REAL)) END 
				+ CASE WHEN LEN(ISNULL(FLAT, '')) = 0 THEN '' ELSE ', оф. ' + LTRIM(RTRIM(FLAT)) END
				--Расчётный счёт		
				+ ISNULL(
					CASE WHEN DA.CODE IS NOT NULL THEN DA.CODE
						ELSE (SELECT TOP 1 DA1.CODE FROM dbo.DEPARTMENT_ACCOUNTS DA1 WHERE DA1.[TYPE] = 1 AND DA1.LINK_UP = ET.LINK_DEST)
					END, '')
			),254),	
		
		link_tax, NAME_TAX, DATE1, DATE2, SUMMA, SUMMA, 1
	FROM 
		dbo.SD_EMPL_TAX ET
		LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = ET.LINK_DEST
		LEFT JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = D.MAIN_LINK
	WHERE 
		ET.LINK_EMPL = @varKSnLinkEmpl
		AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date)
		AND (DATE1 <= @varKSEND_DATE)

	DECLARE @varKSTMP_INT INT, 
		@varKSCOUNT_2 INT, @varKSCOUNT_3 INT, @varKSCOUNT_4 INT, @varKSCOUNT_MAX INT, @varKSDELTA INT
	SET @varKSCOUNT_2 = (SELECT COUNT(*) FROM #TMP_3)
	SET @varKSCOUNT_MAX = @varKSCOUNT_2
	SET @varKSCOUNT_3 = (SELECT COUNT(*) FROM #TMP_DED)
	IF @varKSCOUNT_MAX < @varKSCOUNT_3 SET @varKSCOUNT_MAX = @varKSCOUNT_3
	IF @varKSCOUNT_MAX =0 SET @varKSCOUNT_MAX = 1
	SET @varKSDELTA = @varKSCOUNT_MAX - @varKSCOUNT_2
	SET @varKSTMP_INT = 1
	WHILE @varKSTMP_INT <= @varKSDELTA BEGIN
		INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		SET @varKSTMP_INT=@varKSTMP_INT+1
	END

	SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_3
	SET @varKSTMP_INT=1
	WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
		INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
		SET @varKSTMP_INT=@varKSTMP_INT+1
	END


	INSERT INTO #TMP_3(REAL_REC) VALUES(0)
	INSERT INTO #TMP_3(REAL_REC) VALUES(0)
	INSERT INTO #TMP_3(REAL_REC) VALUES(0)
	INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
	INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
	INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
	

	CREATE TABLE #PART2 (mode int, NAME_STR VARCHAR(254), code varchar(10),
		SM01 NUMERIC(20,2), SM02 NUMERIC(20,2), SM03 NUMERIC(20,2), 
		SM04 NUMERIC(20,2), SM05 NUMERIC(20,2), SM06 NUMERIC(20,2), 
		SM07 NUMERIC(20,2), SM08 NUMERIC(20,2), SM09 NUMERIC(20,2), 
		SM10 NUMERIC(20,2), SM11 NUMERIC(20,2), SM12 NUMERIC(20,2)
	)


	
	insert into #PART2 
	select 1, 'отработано дней', '',
		max(case when month_begin = 1 then days else 0 end),
		max(case when month_begin = 2 then days else 0 end),
		max(case when month_begin = 3 then days else 0 end),
		max(case when month_begin = 4 then days else 0 end),
		max(case when month_begin = 5 then days else 0 end),
		max(case when month_begin = 6 then days else 0 end),
		max(case when month_begin = 7 then days else 0 end),
		max(case when month_begin = 8 then days else 0 end),
		max(case when month_begin = 9 then days else 0 end),
		max(case when month_begin = 10 then days else 0 end),
		max(case when month_begin = 11 then days else 0 end),
		max(case when month_begin = 12 then days else 0 end)
	from s_j_c 
	where  
		link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
		and typ_oper = 1 and (way_calc = 1 or way_calc = 2)

	insert into #PART2 
	select 2, 'всего начислено', '',
		sum(case when month_begin = 1 then summa else 0 end),
		sum(case when month_begin = 2 then summa else 0 end),
		sum(case when month_begin = 3 then summa else 0 end),
		sum(case when month_begin = 4 then summa else 0 end),
		sum(case when month_begin = 5 then summa else 0 end),
		sum(case when month_begin = 6 then summa else 0 end),
		sum(case when month_begin = 7 then summa else 0 end),
		sum(case when month_begin = 8 then summa else 0 end),
		sum(case when month_begin = 9 then summa else 0 end),
		sum(case when month_begin = 10 then summa else 0 end),
		sum(case when month_begin = 11 then summa else 0 end),
		sum(case when month_begin = 12 then summa else 0 end)
	from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
		and typ_oper = 1


	
	insert into #PART2 
	select 4, 'всего удержано', '',
		sum(case when month_begin = 1 then summa else 0 end),
		sum(case when month_begin = 2 then summa else 0 end),
		sum(case when month_begin = 3 then summa else 0 end),
		sum(case when month_begin = 4 then summa else 0 end),
		sum(case when month_begin = 5 then summa else 0 end),
		sum(case when month_begin = 6 then summa else 0 end),
		sum(case when month_begin = 7 then summa else 0 end),
		sum(case when month_begin = 8 then summa else 0 end),
		sum(case when month_begin = 9 then summa else 0 end),
		sum(case when month_begin = 10 then summa else 0 end),
		sum(case when month_begin = 11 then summa else 0 end),
		sum(case when month_begin = 12 then summa else 0 end)
	from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
		and typ_oper = 2 
		and link_doc not in (
			select link from documents_ded_pr 
			where year_base = @varKSnYear

				and flag_jc = 1
				and TYP_PAYMENT = 1
		)



-----Начисленные суммы
	CREATE TABLE #SJ (typ_oper TINYINT , month_begin TINYINT, LINK_PAYS INT, NAME_PAYS VARCHAR(254), CODE_PAYS  varchar(10), SUMMA NUMERIC(18,2))
	INSERT INTO #SJ (typ_oper, month_begin, LINK_PAYS, NAME_PAYS, CODE_PAYS, SUMMA)
	SELECT P.[OBJECT], MONTH(J.PERIOD_BEGIN), ISNULL(P1.LINK,P.LINK), ISNULL(P1.NAME,P.NAME), ISNULL(P1.CODE,P.CODE), SUMMA
	from 
		dbo.CALCULATE_JURNAL J
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
	where 
		link_empl = @varKSnLinkEmpl 
		and YEAR(J.PERIOD_BEGIN) = @varKSnYear
		and P.[OBJECT] in(1, 2)
		and link_doc not in (
			select link from documents_ded_pr 
			where year_base = @varKSnYear
				and flag_jc = 1
				and TYP_PAYMENT = 1
		)
	--
	UPDATE R
	SET NAME_PAYS = NAME_PAYS + '*', CODE_PAYS = CODE_PAYS + '*'
	FROM
		#SJ R
		INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAYS
	--	
	insert into #PART2 
	select 
		case when typ_oper = 1 then 3 else 5 end, 
		name_pays, code_pays,
		sum(case when month_begin = 1 then summa else 0 end),
		sum(case when month_begin = 2 then summa else 0 end),
		sum(case when month_begin = 3 then summa else 0 end),
		sum(case when month_begin = 4 then summa else 0 end),
		sum(case when month_begin = 5 then summa else 0 end),
		sum(case when month_begin = 6 then summa else 0 end),
		sum(case when month_begin = 7 then summa else 0 end),
		sum(case when month_begin = 8 then summa else 0 end),
		sum(case when month_begin = 9 then summa else 0 end),
		sum(case when month_begin = 10 then summa else 0 end),
		sum(case when month_begin = 11 then summa else 0 end),
		sum(case when month_begin = 12 then summa else 0 end)
	from #SJ
	group by 
		case when typ_oper = 1 then 3 else 5 end, 
		name_pays, code_pays


	insert into #PART2 
	select 6, 'сумма к выдаче', '',
		sum(case when month_base = 1 then d1.summa else 0.00 end),
		sum(case when month_base = 2 then d1.summa else 0.00 end),
		sum(case when month_base = 3 then d1.summa else 0.00 end),
		sum(case when month_base = 4 then d1.summa else 0.00 end),
		sum(case when month_base = 5 then d1.summa else 0.00 end),
		sum(case when month_base = 6 then d1.summa else 0.00 end),
		sum(case when month_base = 7 then d1.summa else 0.00 end),
		sum(case when month_base = 8 then d1.summa else 0.00 end),
		sum(case when month_base = 9 then d1.summa else 0.00 end),
		sum(case when month_base = 10 then d1.summa else 0.00 end),
		sum(case when month_base = 11 then d1.summa else 0.00 end),
		sum(case when month_base = 12 then d1.summa else 0.00 end)
	from documents_ded_pr d inner join DOCUMENTS_DED_PR_TABLE d1
		on (d.link = d1.link and d1.REF_Empl = @varKSnLinkEmpl 
			and year_base = @varKSnYear
			and flag_jc = 1
			and TYP_PAYMENT = 1)




	SELECT *,
		@varKSCODE_FKR_D AS CODE_FKR_D, @varKSNAME_FKR_D AS NAME_FKR_D,
		@varKSCODE_FKR_T AS CODE_FKR_T, @varKSNAME_FKR_T AS NAME_FKR_T,
		@varKSCODE_FKR_E AS CODE_FKR_E, @varKSNAME_FKR_E AS NAME_FKR_E
	FROM #PART1

	EXEC ('
		SELECT * 
		INTO ' + @varKSTMP2 + ' 
		FROM #TMP2 T2 LEFT OUTER JOIN ' + @varKSPAYS_EMPL + ' PE
		ON T2.ID = PE.PARENT_ID
	')	
 
	DECLARE @varKSCNT_PAYS INT, @varKSFIELD_NAME VARCHAR(254), @varKSSQL_STR VARCHAR(8000), @varKSI INT
	SELECT @varKSCNT_PAYS = COUNT(DISTINCT CP) FROM #PAYS_EMPL
	SET @varKSI=1
	WHILE @varKSI <= @varKSCNT_PAYS BEGIN
		SET @varKSFIELD_NAME = 'CP_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' WHERE '+
			@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'NP_'  +  RTRIM(LTRIM(STR(@varKSI)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' WHERE '+
			@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'S_'  +  RTRIM(LTRIM(STR(@varKSI)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE '+@varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = 0  WHERE ' +
			@varKSFIELD_NAME+ '  IS  NULL ' 

		SET @varKSI=@varKSI+1
	END

	IF @varKSCNT_PAYS >= 1 AND @varKSCNT_PAYS < 9  BEGIN
		SET @varKSDELTA = 9 - @varKSCNT_PAYS
		SET @varKSI = 1
		WHILE @varKSI <= @varKSDELTA BEGIN
			SET @varKSSQL_STR= 'ALTER TABLE '  + @varKSTMP2 + 
			'  ADD CP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  VARCHAR(10), 
			NP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + ' VARCHAR(254), 
			S_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  NUMERIC(20,2) '
			EXEC (@varKSSQL_STR)
			SET @varKSI=@varKSI+1
		END
	END

	IF @varKSCNT_PAYS = 0 BEGIN
		SET @varKSSQL_STR= 
			'ALTER TABLE '  + @varKSTMP2 + 
			'  ADD CP_0  VARCHAR(10), 
			NP_0_0 VARCHAR(254), 
			S_0_0  NUMERIC(20,2) '
			EXEC (@varKSSQL_STR)
	END


	EXEC( 'SELECT *, ITOGOZP = NULL 
	FROM ' + @varKSTMP2 + ' ORDER  by ID, REAL_REC DESC, ORDER_DATE ASC')
/*
	EXEC( 'SELECT *, ITOGOZP = (SELECT SUM(S) FROM #PAYS_EMPL WHERE ORDER_DATE BETWEEN DATE_BEGIN AND COALESCE(DATE_END,''29990101'')) 
	FROM ' + @varKSTMP2 + ' ORDER BY REAL_REC DESC, ORDER_DATE ASC')
*/
	SELECT * 
	FROM #TMP_3 INNER JOIN #TMP_DED ON #TMP_3.ID = #TMP_DED.ID
	ORDER BY #TMP_3.REAL_REC DESC, ORD_DATE

	select * from #part2
	order by mode, code


	EXEC ('DROP TABLE ' + @varKSPAYS_EMPL )
	EXEC ('DROP TABLE ' + @varKSTMP2 )

END



GO


GRANT EXECUTE ON dbo.[SD_REP_F417] 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_IMPORT_WITH_DICT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_IMPORT_WITH_DICT]
GO

/*******************************************************************************
	c Кейсистемс (Keysystems), 2006
	Для импорта динамических таблиц: загрузка некоторых столбцов из справочников, 
	например, для 428 формы загрузка столбца "Наименование показателя".
	Вызывается из процедуры RA_IMPORT_REPORT_STANDART, есть доступ к таблице:
	#t_Result(TXT varchar(1000), error bit)

	06.10.2009 :
	не только импорт, но из сохранения и расчета итогов

*******************************************************************************/
CREATE       procedure dbo.RO_IMPORT_WITH_DICT
	@LSF int, -- линк сохраненного отчета
	@OrderTable tinyint ,-- порядковый номер таблицы
	@cTMP_Table varchar(10)='', -- '#' данные записываем #REPORT_DINAMICS
	@varKSiMode	tinyint = 0, -- 0 - импорт, 1 - сохранение
	@varKSiCheck tinyint = 1 -- 0 - не проверять на наличие в справочнике, 1 - проверять

AS

declare @LF int, @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
	@ExecStr varchar(8000), @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @option_import_report int, @LinkColDict INT, @CodeSpr VARCHAR(50), 
   @cStr VARCHAR(254), @LinkSpr INT, @AddCode VARCHAR(50), @DictUser VARCHAR(50), @NameSpr VARCHAR(254),@cSplit VARCHAR(1000), @PartCode VARCHAR(100), @DictName VARCHAR(1000),
   @DictWhere VARCHAR(2000), @link_org INT, @link_budg INT, @vcDate VARCHAR(10), @dBeginDate DATETIME  

DECLARE @vcFORM_CODE VARCHAR(50)
--перенос формы из архивной базы
exec RN_MOVE_FORM_FROM_ARH @LSF

DECLARE @t_Dict TABLE (Link_Spr INT, Part_Code VARCHAR(1000), [Code] VARCHAR(500))

-- добавлена настройка для импорта динамических таблиц:
-- 1 - не принимать коды, отсутствующие в справочнике
-- 2 - принимать коды, отсутствующие в справочнике
-- 3 - игнорировать администратора
if object_id('tempdb..#t_Result') is NOT NULL -- на само деле импорт
begin
	select @option_import_report = IMPORT_REPORT from dbo.i_report_options_common
end
else begin
	set @option_import_report = 1
end
--

select @LF = Link_Form, @dBeginDate = dateadd(month, -1, begin_date + 1 )
from report_saved_forms where Link_Saved_Form = @LSF

SELECT @vcFORM_CODE = [CODE] 
 FROM dbo.[REPORT_FORMS]
 WHERE [LINK_FORM]=@LF

IF (@vcFORM_CODE) IN ('0503317G_C','0503169G_БД','0503169G_БК','0503169G_ВБД','0503169G_ВБК','0503369G_БД','0503369G_БК','0503369G_ВБД','0503369G_ВБК')
BEGIN
	set @option_import_report = 2
END

if @LF is NULL
begin
	return -1
end

select @LC = Link_Code_Col, @LT = Link_Table from report_tables where orders = @OrderTable and Link_Form = @LF

if @LC is NULL
begin
	return -2
END

SELECT @link_org = rsf.[Link_Organization], @link_budg = ISNULL(rsf.[Link_Type_Svod], 0),
      @vcDate = CONVERT(VARCHAR(10), rsf.[Begin_Date], 112)
FROM dbo.[REPORT_SAVED_FORMS] rsf
WHERE rsf.[Link_Saved_Form] = @LSF

declare @t_col_dict table (link_col int)
insert @t_col_dict
select link_col from report_coloumns where rtrim(isnull(dictionary,''))<>'' and isnull(property,0)&4 = 4 --and isnull(property,0)&1= case when @code_form='(72н)0503317M' then isnull(property,0)&1 else 0 end
     and link_table=@lt

-- если указано, что нужно проверять по кодовому стролбцу, то берется только этот справочник
if exists(select * from @t_col_dict where link_col = @LC)
	delete @t_col_dict where link_col <> @LC

if not exists(select top 1 * from @t_col_dict) -- для поддержки старого! чтобы все формы не выгружать
begin
	insert @t_col_dict values (@LC)
end

create table #t_CodeRow (Code varchar(1000))
create table #t_Abcent_CodeRow (Code varchar(1000), Code_Rep varchar(1000), LC int)

IF @vcFORM_CODE = '0503074' 
BEGIN
   IF @cTMP_Table=''
    insert #t_CodeRow
	   select distinct RTRIM(Code_Row) from report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
   ELSE
    insert #t_CodeRow
	   select distinct RTRIM(Code_Row) from #report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF

   INSERT #t_Abcent_CodeRow([CODE])
   SELECT [CODE] FROM #t_CodeRow WHERE [CODE] NOT IN (   
      SELECT [CODE] = RTRIM(LTRIM([A].[SHIFR])) + '#' + [B].[FORMULA]
      FROM (
         SELECT [SHIFR] 
         FROM dbo.[REPORT_FORM14_RAZD] 
      ) [A],   
      (  SELECT [A].[FORMULA]
         FROM dbo.[REPORT_FORMULA] [A]
         JOIN dbo.[REPORT_ROWS]    [B] ON [A].[LINK_ROW] = [B].[LINK_ROW]
         JOIN dbo.[REPORT_TABLES]  [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE] AND
                                          [A].[LINK_COL] = [C].[LINK_CODE_COL]
         WHERE [B].[LINK_TABLE] = @LT AND          
               [C].[ORDERS] = @OrderTable
      ) [B]
   )
END
ELSE BEGIN
   IF @cTMP_Table=''
	insert #t_CodeRow
	   select distinct RTRIM(Code_Row) from report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF
   ELSE
	insert #t_CodeRow
	   select distinct RTRIM(Code_Row) from #report_dinamics RD inner join report_coloumns RC on RC.Link_Table = @LT and RD.Link_Col = RC.Link_Col and Link_SF = @LSF

   --для 317G отдельная штука
	exec RN_FILL_WITH_CODEROW @LSF,@LF,@ORDERTABLE


	while exists(select top 1 * from @t_col_dict)
	begin
		select top 1 @LinkColDict = Link_Col from @t_col_dict
		select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List), @DictWhere = RTRIM(ISNULL([Dictionary_Where], ''))
		  from report_coloumns where Link_Col = @LinkColDict
        
      SET @DictWhere = REPLACE(REPLACE(REPLACE(@DictWhere, '%link_org%', LTRIM(STR(@link_org))), '%link_budg%', LTRIM(STR(@link_budg))), '%date%', '''' + @vcDate + '''')

	   if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
	   begin
			delete @t_col_dict where Link_Col = @LinkColDict
		   continue -- нет подключенных справочников
	   end

	   set @Cols = ''
	   set @Field =''
	   set @Fields = ''
	   set @Col = ''
	   while @DictField <> '' and @DictCol <> ''
	   begin
		   exec dbo.RO_FORMULA_FUNCTIONS 1, @DictField output, @Field output, ','
		   exec dbo.RO_FORMULA_FUNCTIONS 1, @DictCol output, @Col output, ','
		   set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
		   if @i = @OrderCol
		   begin
			   set @CodeCol = @Col -- ключевой столбец
			   set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
		   end
		   else begin
			   set @Fields = @Fields + @Field + ','
			   set @Cols = @Cols + @Col + ','
		   end
	   end

	 /*  if @Fields = '' or @Cols = ''
	   begin
		   return 0 -- нет полей, кроме ключевого столбца
	   end*/
		
		if @Fields <> '' or @Cols <> ''
	   begin
			set @Fields = LEFT(@Fields, LEN(@Fields) - 1)
			set @Cols =  LEFT(@Cols, LEN(@Cols) - 1)
		end

	 -- проверка на наличие в справочнике
		if @LinkColDict = @LC
		begin
		   set @ExecStr = 'insert #t_Abcent_CodeRow (Code)
		   select Code
		   from #t_CodeRow CR
		   where not exists(select * from '+@Dict + ' D where D.' + Ltrim(@FieldCol) + ' = CR.Code ' + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END  + ')'
		end
		else begin
		   set @ExecStr = 'insert #t_Abcent_CodeRow (Code, Code_Rep)
		   select Code_Row, RD.Str_Val
		   from '+@cTMP_Table+'report_dinamics RD 
			where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkColDict) +' and not exists(select * from ' + @Dict + ' D where D.' + Ltrim(@FieldCol) + ' = RD.Str_Val' + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END  + ')'
		END
      -- print @ExecStr
		execute(@ExecStr)

	   while @Fields <> '' and @Cols <> ''
	   begin
		   exec dbo.RO_FORMULA_FUNCTIONS 1, @Cols output, @Col output, ','
		   exec dbo.RO_FORMULA_FUNCTIONS 1, @Fields output, @Field output, ','
		   select @LinkCol = Link_Col from report_coloumns where Link_Table = @LT and orders = convert(int, REPLACE(@Col, 'COL', ''))
/*		   if @option_import_report <> 3 or (select top 1 len(Code) from #t_CodeRow) <> 20
		   begin*/
				if @LinkColDict = @LC -- кодовый столбец
				begin
				   set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val) 
				   select ' + STR(@LSF) + ', ' + STR(@LinkCol) + ', CR.Code, 0, isnull(max(D.' + @Field + '),'''')
				   from #t_CodeRow CR inner join ' + @Dict + ' D on CR.Code = D.' + @FieldCol + '
				   where not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  CR.Code)' + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END  + '
				   group by CR.Code'

				   set @ExecStr =  @ExecStr +' update  '+@cTMP_Table+'report_dinamics set Str_Val= isnull(D.' + @Field + ','''')
				   from '+@cTMP_Table+'report_dinamics CR inner join ' + @Dict + ' D on CR.Code_row = D.' + @FieldCol + '
				   where CR.link_SF=' + STR(@LSF) + ' and Link_col=' + STR(@LinkCol)+ ' and str_val<>D.' + @Field + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END 
				end 
				else begin
				   set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val) 
				   select ' + STR(@LSF) + ', ' + STR(@LinkCol) + ', CR.Code_Row, 0, isnull(max(D.' + @Field + '), '''')
				   from (select Str_Val as Code, Code_Row from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkColDict) +') CR inner join ' + @Dict + ' D on CR.Code = D.' + @FieldCol +  CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END  + '
				   where not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row = CR.Code_Row)
				   group by CR.Code_Row'

				   set @ExecStr =  @ExecStr +' update  '+@cTMP_Table+'report_dinamics set Str_Val= isnull(D.' + @Field + ','''')
				   from '+@cTMP_Table+'report_dinamics CR inner join (select Str_Val as Code, Code_Row from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkColDict) +') CR1 on CR. Code_Row = CR1.Code_Row inner join ' + @Dict + ' D on CR1.Code = D.' + @FieldCol  + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END  + '
				   where CR.link_SF=' + STR(@LSF) + ' and Link_col=' + STR(@LinkCol)+ ' and str_val<>D.' + @Field
				end

/*		   end
		   else begin -- игнорировать администратора
					   set @ExecStr = 'insert '+@cTMP_Table+'report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val) 
			   select ' + STR(@LSF) + ', ' + STR(@LinkCol) + ', CR.Code, 0, max(D.' + @Field + ')
			   from #t_CodeRow CR inner join ' + @Dict + ' D on RIGHT(CR.Code,ABS(LEN(CR.Code)-3)) = RIGHT(D.' + @FieldCol + ',ABS(LEN(D.' + @FieldCol + ')-3))
			   where not exists(select * from '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Link_Col = ' + STR(@LinkCol) + ' and Code_Row =  CR.Code)
			   group by CR.Code'


			   set @ExecStr =  @ExecStr +' update  '+@cTMP_Table+'report_dinamics set Str_Val= D.' + @Field + '
			   from '+@cTMP_Table+'report_dinamics CR inner join ' + @Dict + ' D on RIGHT(RTRIM(CR.Code_row),ABS(LEN(RTRIM(CR.Code_row))-3)) = RIGHT(D.' + @FieldCol + ',ABS(LEN(D.' + @FieldCol + ')-3))
			   where CR.link_SF=' + STR(@LSF) + 'and Link_col=' + STR(@LinkCol)+ ' and str_val='''''

		   end*/
			-- print @ExecStr
			execute(@ExecStr)
	   end -- while
		delete @t_col_dict where Link_Col = @LinkColDict
	end --while
END -- else

if object_id('tempdb..#t_Result') is NOT NULL
begin
	if @option_import_report <> 2
	begin    
		set @ExecStr = 'delete '+@cTMP_Table+'report_dinamics where Link_SF = ' + STR(@LSF) + ' and Code_Row in (select Code from #t_Abcent_CodeRow) and Link_Col in (select Link_Col from report_coloumns where Link_Table = ' + STR(@LT) + ')'

		execute(@ExecStr)

      set @ExecStr = 'insert #t_Result (TXT, error)
      select distinct ''ОШИБКА СОХРАНЕНИЯ: таблица ' + LTRIM(STR(@OrderTable)) + ', код строки '' + Code + '': нет значения '' + ltrim(isnull(Code_Rep,'''')) + '' в справочнике'' + CHAR(13), 1
   	from #t_Abcent_CodeRow CR'
 	-- print @ExecStr
   	execute(@ExecStr)
   END
   
   SELECT @cStr = ' (Форма ' +  RTRIM(RF.[Code]) + ' Версия ' + CONVERT(VARCHAR(10),rf.[Start_Date],104) + ')', @Dict = rc.[Dictionary], @cSplit = dbo.rn_get_formula_code_row_f (@LT, 'SPLIT=')
   FROM dbo.[REPORT_COLOUMNS] rc JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table]
        JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
    WHERE rc.[Link_Col] = @LC

   INSERT @t_Dict ([Link_Spr], [Part_Code], [Code])
   SELECT rs.[Link],  REPLACE(SUBSTRING(@cSplit, CHARINDEX('=', @cSplit, CHARINDEX('COL' + RTRIM(LTRIM(STR(rc.[Orders]))) + '=', @cSplit)) + 1, 
         abs(case when CHARINDEX('#', @cSplit, CHARINDEX('COL' + RTRIM(LTRIM(STR(rc.[Orders]))) + '=', @cSplit)) = 0 then LEN(@cSplit) + 1 else CHARINDEX('#', @cSplit, CHARINDEX('COL' + RTRIM(LTRIM(STR(rc.[Orders]))) + '=', @cSplit)) END  - 
         CHARINDEX('=', @cSplit, CHARINDEX('COL' + RTRIM(LTRIM(STR(rc.[Orders]))) + '=', @cSplit)) -1 )), 'Code_Row', 'Code'), [Code]
   FROM dbo.[REPORT_COLOUMNS] rc 
   JOIN dbo.[REPORT_SPR] rs ON rc.[Link_Table] = @LT AND @cSplit LIKE '%COL' + RTRIM(LTRIM(STR(rc.[Orders]))) + '=%'
        AND rc.[Dictionary] = rs.[Code]
   WHERE rs.Code <> @Dict -- не равно справочнику кодового столбца (т.к. в кодовом столбце содержится больше информации)
      
   IF @@ROWCOUNT  = 0
      INSERT @t_Dict ([Link_Spr], [Part_Code], [Code])
      SELECT [Link], 'Code', [Code]
      FROM dbo.report_spr WHERE [Code] = @Dict

  INSERT @t_Dict ([Link_Spr], [Part_Code], [Code])
  SELECT rs2.[Link], D.[Part_Code], rs.Code
  FROM @t_Dict D
         JOIN dbo.report_spr rs ON D.[Link_Spr] = rs.[Link]
         JOIN dbo.[REPORT_SPR_DATA] rsd ON rsd.[Link_Spr] = rs.[Link]
         JOIN dbo.[REPORT_SPR] rs2 ON rs2.[Code] = rsd.[Table_From]

   WHILE EXISTS(SELECT * FROM @t_Dict)
   BEGIN
      SELECT TOP 1  @LinkSpr = [Link_Spr], @PartCode = [Part_Code], @CodeSpr = Code FROM @t_Dict
      DELETE @t_Dict WHERE [Link_Spr] = @LinkSpr
      
      IF NOT EXISTS(SELECT * FROM dbo.[REPORT_SPR_DATA] rsd WHERE rsd.[Link_Spr] = @LinkSpr) 
      BEGIN
         -- справочник не наследуемый
         SELECT @Dict = rs.[Code], @NameSpr = RTRIM(rs.[Name])  
         FROM dbo.[REPORT_SPR] rs 
         WHERE rs.[Link] = @LinkSpr 
         
         SET @AddCode = NULL
         SELECT @AddCode = CASE WHEN rsc.[First] = 0 THEN '' ELSE REPLACE(SPACE(rsc.[First] - 1), ' ', '0') END 
           FROM dbo.[REPORT_SPR_COL] rsc WHERE rsc.[Source] = 'Code' AND rsc.[Link_Spr] = @LinkSpr

         IF @AddCode IS NOT NULL 
         BEGIN
            SELECT @DictName = ISNULL(RTRIM(rk3.Name) + '\', '') + ISNULL(RTRIM(rk2.Name) + '\', '') + ISNULL(RTRIM(rk.Name), '') 
            FROM dbo.[REPORT_KBK] rk 
                  LEFT JOIN dbo.[REPORT_KBK] rk2 ON rk.[Link_self] = rk2.[link]
                  LEFT JOIN dbo.[REPORT_KBK] rk3 ON rk2.[Link_self] = rk3.[Link]
            WHERE  rk.Code = @Dict AND rk.Code_Form = 'HEADER'
             
           
            set @ExecStr = 'if exists(select * FROM #t_Abcent_CodeRow A '
                        + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code')  + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END +  ') '
                         + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @Dict + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ')) '
                         + 'begin '
                         + 'insert #t_Result (TXT, error) values(CHAR(13) + CHAR(10) + ''В буфер импорта занесены следующие коды: '', 1) '
                         + 'insert #t_Result (TXT, error) '
                        + 'SELECT CHAR(13) + CHAR(10) + ''' + @AddCode + ''' + ' + @PartCode + ' , 1 ' 
                        + 'FROM #t_Abcent_CodeRow A '
                        + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END + ') '
                         + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @Dict + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ') '
                         + 'end'                         

      	execute(@ExecStr)
                  
            SET @ExecStr = 'INSERT dbo.report_kbk(Code, [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [add_info], [Long_Name], begin_date)  ' 
                        + 'SELECT ''' + @AddCode + ''' + ' + @PartCode + ', 0, ''BUFFER_IMPORT'', 0, ''' + @NameSpr + @cStr + ''', 0, ''' + @Dict + ''', CONVERT(VARCHAR(30), GETDATE(), 113), ''' + @DictName + ''',''' + CONVERT(VARCHAR(10), @dBegindate, 112) + '''' 
                        + 'FROM #t_Abcent_CodeRow A '
                        + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code')  + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END + ') '
                         + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @Dict + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ') '
            -- print @ExecStr                         
            EXECUTE (@ExecStr)
         END
      END 
      ELSE BEGIN
         SET @DictUser = NULL
                                
         SELECT top 1 @DictUser = kbk.Code,  @cStr = RTRIM(KBK.[Name]) + @cStr 
         FROM dbo.[REPORT_SPR_DATA] rsd JOIN dbo.report_kbk KBK on rsd.[Link_Spr] = @LinkSpr AND rsd.[Filter] LIKE '%USER%' AND rsd.[Filter] like '%''' + RTRIM(KBK.Code) + '''%' AND KBK.[Code_Form] = 'HEADER' AND KBK.Code LIKE '%USER%'
        
         IF @DictUser IS NOT NULL 
          -- значит наследуемый справочник, в котором есть место пользовательскому справочнику
         BEGIN
            SET @AddCode = NULL
            SELECT @AddCode = CASE WHEN rsc.[First] = 0 THEN '' ELSE REPLACE(SPACE(rsc.[First] - 1), ' ', '0') END 
              FROM dbo.[REPORT_SPR_COL] rsc WHERE rsc.[Source] like '%Code' AND rsc.[Link_Spr] = @LinkSpr
              
            IF @DictUser LIKE 'ИСТОЧНИКИ%' AND @AddCode <> ''
            BEGIN 
               SET @AddCode = ''
               SET @PartCode = 'LEFT(CODE,3) + ''000'' + SUBSTRING(CODE,4,17)'
            END
            
            IF @AddCode IS NOT NULL 
            BEGIN 
               SELECT @DictName = ISNULL(RTRIM(rk3.Name) + '\', '') + ISNULL(RTRIM(rk2.Name) + '\', '') + ISNULL(RTRIM(rk.Name), '') 
               FROM dbo.[REPORT_KBK] rk 
                     LEFT JOIN dbo.[REPORT_KBK] rk2 ON rk.[Link_self] = rk2.[link]
                     LEFT JOIN dbo.[REPORT_KBK] rk3 ON rk2.[Link_self] = rk3.[Link]
               WHERE  rk.Code = @DictUser AND rk.Code_Form = 'HEADER'

               set @ExecStr = 'if exists(select * FROM #t_Abcent_CodeRow A '
                           + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code')  + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END +  ') '
                           + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @DictUser + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ')) '
                            + 'begin '
                            + 'insert #t_Result (TXT, error) values(CHAR(13) + CHAR(10) + ''В буфер импорта занесены следующие коды: '', 1) '
                            + 'insert #t_Result (TXT, error) '
                           + 'SELECT distinct CHAR(13) + CHAR(10) + ''' + @AddCode + ''' + ' + @PartCode + ', 1 ' 
                           + 'FROM #t_Abcent_CodeRow A '
                           + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END + ') '
                           + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @DictUser + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ') '
                            + 'end'                         

      	      execute(@ExecStr)
               
               SET @ExecStr = 'INSERT dbo.report_kbk(Code, [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [add_info], [Long_Name], begin_date) ' 
                           + 'SELECT distinct ''' + @AddCode + ''' + ' + @PartCode + ', 0, ''BUFFER_IMPORT'', 0, ''' + @cStr + ''', 0, ''' + @DictUser + ''', CONVERT(VARCHAR(30), GETDATE(), 113), ''' + @DictName + ''',''' + CONVERT(VARCHAR(10), @dBegindate, 112) + ''''
                           + 'FROM #t_Abcent_CodeRow A '
                           + 'where not exists(select * from ' + @CodeSpr + ' where code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END + ') '
                           + 'and not exists(select * from dbo.report_kbk where code_form = ''BUFFER_IMPORT''  and code_str = ''' + @DictUser + ''' and code = ''' + @AddCode + ''' + ' + REPLACE(@PartCode, 'Code', 'A.Code') + ') '
               -- print @ExecStr
               EXECUTE (@ExecStr)
            END
         END
      END          
   END

end

drop table #t_CodeRow
drop table #t_Abcent_CodeRow



GO
GRANT ALL ON dbo.[RO_IMPORT_WITH_DICT] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_EGRL]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_EGRL]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- Процедура импорта из ЕГРЮЛ
-- Вход: таблица    create table #IMPORT_EGRL(PP varchar(100), INN  varchar(100), KPP varchar(100), OGRN varchar(100), FullName varchar(1000),
--    Name varchar(1000), OKOPF varchar(100), NameOKOPF varchar(1000), DateCreate varchar(100), UOKOPF varchar(100), UFullName varchar(1000),
--    UOGRN varchar(100), UINN varchar(100), UKPP varchar(100), UOKATO varchar(100), UIndex varchar(100), UCODEKLADR varchar(100), UNameSub varchar(1000),
--    UCODEKLADRR varchar(100),UNameR varchar(1000),UCODEKLADRG varchar(100), UNameG varchar(1000),UCODEKLADRNP varchar(100), UNameNP varchar(1000),
--    UCODEKLADRU varchar(100),UNameU varchar(1000),UDom varchar(100),UKorp varchar(100),UKvart varchar(100),AOKATO varchar(100), AINDEX varchar(100), ACODEKLADR varchar(100),
--    ANameSub varchar(1000), ACODEKLADRR varchar(100), ANameR varchar(1000), ACODEKLADRG varchar(100), ANameG varchar(1000), ACODEKLADRNP varchar(100),
--    ANameNP varchar(1000), ACODEKLADRU varchar(100), ANameU varchar(1000), Dom varchar(100), Korp varchar(100), Kvart varchar(100), KodTel varchar(100), 
--    Tel varchar(100), RukF varchar(100), RukI varchar(100), RukO varchar(100), RukD varchar(1000), OKVED varchar(100), OKVEDDOP varchar(100), OBOSNAME VARCHAR(1000),
--    OOKATO varchar(100),OINDEX varchar(100),OCODEKLADR varchar(100),ONameSub varchar(1000),OCODEKLADRR varchar(100),ONameR varchar(1000),OCODEKLADRG varchar(100),
--    ONameG varchar(1000),OCODEKLADRNP varchar(100),ONameNP varchar(1000),OCODEKLADRU varchar(100),ONameU varchar(1000),ODom varchar(100),OKorp varchar(100),
--    OKvart varchar(100),OKodTel varchar(100),OTel varchar(100),ORukF varchar(1000),ORukI varchar(1000),ORukO varchar(1000),ORukD varchar(1000), orders INT IDENTITY(1,1))

CREATE PROCEDURE dbo.[RO_IMPORT_EGRL]
AS

IF OBJECT_ID('tempdb..#IMPORT_EGRL') IS NULL AND OBJECT_ID('tempdb..#IMPORT_EGRL_XML') IS NOT NULL
BEGIN
   create table #IMPORT_EGRL(PP varchar(100), INN  varchar(100), KPP varchar(100), OGRN varchar(100), FullName varchar(1000),
    Name varchar(1000), OKOPF varchar(100), NameOKOPF varchar(1000), DateCreate varchar(100), UOKOPF varchar(100), UFullName varchar(1000),
    UOGRN varchar(100), UINN varchar(100), UKPP varchar(100), UOKATO varchar(100), UIndex varchar(100), UCODEKLADR varchar(100), UNameSub varchar(1000),
    UCODEKLADRR varchar(100),UNameR varchar(1000),UCODEKLADRG varchar(100), UNameG varchar(1000),UCODEKLADRNP varchar(100), UNameNP varchar(1000),
    UCODEKLADRU varchar(100),UNameU varchar(1000),UDom varchar(100),UKorp varchar(100),UKvart varchar(100),AOKATO varchar(100), AINDEX varchar(100), ACODEKLADR varchar(100),
    ANameSub varchar(1000), ACODEKLADRR varchar(100), ANameR varchar(1000), ACODEKLADRG varchar(100), ANameG varchar(1000), ACODEKLADRNP varchar(100),
    ANameNP varchar(1000), ACODEKLADRU varchar(100), ANameU varchar(1000), Dom varchar(100), Korp varchar(100), Kvart varchar(100), KodTel varchar(100), 
    Tel varchar(100), RukF varchar(100), RukI varchar(100), RukO varchar(100), RukD varchar(1000), OKVED varchar(100), OKVEDDOP varchar(100), OBOSNAME VARCHAR(1000),
    OOKATO varchar(100),OINDEX varchar(100),OCODEKLADR varchar(100),ONameSub varchar(1000),OCODEKLADRR varchar(100),ONameR varchar(1000),OCODEKLADRG varchar(100),
    ONameG varchar(1000),OCODEKLADRNP varchar(100),ONameNP varchar(1000),OCODEKLADRU varchar(100),ONameU varchar(1000),ODom varchar(100),OKorp varchar(100),
    OKvart varchar(100),OKodTel varchar(100),OTel varchar(100),ORukF varchar(1000),ORukI varchar(1000),ORukO varchar(1000),ORukD varchar(1000), orders INT IDENTITY(1,1))
   
   EXEC dbo.[RO_IMPORT_EGRL_XML]
END

DECLARE @lf         INT
       ,@dDate      DATETIME
       ,@tPT        TINYINT
       ,@tPN        TINYINT
       ,@INN        VARCHAR(50)
       ,@lsf        INT
       ,@link_org   INT
       ,@link_budg  INT
       ,@lc1        INT
       ,@lc2        INT 
       ,@lc4        INT
       ,@lt1        INT
       ,@lt2        INT
       ,@lr          INT,
       @PP varchar(100), 
       @KPP VARCHAR(100),
       @OGRN VARCHAR(100),
       @FullName VARCHAR(1000), 
       @Code VARCHAR(50),
@NAME VARCHAR(1000),
 @OKOPF VARCHAR(100), 
 @NameOKOPF VARCHAR(1000),
  @DateCreate VARCHAR(100), 
  @UOKOPF VARCHAR(100), 
  @UFullName VARCHAR(1000),
@UOGRN VARCHAR(100), 
@UINN VARCHAR(100), @UKPP VARCHAR(100), @UOKATO VARCHAR(100), @AOKATO VARCHAR(100), 
@AINDEX VARCHAR(100), @ACODEKLADR VARCHAR(100),
@ANameSub VARCHAR(1000), @ACODEKLADRR VARCHAR(100), @ANameR VARCHAR(1000), 
@ACODEKLADRG VARCHAR(100), @ANameG VARCHAR(1000), @ACODEKLADRNP VARCHAR(100),
@ANameNP VARCHAR(1000), @ACODEKLADRU VARCHAR(100), @ANameU VARCHAR(1000), @Dom 
VARCHAR(100), @Korp VARCHAR(100), @Kvart VARCHAR(100), @KodTel VARCHAR(100),
@Tel VARCHAR(100), @RukF VARCHAR(100), @RukI VARCHAR(100), @RukO VARCHAR(100), @RukD 
VARCHAR(1000), @OKVED VARCHAR(100), @OKVEDDOP VARCHAR(100), @i int ,
@cStr VARCHAR(1000), @OBOSNAME VARCHAR(1000), @lc3 INT, @lt3 INT, @lc2_n INT, @lc3_n INT 

create table #t_Protokol (org varchar(1000))

Create index #IX_IMPORT_EGRL on #IMPORT_EGRL (inn)

SET @dDate = '20111231'
SET @tPT = 1
SET @tPN = 1
 
SELECT @lf = link_form FROM dbo.report_forms WHERE code = '(86н)001' AND START_DATE = '20111101'

SELECT @lc1 = rc.link_col,
         @lt1 = rt.link_table
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 1 AND rc.orders = 4

SELECT @lc2 = rc.link_col,
         @lt2 = rt.link_table
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 2 AND rc.orders = 3

SELECT @lc3 = rc.link_col,
         @lt3 = rt.link_table
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 3 AND rc.orders = 3

SELECT @lc2_n = rc.link_col
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 2 AND rc.orders = 4

SELECT @lc3_n = rc.link_col
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 3 AND rc.orders = 4

SELECT @lc4 = rc.link_col
FROM dbo.report_tables RT JOIN dbo.report_coloumns RC ON RT.link_table = RC.[Link_Table] WHERE RT.[Link_Form] = @lf AND rt.orders = 4 AND rc.orders = 4


IF @lf IS NULL
   RETURN -1

DECLARE cur CURSOR LOCAL STATIC FOR 
SELECT DISTINCT inn FROM  #IMPORT_EGRL WHERE isnull(inn, '') <> '' 

OPEN cur

FETCH NEXT FROM cur INTO @INN

WHILE @@fetch_status = 0
BEGIN
   IF EXISTS(SELECT * FROM dbo.report_svod_tree rst JOIN dbo.departments d ON rst.link_org = d.link WHERE d.inn = @inn)
   BEGIN
      SELECT top 1 @link_org = rst.link_org, @link_budg = rst.link_report_budg 
      FROM dbo.report_svod_tree rst 
            JOIN dbo.departments d ON rst.link_org = d.link WHERE d.inn = @inn
            
      INSERT #t_Protokol ([org])
      SELECT top 1 d.name
      FROM dbo.report_svod_tree rst 
            JOIN dbo.departments d ON rst.link_org = d.link WHERE d.inn = @inn
                  
            
      SET @lsf = NULL
      
      SELECT @lsf = link_saved_form 
      FROM dbo.report_saved_forms 
      WHERE link_form = @lf
            AND del = 0
            AND link_organization = @link_org
            AND link_type_svod = @link_budg
            AND [Period_Type] = @tPT
            AND [Period_Number] = @tPN
            AND [Begin_Date] = @dDate
            
      IF @lsf IS NULL -- отчет не найден, значит создаем его
      BEGIN
         EXEC dbo.[I_REPORT_SAVE_FORM] @lsf OUTPUT, @lf, 0, @dDate, @tPT, @tPN, @Link_Org, 0, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, @Link_Budg
         IF @lsf IS NULL
            RETURN -2         
      END
      
      SELECT @FullName = '', 
            @Name = '',
            @OGRN = '',
            @KPP = '',
            @AOKATO = '',
            @OKOPF = '',
            @ANameSub = '',
            @ANameR = '',
            @ANameG = '',
            @ANameNP = '',
            @ANameU = '',
            @Dom = '',
            @Korp = '',
            @Kvart = '',
            @AINDEX = '',
            @Tel = '',
            @RukF = '', 
            @RukI = '',
            @RukO = '',
            @RukD = '',
            @OBOSNAME = '',
            @UINN = ''
      
      SELECT @FullName = FullName, 
            @Name = NAME,
            @OGRN = OGRN,
            @KPP = KPP,
            @AOKATO = AOKATO,
            @OKOPF = RTRIM(OKOPF), 
            @NameOKOPF =  NameOKOPF,
            @ANameSub = RTRIM(ANameSub),
            @ACODEKLADR = ACODEKLADR,
            @ANameR = RTRIM(ANameR),
            @ACODEKLADRR = ACODEKLADRR,
            @ANameG = RTRIM(ANameG),
            @ACODEKLADRG =  ACODEKLADRG,
            @ANameNP = RTRIM(ANameNP),
            @ACODEKLADRNP = ACODEKLADRNP,
            @ANameU = RTRIM(ANameU),
            @ACODEKLADRU = ACODEKLADRU,
            @Dom = Dom,
            @Korp = Korp,
            @Kvart = Kvart,
            @AINDEX = AINDEX,
            @Tel = Tel,
            @KodTel = KodTel,
            @RukF = RukF, 
            @RukI = RukI,
            @RukO = RukO,
            @RukD = RukD,
            @UINN = UINN
      FROM #IMPORT_EGRL WHERE INN = @INN AND FULLName <> ''
      
      SET @Tel = CASE WHEN @KodTel = '' THEN '' ELSE '(' + RTRIM(@KodTel)+ ')' END  + @Tel
      
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '101000', @FullName
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '102000', @Name
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '103000', @INN
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '104000', @KPP
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '105000', @OGRN
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '119000', @AOKATO
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '122000', @OKOPF
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '122001', @NameOKOPF
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124010', @ACODEKLADR
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124011', @ANameSub
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124020', @ACODEKLADRR
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124021', @ANameR
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124030', @ACODEKLADRG
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124031', @ANameG
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124040', @ACODEKLADRNP
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124041', @ANameNP
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124050', @ACODEKLADRU
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124051', @ANameU
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124060', @Dom
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124070', @Kvart
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '124080', @AINDEX
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '126000', @Tel
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '112010', @RukF
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '112020', @RukI
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '112030', @RukO
      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '112040', @RukD
      
      SELECT @UFullName = UFullName 
      FROM #IMPORT_EGRL WHERE INN = @INN AND UFullName <> '' 

      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '107001', @UFullName

      SET @OBOSName = ''
      SELECT @OBOSName = @OBOSName +';' + OBOSName
      FROM #IMPORT_EGRL WHERE INN = @INN AND OBOSName <> '' 

      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '113000', @OBOSNAME

      SET @UINN = ''

      SELECT @UINN = @UINN + UINN + '    ' 
      FROM #IMPORT_EGRL WHERE INN = @INN 

      EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc1, '107000', @UINN
      
      SET @OKVED = ''
      
      SELECT @OKVED = OKVED, @pp = pp
      FROM #IMPORT_EGRL WHERE INN = @INN 

      IF isnull(@OKVED,'') <> '' 
      BEGIN 
         SET @Code = '_              ' + @OKVED
         SET @cStr = ISNULL((SELECT NAME FROM dbo.R_SPR_OKVD WHERE code = @OKVED), '')   
         
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc2, @Code, @OKVED
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc2_n, @Code, @cStr
      END 
      
      SET @OKVED = ''
      
      SELECT @OKVED = OKVED
      FROM #IMPORT_EGRL WHERE INN = @INN AND  @pp <> pp   
      
      IF isnull(@OKVED,'') <> '' 
      BEGIN 
         SET @Code = '_              ' + @OKVED   
         
         SET @cStr = ISNULL((SELECT NAME FROM dbo.R_SPR_OKVD WHERE code = @OKVED), '')   
         
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc2, @Code, @OKVED
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc2_n, @Code, @cStr
      END 
       
      SET @OKVEDDOP = '' 
      SET @pp = ''

      SELECT @OKVEDDOP = OKVEDDOP, @pp = ',' + LTRIM(RTRIM(pp)) + ','  
      FROM #IMPORT_EGRL WHERE INN = @INN      AND OKVEDDOP <> ''
      
      IF isnull(@OKVEDDOP,'') <> ''
      BEGIN       
         SET @Code = '_              ' + @OKVEDDOP
         SET @cStr = ISNULL((SELECT NAME FROM dbo.R_SPR_OKVD WHERE code = @OKVEDDOP), '')       
         
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc3, @Code, @OKVEDDOP
         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc3_n, @Code, @cStr
      END       

      SET @i = 1
      
      WHILE isnull(@OKVEDDOP,'')<> '' AND  EXISTS( SELECT *   FROM #IMPORT_EGRL WHERE INN = @INN   AND charindex( ',' + LTRIM(RTRIM(pp)) + ',', @pp) = 0   AND OKVEDDOP <> '') AND @i < 40
      BEGIN

         SELECT @OKVEDDOP = OKVEDDOP, @pp = @pp + ',' + LTRIM(RTRIM(pp)) + ','  
         FROM #IMPORT_EGRL WHERE INN = @INN    
               AND charindex( ',' + LTRIM(RTRIM(pp) )+ ',', @pp) = 0   AND OKVEDDOP <> ''

         IF isnull(@OKVEDDOP,'')<> ''
         BEGIN                
            SET @cStr = ISNULL((SELECT NAME FROM dbo.R_SPR_OKVD WHERE code = @OKVEDDOP), '')               

            SET @i = @i + 1
            SET @Code = '_              ' + @OKVEDDOP 
            EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc3, @Code, @OKVEDDOP
            EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc3_n, @Code, @cStr               
         END          
      END                

--      SET @OBOSNAME = '' 
--      SET @pp = ''
--
--      SELECT @OBOSNAME = OBOSNAME, @pp = ',' + LTRIM(RTRIM(pp)) + ','  
--      FROM #IMPORT_EGRL WHERE INN = @INN      AND OBOSNAME <> ''
--      
--      IF @OBOSNAME <> ''
--      BEGIN       
--         SET @Code = dbo.RA_GETWORDNUM(@pp,2,',')         
--         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc4, @Code, @OBOSNAME
--      END       
--
--      SET @i = 1
--      
--      WHILE @OBOSNAME<> '' AND  EXISTS( SELECT *   FROM #IMPORT_EGRL WHERE INN = @INN   AND charindex( ',' + LTRIM(RTRIM(pp)) + ',', @pp) = 0   AND OBOSNAME <> '') AND @i < 40
--      BEGIN
--
--         SELECT @OBOSNAME = OBOSNAME, @pp =  ',' + LTRIM(RTRIM(pp)) + ',' + @pp  
--         FROM #IMPORT_EGRL WHERE INN = @INN    
--               AND charindex( ',' + LTRIM(RTRIM(pp) )+ ',', @pp) = 0   AND OBOSNAME <> ''
--               
--         SET @i = @i + 1
--         SET @Code = dbo.RA_GETWORDNUM(@pp,2,',')   
--         EXEC dbo.RO_IMPORT_EGRL_VALUE @lsf, @lc4, @Code, @OBOSNAME
--              
--         
--      END                

   END
   FETCH NEXT FROM cur INTO @INN

END

   SELECT * FROM #t_Protokol
   DROP TABLE   #t_Protokol

RETURN 0
--RETURN dbo.[RA_GET_ERROR](OBJECT_ID('dbo.[RA_IMPORT_FORM_ANALYZE_XML]'))
GO
GRANT ALL ON dbo.[RO_IMPORT_EGRL] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select @@datalength
sp_help RA_IMPORT_FORM_ANALYZE_XML
*/	

GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BI_SAVE_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BI_SAVE_KBK]
GO

CREATE	PROCEDURE dbo.BI_SAVE_KBK
	@varKSparLINK	int	OUTPUT,
	@varKSType	tinyint,
	@varKSparNAME	VARCHAR(250) = '',
	@varKSLink_Adm	int,
	@varKSLink_KD	int = null,
	@varKSLink_IVF	int = null,
	@varKSLink_prog	int = null,
	@varKSLink_Div	int = null,
	@varKSLink_CSR	int = null,
	@varKSLink_Exp	int = null,
	@iKBKL_Link		int = null,
	@iUsed			bit = 1,
	@iUsedAll		bit = 0,
	@iOsn			bit = 0

AS
DECLARE @iRes	int,
		@cDelim char(1),
		@iDepLink int

set @cDelim = '.' -- брать из настройки!!!
set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
--select @varKSparLINK , @varKSparNAME, @varKSLink_Adm, @varKSLink_Div, @varKSLink_Csr, @varKSLink_Exp, @iUsedAll, @cDelim
IF @varKSType = 1
	EXEC @iRes = dbo.BI_SAVE_VKR @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_Div, @varKSLink_Csr, @varKSLink_Exp, @iUsedAll, @cDelim
IF @varKSType = 2
	EXEC @iRes = dbo.BI_SAVE_KBK_KD @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_KD, @varKSLink_prog, @iUsedAll, @cDelim
IF @varKSType = 3
	EXEC @iRes = dbo.BI_SAVE_KBK_IVF @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_IVF, @varKSLink_prog, @iUsedAll, 4,@cDelim
IF @varKSType = 4
	EXEC @iRes = dbo.BI_SAVE_KBK_IVF @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_IVF, @varKSLink_prog, @iUsedAll, 8,@cDelim
if @iRes <> 0
	return @iRes

-- Исправляем неверные коды
	UPDATE KL_KBK
	SET Code = A.Right_Code
--	select *
	FROM KL_KBK K left join 
	    (SELECT Link, 
		[Right_Code] = adm_code + @cDelim 
			+ (case when type=1 then rtrim(div_code) + @cDelim + rtrim(csr_code) + @cDelim + rtrim(exp_code)
				when type=2 then rtrim(KD_code) + PROG_CODE
				when type>2 then rtrim(IVF_code) + PROG_CODE end)
		FROM bi_diction_kbk_full) A on K.link = A.link
	WHERE A.Right_Code <> K.Code

--SELECT @@ROWCOUNT
update dbo.DEPARTMENT_KBK
set OSN = @iOsn 
where KBK_LINK = @varKSparLINK and DEP_LINK = @iDepLink

if @@rowcount = 0 and (@iOsn = 1 or @iUsedAll = 0 and @iUsed = 1)
	insert into dbo.DEPARTMENT_KBK (DEP_LINK,KBK_LINK, OSN)
	values (@iDepLink,@varKSparLINK,@iOsn)



if @iUsedAll = 1 or @iUsed = 0
	delete 
	from dbo.DEPARTMENT_KBK
	where KBK_LINK = @varKSparLINK AND OSN <> 1


if @iKBKL_Link is null
	delete from dbo.KL_KBK_LINKED where LINK = @varKSparLINK
else
begin
	update dbo.KL_KBK_LINKED 
	set LINK_KBK = @iKBKL_Link
	where LINK = @varKSparLINK
	if @@ROWCOUNT = 0
			insert into dbo.KL_KBK_LINKED (LINK, LINK_KBK) values(@varKSparLINK, @iKBKL_Link)
end		
RETURN @iRes


GO

grant all on dbo.BI_SAVE_KBK 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_PRINT_117_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_117_ITOG]
GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать форм 127 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_117_ITOG
	@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(1000), Col2 varchar(1000), Col3 varchar(1000), 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 = '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)
--select * from #doh order by left(code, 3), orders, Code
drop table #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(2000), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 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)
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, Col10)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,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(col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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, Col10)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, '00096000000000000000', 'Расходы - всего', '200','9600', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), '00096000000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
end

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 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, Col10 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))
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 = '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)

--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 ALL ON dbo.[RO_PRINT_117_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_86N_GET_DATA]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_86N_GET_DATA]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011
   
   Вход: @iLINK_SAVED_FORM - ИД отчета
         @tRazdel          - Раздел - 1 - Общая информация об учреждения
         Созданные таблицы:
CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении

Раздел 1:
         
CREATE TABLE #tab001_OKVED (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [NAME] VARCHAR(8000), [NAMEU] VARCHAR(8000)) -- основыне ОКВЕД
CREATE TABLE #tab001_OKVED_ADD (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [NAME] VARCHAR(8000), [NAMEU] VARCHAR(8000)) -- дополнительные ОКВЕД
CREATE TABLE #tab001_BRANCH (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [FULL_NAME] VARCHAR(8000), [NAME] VARCHAR(8000), [TYPE] VARCHAR(50)) -- филиалы и представительства

Раздел 2:

CREATE TABLE #tab002
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT         -- Текущий финансовый год
   ,[nextFinancialYear] INT      -- Очередной финансовый год
   ,[planFirstYear] INT          --Первый год планового периода
   ,[planLastYear] INT           --Второй год планового периода
)
-- Услуги
CREATE TABLE #tab002_SERVICE
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код услуги
   ,[NUM_UTV] VARCHAR(200) -- Номер (код) по утвержденному перечню услуг 
   ,[NUM]   VARCHAR(50)    -- Порядковый номер раздела, соответствующий услуге
   ,[NAME]  VARCHAR(1000)  -- Наименование услуги, указанной в данном разделе
   ,[KAT]   VARCHAR(1000)  -- Категория потребителей (наименование)   
)
-- Показатели качества услуг 
CREATE TABLE #tab002_QUALITY
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя качества услуги за отчетный финансовый год
   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя качества услуги на текущий финансовый год 
   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя качества услуги на очередной финансовый год  
   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя качества услуги на первый год планового периода  
   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя качества услуги на второй год планового периода
   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя качества услуги за текущий финансовый
   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя качества 
)
-- Показатели объема услуги
CREATE TABLE #tab002_VOLUME
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя объема услуги за отчетный финансовый год
   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя объема услуги на текущий финансовый год 
   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя объема услуги на очередной финансовый год  
   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя объема услуги на первый год планового периода  
   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя объема услуги на второй год планового периода
   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя объема услуги за текущий финансовый
   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя объема 
)
-- Возможность взимания платы за услугу
CREATE TABLE #tab002_PRICE
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[SUMMA]   NUMERIC(20,2)   --Средневзвешенная цена за единицу услуги (руб.) 
   ,[NPA_VID]   VARCHAR(8000) --Вид нормативного правового акта 
   ,[NPA_NAME_ORGAN]   VARCHAR(8000) -- Наименование органа, утвердившего нормативный правовой акт 
   ,[NPA_DATE]   VARCHAR(8000)--Дата нормативного правового акта
   ,[NPA_NUM]   VARCHAR(8000) --Номер нормативного правового акта
   ,[NPA_NAME]   VARCHAR(8000)--Наименование нормативного правового акта 
)
-- Сведения о работах   
CREATE TABLE #tab002_WORK
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код работы
   ,[NUM_UTV] VARCHAR(200) -- Номер (код) по утвержденному перечню услуг (работ)
   ,[NUM]   NUMERIC(50)       --Порядковый номер раздела соответствующий работе
   ,[NAME]   VARCHAR(8000)    --Наименование работы, указанной в данном разделе
)

Раздел 3:

CREATE TABLE #tab003
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT         -- Значение на финансовый год, на который утверждается план ФХД
   ,[planFirstYear] INT          --Первый год планового периода
   ,[planLastYear] INT        --Второй год планового периода
)

CREATE TABLE #tab003_FHD
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код показателя
   ,[SUMMA1] NUMERIC(20,2) -- Значение на финансовый год, на который утверждается план ФХД          
   ,[SUMMA2] NUMERIC(20,2) -- Значение показателя на первый год планового периода
   ,[SUMMA3] NUMERIC(20,2) -- Значение показателя на второй год планового периода
)

Раздел 4:

CREATE TABLE #tab004
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT         -- Значение на финансовый год, на который утверждается план ФХД
)
--Целевые средства
CREATE TABLE #tab004_BUDGETARY
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код показателя
   ,[SUMMA] NUMERIC(20,2) -- Значение      
)
--Объекты бюджетных инвестиций 
CREATE TABLE #tab004_CONSTRUCTION
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код
   ,[NAME] NUMERIC(20,2)   -- Наименование объекта  
   ,[KAT]  VARCHAR(50)     -- Код категории объекта 
   ,[SUMMA] NUMERIC(20,2)
)

--Целевые субсидии
CREATE TABLE #tab004_GRANT
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код
   ,[NAME] NUMERIC(20,2)   -- Наименование субсидии
   ,[SUMMA] NUMERIC(20,2)  -- Сумма планируемых поступлений по целевой субсидии (руб)      
)

   Выход: заполненные таблицы

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_86N_GET_DATA]
	@iLINK_SAVED_FORM INT,
   @tRazdel TINYINT 
AS

print @iLINK_SAVED_FORM

DECLARE @vcExec VARCHAR(8000), @lt INT, @lf INT, @vcTmpTable VARCHAR(100), @ID UNIQUEIDENTIFIER,
      @tVersion   TINYINT     



SET @tVersion = 	(select isnull((select top 1 Version
	from report_export_info EI
	where exists(select top 1 * from report_saved_forms RSF where RSF.Link_Saved_Form = @iLINK_SAVED_FORM and RSF.Link_Form = EI.Link_Form and RSF.Link_Organization = EI.Link_Org and isnull(RSF.Link_Type_Svod,0) = isnull(EI.Link_Budg,0) and RSF.Period_Type = EI.Period_Type and RSF.Period_Number = EI.Period_Number and YEAR(RSF.Begin_Date) = EI.Period_Year)),1) as Version)



EXEC dbo.[X_GET_TABLE_NAME] @vcTmpTable OUTPUT

SELECT @lf = link_form FROM dbo.[REPORT_SAVED_FORMS] rsf WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

IF OBJECT_ID('tempdb..#Reports') IS NULL
   CREATE TABLE #Reports (LSF INT)

DECLARE cur cursor LOCAL STATIC FOR
SELECT @iLINK_SAVED_FORM AS LINK_SAVED_FORM
UNION
SELECT rsf.LINK_SAVED_FORM
FROM dbo.[REPORT_SAVED_FORMS] rsf
   JOIN #Reports R ON rsf.[Link_Saved_Form] = R.LSF AND rsf.[Link_Form] = @lf
   
OPEN cur

FETCH NEXT FROM cur INTO @iLINK_SAVED_FORM
 
WHILE @@FETCH_STATUS = 0   
BEGIN 
   --перенос формы из архивной базы
   EXEC dbo.[RN_MOVE_FORM_FROM_ARH] @iLINK_SAVED_FORM

   IF @tRazdel = 1 -- Раздел - 1 - Общая информация об учреждения
   BEGIN
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab001 ([CODE], [VALUE]) select [CODE], CASE WHEN [COL3] = '''' THEN [COL4] ELSE [COL3] END from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 2
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab001_OKVED ([CODE], [NAME], [NAMEU]) select CASE WHEN [COL1] = '''' THEN [COL3] ELSE [COL1] END, [COL2], [COL5] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 3
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab001_OKVED_ADD ([CODE], [NAME], [NAMEU]) select CASE WHEN [COL1] = '''' THEN [COL3] ELSE [COL1] END, [COL2], [COL5] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)
      
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 4
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab001_BRANCH ([CODE], [FULL_NAME], [NAME], [TYPE]) select [COL1], [COL2], [COL4], [COL3] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 5
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' UPDATE #tab001
                          SET VALUE = (select TOP 1 [COL2] from ' + @vcTmpTable+')   
                          WHERE CODE = ''116001''
                          UPDATE #tab001
                          SET VALUE = (select TOP 1 [COL3] from ' + @vcTmpTable+')   
                          WHERE CODE = ''116000''                          
                         drop table ' + @vcTmpTable
      EXECUTE(@vcExec)
      
      SET @ID = NEWID()
      
      UPDATE #tab001
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab001_OKVED
      SET ID = @ID
      WHERE ID IS NULL
      
      UPDATE #tab001_OKVED_ADD
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab001_BRANCH
      SET ID = @ID   
      WHERE ID IS NULL
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) -- дата и время изменения
      
      SELECT @ID, '000001', REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T')
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsfvs
      WHERE rsfvs.[link_saved_form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE])
      SELECT @ID, '000002', LTRIM(STR(@tVersion)) -- номер версии
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsfvs
      WHERE rsfvs.[link_saved_form] = @iLINK_SAVED_FORM
      
      INSERT #tab001 (ID, CODE, [VALUE]) 
      SELECT @ID, '000003', LEFT(rtrim(d.[NAME]),250) +' ИНН ('+RTRIM(D.INN)+')' 
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) 
      SELECT @ID, '000004', RTRIM(D.INN) 
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) 
      SELECT @ID, '000005', LTRIM(STR(D.BUH_TYPE)) 
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) 
      SELECT @ID, '000006', dbo.rn_get_ogs_code(D.INN,'',0) 
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) 
      SELECT @ID, '000007', B.CODE_STR  
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      INNER JOIN dbo.[REPORT_KBK] B ON B.CODE_FORM = 'SPR_86n_OGS_ADD_INFO' AND B.CODE = dbo.rn_get_ogs_code(D.INN,'',0) 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM
   END


   IF @tRazdel = 2   AND (SELECT CODE FROM REPORT_FORMS A INNER JOIN  REPORT_SAVED_FORMS B ON B.Link_Form = A.Link_Form WHERE B.Link_Saved_Form = @iLINK_SAVED_FORM) = '(86н)002'   
-- Раздел - 2 - Информация о государственном (муниципальном) задании на оказание услуг (выполнение работ) и его исполнении
   BEGIN
   	
   	
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 0, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab002_SERVICE ([CODE],[NUM_UTV], [NUM],[NAME],[KAT]) select [COL1], [COL2], [COL3], [COL4], [COL5] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 2
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab002_QUALITY ([CODE],[NAME],[EI_SYMBOL],[EI_NAME],[SUMMA1],[SUMMA2],[SUMMA3],[SUMMA4],[SUMMA5],[SUMMA6],[REASON]) select [COL1], [COL2], [COL3], [COL4], [COL5], [COL6], [COL7], [COL8], [COL9], [COL10], [COL11] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

	  UPDATE 	#tab002_QUALITY
	  SET EI_CODE = ISNULL((select O.Code_Str from report_kbk O WHERE Code_Form='R_86n_OKEI' AND (O.Code = EI_SYMBOL /*OR O.add_info = EI_SYMBOL*/)),'')


      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 3
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab002_VOLUME ([CODE],[NAME],[EI_SYMBOL],[EI_NAME],[SUMMA1],[SUMMA2],[SUMMA3],[SUMMA4],[SUMMA5],[SUMMA6],[REASON]) select [COL1], [COL2], [COL3], [COL4], [COL5], [COL6], [COL7], [COL8], [COL9], [COL10], [COL11] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

	  UPDATE 	#tab002_VOLUME
	  SET EI_CODE = ISNULL((select O.Code_Str from report_kbk O WHERE Code_Form='R_86n_OKEI' AND (O.Code = EI_SYMBOL /*OR O.add_info = EI_SYMBOL*/)),'')

      
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 4
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab002_PRICE ([CODE],[SUMMA],[NPA_VID],[NPA_NAME_ORGAN],[NPA_DATE],[NPA_NUM],[NPA_NAME]) select [COL1], [COL2], [COL3], [COL4], [COL5], [COL6], [COL7] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 5
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab002_WORK ([CODE],[NUM_UTV],[NUM],[NAME]) select [COL1], [COL2], [COL3], [COL4] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)
      
      SET @ID = NEWID()
      
      UPDATE #tab002
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_SERVICE
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_QUALITY
      SET ID = @ID
      WHERE ID IS NULL
      
      UPDATE #tab002_VOLUME
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_PRICE
      SET ID = @ID   
      WHERE ID IS NULL
      
      UPDATE #tab002_WORK
      SET ID = @ID    
      WHERE ID IS NULL
      
      INSERT #tab002 (ID,[changeDate],[versionNumber],[financialYear],[nextFinancialYear],[planFirstYear],[planLastYear])
      SELECT @ID, REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T'), '1', YEAR(rsf.[Begin_Date]), YEAR(rsf.[Begin_Date]) +1, YEAR(rsf.[Begin_Date])+2, YEAR(rsf.[Begin_Date]) +3
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM   

      INSERT #tab001 (ID, CODE, [VALUE]) -- Полное наименование
      SELECT @ID, '101000', dbo.[GetDepFullName](rsf.[Link_Organization], rsf.[Begin_Date])
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM 
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '103000', d.[INN]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '104000', d.[KPP]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

   END   

   IF @tRazdel = 2   AND (SELECT CODE FROM REPORT_FORMS A INNER JOIN  REPORT_SAVED_FORMS B ON B.Link_Form = A.Link_Form WHERE B.Link_Saved_Form = @iLINK_SAVED_FORM) = '(86н)002_398'   
-- Раздел - 2 - Информация о государственном (муниципальном) задании на оказание услуг (выполнение работ) и его исполнении
   BEGIN

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 0, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        'insert #tab002_SERVICE ([CODE],[NUM],[NAME],[KAT]) 
                        select [COL1], [COL2] , [COL3], [COL4] from ' + @vcTmpTable + 
						' insert #tab002_PRICE ([CODE],[SUMMA]) select [COL1], [COL5] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable


     	PRINT	@vcExec
      EXECUTE(@vcExec)
	UPDATE #tab002_SERVICE
	SET NUM = ISNULL((select TOP 1 CODE from R_398_RAZDEL WHERE NAME=NUM),'')
	WHERE EXISTS(select * from R_398_RAZDEL B WHERE B.NAME=NUM)


      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 2
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
						'UPDATE ' + @vcTmpTable + 
						' SET COL7 = REPLACE(REPLACE(REPLACE(COL7,'','',''.''),''-'',''-0''),''%'',''''),
						COL8 = REPLACE(REPLACE(REPLACE(COL8,'','',''.''),''-'',''-0''),''%'',''''),
						COL9 = REPLACE(REPLACE(REPLACE(COL9,'','',''.''),''-'',''-0''),''%'',''''),
						COL10 = REPLACE(REPLACE(REPLACE(COL10,'','',''.''),''-'',''-0''),''%'',''''),
						COL11 = REPLACE(REPLACE(REPLACE(COL11,'','',''.''),''-'',''-0''),''%'','''')

                         insert #tab002_QUALITY ([CODE],[NAME],[EI_CODE],[EI_SYMBOL],[SUMMA1],[SUMMA2],[SUMMA3],[SUMMA4],[SUMMA5],[SUMMA6],[REASON]) 
                        select COL1,[COL3], [COL2], [COL4], 
                        CASE WHEN ISNUMERIC([COL7])=1 THEN CAST(COL7 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL8])=1 THEN CAST(COL8 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL9])=1 THEN CAST(COL9 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL10])=1 THEN CAST(COL10 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL11])=1 THEN CAST(COL11 AS NUMERIC(20,2)) ELSE 0 END,
                         0, '''' from ' + @vcTmpTable + 
                        ' drop table ' + @vcTmpTable
	PRINT	@vcExec
      EXECUTE(@vcExec)


	  UPDATE 	#tab002_QUALITY
	  	  SET EI_CODE = ISNULL((select O.Code_Str from report_kbk O WHERE Code_Form='R_86n_OKEI' AND (O.Code = EI_SYMBOL OR O.add_info = EI_SYMBOL  OR O.name = EI_SYMBOL 
	  	  OR O.Code = REPLACE(EI_SYMBOL,'.','') OR O.add_info = REPLACE(EI_SYMBOL,'.',''))),'')



      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 3

      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
						'UPDATE ' + @vcTmpTable + 
						' SET COL7 = REPLACE(REPLACE(REPLACE(COL7,'','',''.''),''-'',''-0''),''%'',''''),
						COL8 = REPLACE(REPLACE(REPLACE(COL8,'','',''.''),''-'',''-0''),''%'',''''),
						COL9 = REPLACE(REPLACE(REPLACE(COL9,'','',''.''),''-'',''-0''),''%'',''''),
						COL10 = REPLACE(REPLACE(REPLACE(COL10,'','',''.''),''-'',''-0''),''%'',''''),
						COL11 = REPLACE(REPLACE(REPLACE(COL11,'','',''.''),''-'',''-0''),''%'','''')
                         insert #tab002_VOLUME ([CODE],[NAME],[EI_CODE],[EI_SYMBOL],[SUMMA1],[SUMMA2],[SUMMA3],[SUMMA4],[SUMMA5],[SUMMA6],[REASON]) 
                        select [COL1], [COL3], [COL2], [COL4], 
                        CASE WHEN ISNUMERIC([COL7])=1 THEN CAST(COL7 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL8])=1 THEN CAST(COL8 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL9])=1 THEN CAST(COL9 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL10])=1 THEN CAST(COL10 AS NUMERIC(20,2)) ELSE 0 END,
                        CASE WHEN ISNUMERIC([COL11])=1 THEN CAST(COL11 AS NUMERIC(20,2)) ELSE 0 END,
					    0, '''' from ' + @vcTmpTable + 
                        ' drop table ' + @vcTmpTable
      print @vcExec
      EXECUTE(@vcExec)

	  UPDATE 	#tab002_VOLUME
	  	  SET EI_CODE = ISNULL((select O.Code_Str from report_kbk O WHERE Code_Form='R_86n_OKEI' AND (O.Code = EI_SYMBOL OR O.add_info = EI_SYMBOL OR O.name = EI_SYMBOL
	  	  OR O.Code = REPLACE(EI_SYMBOL,'.','') OR O.add_info = REPLACE(EI_SYMBOL,'.',''))),'')

    
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 6
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        'insert #tab002_PRICE ([CODE],[SUMMA],[NPA_VID],[NPA_NAME_ORGAN],[NPA_DATE],[NPA_NUM],[NPA_NAME]) 
                        select [COL1], 0, [COL3], [COL4], [COL5], [COL6], [COL7] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
	PRINT ''
	PRINT	@vcExec
    EXECUTE(@vcExec)


      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 4
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        'insert #tab002_PRICE ([CODE],[SUMMA],[NPA_VID],[NPA_NAME_ORGAN],[NPA_DATE],[NPA_NUM],[NPA_NAME]) 
                        select [COL1], 0, [COL3], [COL4], [COL5], [COL6], [COL7] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable+'
                        UPDATE A 
                        SET A.SUMMA = B.SUMMA
                        FROM #tab002_PRICE A, #tab002_PRICE B WHERE A.CODE = B.CODE AND B.[NPA_VID] IS NULL
                        DELETE #tab002_PRICE WHERE [NPA_VID] IS NULL'
	PRINT	@vcExec
      EXECUTE(@vcExec)


      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 7
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' UPDATE A 
                        SET NPA_NAME_ORGAN = B.COL2
                        FROM #tab002_PRICE A, '+@vcTmpTable+' B WHERE A.CODE = B.CODE
                        drop table ' + @vcTmpTable 
PRINT	@vcExec
      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 10
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' +
                        ' insert #tab002_WORK ([CODE],[NUM],[NAME]) select [COL1], [COL2], [COL3] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
--PRINT	@vcExec
      EXECUTE(@vcExec)

	UPDATE #tab002_WORK
	SET NUM = ISNULL((select TOP 1 CODE from R_398_RAZDEL WHERE NAME=NUM),'')
	WHERE EXISTS(select * from R_398_RAZDEL B WHERE B.NAME=NUM)

      
      SET @ID = NEWID()
      
      UPDATE #tab002
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_SERVICE
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_QUALITY
      SET ID = @ID
      WHERE ID IS NULL
      
      UPDATE #tab002_VOLUME
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab002_PRICE
      SET ID = @ID   
      WHERE ID IS NULL
      
      UPDATE #tab002_WORK
      SET ID = @ID    
      WHERE ID IS NULL

      
      INSERT #tab002 (ID,[changeDate],[versionNumber],[financialYear],[nextFinancialYear],[planFirstYear],[planLastYear])
      SELECT @ID, REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T'), '1', YEAR(rsf.[Begin_Date]), YEAR(rsf.[Begin_Date]) +1, YEAR(rsf.[Begin_Date])+2, YEAR(rsf.[Begin_Date]) +3
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM   

      INSERT #tab001 (ID, CODE, [VALUE]) -- Полное наименование
      SELECT @ID, '101000', dbo.[GetDepFullName](rsf.[Link_Organization], rsf.[Begin_Date])
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM 
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '103000', d.[INN]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '104000', d.[KPP]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

   END   


   IF @tRazdel = 3 -- Раздел - 3 - Информация о плане финансово-хозяйственной деятельности   
   BEGIN
   	  IF (SELECT CODE FROM REPORT_FORMS A INNER JOIN  REPORT_SAVED_FORMS B ON B.Link_Form = A.Link_Form WHERE B.Link_Saved_Form = @iLINK_SAVED_FORM) = '(86н)003_398'   
		SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 5
		ELSE	
	      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 0, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab003_FHD ([CODE],[SUMMA1],[SUMMA2],[SUMMA3]) select [CODE], [COL3], [COL4], [COL5] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SET @ID = NEWID()
      
   	  IF (SELECT CODE FROM REPORT_FORMS A INNER JOIN  REPORT_SAVED_FORMS B ON B.Link_Form = A.Link_Form WHERE B.Link_Saved_Form = @iLINK_SAVED_FORM) = '(86н)003_398'
   		BEGIN
   			UPDATE #tab003_FHD
   			SET CODE = '33701'
   			WHERE CODE = '33700'

			INSERT #tab003_FHD ([CODE],[SUMMA1],[SUMMA2],[SUMMA3])
			SELECT '33603',SUM(SUMMA1),SUM(SUMMA2),SUM(SUMMA3)
			FROM #tab003_FHD WHERE CODE IN ('33016','33028') 	   			

   		END    

      UPDATE #tab003_FHD
      SET ID = @ID
      WHERE ID IS NULL

      
      INSERT #tab003 (ID,[changeDate],[versionNumber],[financialYear],[planFirstYear],[planLastYear])
      SELECT @ID, REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T'), '1',  YEAR(rsf.[Begin_Date]) +1, YEAR(rsf.[Begin_Date])+2, YEAR(rsf.[Begin_Date]) +3
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM
      
     
      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM   

      INSERT #tab001 (ID, CODE, [VALUE]) -- Полное наименование
      SELECT @ID, '101000', dbo.[GetDepFullName](rsf.[Link_Organization], rsf.[Begin_Date])
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM 
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '103000', d.[INN]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '104000', d.[KPP]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

   END   

   IF @tRazdel = 4 -- Раздел - 4 - Информация об операциях с целевыми средствами из бюджета 
   BEGIN
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab004_BUDGETARY ([CODE],[SUMMA]) select [CODE], [COL3] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable

      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 2
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab004_CONSTRUCTION ([CODE],[NAME],[KAT],[SUMMA]) select [CODE], [COL1], [COL2], [COL3] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable

      EXECUTE(@vcExec)

      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 3
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab004_GRANT ([CODE],[NAME],[SUMMA]) select [CODE], [COL2], [COL3] from ' + @vcTmpTable + ' drop table ' + @vcTmpTable
                        
      EXECUTE(@vcExec)
      SET @ID = NEWID()
      
      UPDATE #tab004_BUDGETARY
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab004_CONSTRUCTION
      SET ID = @ID
      WHERE ID IS NULL

      UPDATE #tab004_GRANT
      SET ID = @ID
      WHERE ID IS NULL

      INSERT #tab004 (ID,[changeDate],[versionNumber],[financialYear])
      SELECT @ID, REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T'), '1',  YEAR(rsf.[Begin_Date]) +1
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM   

      INSERT #tab001 (ID, CODE, [VALUE]) -- Полное наименование
      SELECT @ID, '101000', dbo.[GetDepFullName](rsf.[Link_Organization], rsf.[Begin_Date])
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM 
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '103000', d.[INN]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '104000', d.[KPP]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

   END   


   IF @tRazdel = 5 -- Раздел - 5 - Бюджетные обязательства 
   BEGIN
      SELECT @lt = rt.[Link_Table] FROM dbo.[REPORT_TABLES] rt WHERE rt.[Link_Form] = @lf AND orders = 1
      
      SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@lt)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table = ''' + @vcTmpTable + '''' + 
                        ' insert #tab005_CIRCUMSTANCE ([CODE], [NAME],[RZPR], [CSR], [VR], [SGU], [BUDGET_CODE], [BUDGET_NAME], [SUMMA]) 
                        select [CODE], [COL2], [COL3], [COL4], [COL5], [COL6], [COL8], [COL9], [COL7] from ' + @vcTmpTable + '
                        where COL3 <> ''9600''  
                         drop table ' + @vcTmpTable
      EXECUTE(@vcExec)

      SET @ID = NEWID()
      
      UPDATE #tab005_CIRCUMSTANCE
      SET ID = @ID
      WHERE ID IS NULL

      INSERT #tab005 (ID,[changeDate],[versionNumber],[financialYear])
      SELECT @ID, REPLACE(left(ISNULL(convert(varchar(30), DateLastEdit, 127),convert(varchar(30),GETDATE(),127)),19),' ','T'), '1',  YEAR(rsf.[Begin_Date]) +1
      FROM dbo.[RO_SAVED_FORMS_VIEW_SVOD] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- Реестровый номер организации в ОГС
      SELECT @ID, '000000', d.[CODE]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM   

      INSERT #tab001 (ID, CODE, [VALUE]) -- Полное наименование
      SELECT @ID, '101000', dbo.[GetDepFullName](rsf.[Link_Organization], rsf.[Begin_Date])
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM 
      
      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '103000', d.[INN]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- ИНН
      SELECT @ID, '104000', d.[KPP]
      FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

      INSERT #tab001 (ID, CODE, [VALUE]) -- АДМ
      SELECT @ID, '105000', dbo.RN_GET_ATR_VALUE(rsf.Link_Saved_Form, 'REPORTS_ATR_ADM')
      FROM dbo.[REPORT_SAVED_FORMS] rsf 
      WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM     

     
      UPDATE A
      SET CODE = RTRIM(VALUE)+RTRIM(A.CODE)
      FROM  #tab005_CIRCUMSTANCE A 
      INNER JOIN #tab001 B ON A.ID = B.ID 
      WHERE B.CODE = '105000'

   END
   FETCH NEXT FROM cur INTO @iLINK_SAVED_FORM   
END


DELETE R
FROM dbo.[REPORT_SAVED_FORMS] rsf
   JOIN #Reports R ON rsf.[Link_Saved_Form] = R.LSF AND rsf.[Link_Form] = @lf

SET @tVersion = @tVersion + 1
EXEC dbo.[RO_EXPORT_INFO_SAVE] @iLINK_SAVED_FORM,  @tVersion 

GO
GRANT ALL ON dbo.[RO_EXPORT_86N_GET_DATA] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_GET_DOCUMENTS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_GET_DOCUMENTS]

GO
CREATE PROCEDURE dbo.DP_GET_DOCUMENTS
    @varKSMode         INT,
    @varKSFOLDER       INT = NULL,         
    @varKSSORTFIELD    VARCHAR(50) = NULL, 
    @varKSDEFASC       INT = NULL          
AS

DECLARE @varKSStrSQL         VARCHAR(8000),
        @varKSStrSelect      VARCHAR(1500),
        @varKSStrFrom        VARCHAR(1000),
        @varKSStrWhere       VARCHAR(1000),
        @varKSLinkOutOtd     INT,
        @varKSEventRegLink   INT,
        @varKSLinkEmpl       INT


IF @varKSFOLDER IS NULL SELECT @varKSFOLDER = 0                                         

SELECT @varKSLinkOutOtd = LINK FROM S_OBJECTS WHERE CODE = 'WF_COLUMN_DOC_OUT_OTD'
SELECT @varKSEventRegLink = LINK FROM S_OBJECTS WHERE CODE = 'WF_EVENT_REG'

DECLARE @getdate datetime
set @getdate = GETDATE()
CREATE TABLE #StatusImageByDoc(LINK INT, StatusImage TINYINT)
INSERT INTO #StatusImageByDoc(LINK, StatusImage)
SELECT LINK, StatusImage FROM dbo.StatusImageByDoc (@getdate) 

SELECT @varKSStrSelect =
  CASE    WHEN @varKSMode = 11 and @varKSFOLDER = -16
     THEN 'SELECT
              DISTINCT D.LINK,
              D.DATE_DOC,
              D.NAME,
              D.DOC_TIP,
              isnull(S.StatusImage,0) AS IMG ,
 	      ES.SUBDIV_LINK as SUBDIV_LINK'
		  WHEN @varKSMode = 12 and @varKSFOLDER = -16
     THEN 'SELECT
              DISTINCT D.LINK,
              D.DATE_DOC,
              D.SODER,
              D.NAME,
              D.DOC_TIP,
              D.ISHNISP,
              D.ISHDISP,
	      (SELECT [NAME] FROM DEPARTMENTS WHERE LINK = D.CORR) AS COR_NAME, 		
              (SELECT DV.NAME FROM WF_DOCVID DV WHERE DV.LINK = D.DOC_VID) AS VID, 		
              (CASE WHEN ER.REG_NUM IS NOT NULL
                 THEN ER.REG_NUM
                 ELSE ''не рег.'' END) AS REG_NUM,
              CONVERT(VARCHAR(10),ER.REG_DATE,120) AS REG_DATE,
              isnull(S.StatusImage,0) AS IMG,
	      ES.SUBDIV_LINK as SUBDIV_LINK'
		  WHEN @varKSMode = 1
     THEN 'SELECT
              DISTINCT D.LINK,
              D.DATE_DOC,
              D.NAME,
              D.DOC_TIP,
              isnull(S.StatusImage,0) AS IMG '
     ELSE 'SELECT
              DISTINCT D.LINK,
              D.DATE_DOC,
              D.SODER,
              D.NAME,
              D.DOC_TIP,
              D.ISHNISP,
              D.ISHDISP,
	      (SELECT [NAME] FROM DEPARTMENTS WHERE LINK = D.CORR) AS COR_NAME,
              (SELECT DV.NAME FROM WF_DOCVID DV WHERE DV.LINK = D.DOC_VID) AS VID, 		
              (CASE WHEN ER.REG_NUM IS NOT NULL
                 THEN ER.REG_NUM
                 ELSE ''не рег.'' END) AS REG_NUM,
              CONVERT(VARCHAR(10),ER.REG_DATE,120) AS REG_DATE,
              isnull(S.StatusImage,0) AS IMG '
   END


IF NOT (IS_MEMBER ('ДЕЛО-КС - ОКО') = 1) 
SET @varKSStrFrom ='	FROM dbo.DOCUMENTS D INNER JOIN dbo.DOC_ACCESS SEC ON D.LINK = SEC.DOC_LINK 
                INNER JOIN dbo.WHO_IS_WHO WW ON SEC.LINK_EMPL = WW.USER_REF
                INNER JOIN dbo.USER_INFO UI ON WW.SID = UI.SID
                INNER JOIN #StatusImageByDoc S ON S.LINK = D.LINK
                LEFT OUTER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC'
ELSE
SET @varKSStrFrom ='	FROM dbo.DOCUMENTS D
				INNER JOIN #StatusImageByDoc S ON S.LINK = D.LINK 
                LEFT JOIN dbo.USER_INFO UI ON 1 = 1
                LEFT OUTER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC '

IF NOT (IS_MEMBER ('ДЕЛО-КС - ОКО') = 1) 
SET @varKSStrWhere = ' WHERE (((D.DATE_DOC BETWEEN UI.BEGINDATE AND UI.ENDDATE) AND (ER.REG_DATE IS NULL)) OR (NOT (ER.REG_DATE IS NULL) AND (ER.REG_DATE BETWEEN UI.BEGINDATE AND UI.ENDDATE))) '
ELSE
SET @varKSStrWhere = ' WHERE (((D.DATE_DOC BETWEEN UI.BEGINDATE AND UI.ENDDATE) AND (ER.REG_DATE IS NULL)) OR (NOT (ER.REG_DATE IS NULL) AND (ER.REG_DATE BETWEEN UI.BEGINDATE AND UI.ENDDATE))) AND D.LINK > 0'


IF @varKSFOLDER < 0           
BEGIN
     SELECT @varKSLinkEmpl = USER_REF FROM WHO_IS_WHO WHERE SID = (SELECT SID FROM USER_INFO)
     -- выделить заведённые пользователем карточки
     IF NOT (IS_MEMBER ('ДЕЛО-КС - ОКО') = 1)  -- пользователи включенные в роль ДЕЛО-КС - ОКО имеют доступ ко всем документам папки
		begin

		IF (@varKSLinkEmpl IS NOT NULL)
			BEGIN
				SELECT LINK_DOC, EVENT_LINK_EMPL into #card FROM EVENT_GETDOC WHERE EVENT_LINK_EMPL = @varKSLinkEmpl
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_GETCITIZ WHERE EVENT_LINK_EMPL = @varKSLinkEmpl
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_OUTISP WHERE EVENT_LINK_EMPL = @varKSLinkEmpl
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_CREATE WHERE EVENT_LINK_EMPL = @varKSLinkEmpl

     			SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN #card CARDS ON (D.LINK = CARDS.LINK_DOC)'
			END
			ELSE
			BEGIN
				SELECT LINK_DOC, EVENT_LINK_EMPL into #card2 FROM EVENT_GETDOC
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_GETCITIZ
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_OUTISP
				UNION ALL
				SELECT LINK_DOC, EVENT_LINK_EMPL FROM EVENT_CREATE

     			SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN #card2 CARDS ON (D.LINK = CARDS.LINK_DOC)'
			END
     	--SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.GetRegCardsByEmpl(' + STR(@varKSLinkEmpl) + ') CARDS ON (D.LINK = CARDS.LINK_DOC)'
		end
--     ELSE
--     	SET @varKSStrFrom = @varKSStrFrom + ' LEFT JOIN dbo.GetRegCardsByEmpl(' + STR(@varKSLinkEmpl) + ') CARDS ON (D.LINK = CARDS.LINK_DOC)'
	
     -- добавить отделы к реквизитам вх. документов
     IF @varKSFOLDER = -16 AND @varKSMode > 10 
	SET @varKSStrFrom = @varKSStrFrom +'INNER JOIN dbo.EVENT_EXECUTORS EX ON (D.LINK = EX.LINK_DOC)
	INNER JOIN DBO.EMPL_STAFF(DEFAULT) ES ON EX.EXECUTOR = ES.EMPL_LINK '
     -- документы по видам
     IF @varKSFOLDER IN (SELECT (-1)*LINK FROM WF_DOCVID)
        SET @varKSstrSQL = @varKSStrSelect + @varKSStrFrom + @varKSStrWhere + 'AND D.DOC_VID   = ' + STR(-1*@varKSFOLDER)

     -- документы по типам
     IF @varKSFOLDER IN (SELECT (-1)*TIP FROM WF_DOCTIP WHERE TIP_CLASS LIKE 'WF_DOC_CARD%')
        SET @varKSstrSQL = @varKSStrSelect + @varKSStrFrom + @varKSStrWhere + 'AND D.DOC_TIP = ' + STR(-1*@varKSFOLDER)

     -- документы по номеклатуре
     IF @varKSFOLDER IN (SELECT (-1)*LINK FROM WF_DOCDELO)
        SET @varKSstrSQL = @varKSStrSelect + @varKSStrFrom + @varKSStrWhere + 'AND D.DELO   = ' + STR(-1*@varKSFOLDER)
END
ELSE
BEGIN
     -- папки-фильтры
     IF 2 = (SELECT DOC_TIP FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
     BEGIN
        SELECT @varKSStrSQL = VALUE FROM DOCUMENTS_APP WHERE LINK_UP = @varKSFOLDER AND OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'WF_FILTER_FIELD')
        SET @varKSStrSQL = REPLACE(@varKSStrSQL,'FROM dbo.DOCUMENTS D',@varKSStrSelect + ' FROM dbo.DOCUMENTS D INNER JOIN #StatusImageByDoc S ON S.LINK = D.LINK')
     END
	
     -- пользовательские и системные папки
     IF 0 = (SELECT DOC_TIP FROM DOCUMENTS WHERE LINK = @varKSFOLDER) OR
        1 = (SELECT DOC_TIP  FROM DOCUMENTS  WHERE LINK = @varKSFOLDER) OR
        (SELECT DOC_TIP FROM DOCUMENTS WHERE LINK = @varKSFOLDER) IS NULL
		 SET @varKSstrSQL = @varKSStrSelect +  @varKSStrFrom + ',DOCUMENTS_REF DR ' + @varKSStrWhere + 
                           ' AND D.DOC_TIP IN (SELECT TIP FROM WF_DOCTIP WHERE TIP_CLASS LIKE ''WF_DOC_CARD%'') AND DR.REF_DOWN = D.LINK AND DR.REF_UP =' + STR(@varKSFOLDER)


     IF (IS_MEMBER ('ДЕЛО-КС - ОКО') = 1)  -- пользователи включенные в роль ДЕЛО-КС - ОКО паках-фильтрах и сист-папках видят только свои
	SET @varKSStrFrom = @varKSStrFrom + 
				' INNER JOIN dbo.DOC_ACCESS SEC ON D.LINK = SEC.DOC_LINK 
			                INNER JOIN dbo.WHO_IS_WHO WW ON SEC.LINK_EMPL = WW.USER_REF
			                INNER JOIN dbo.USER_INFO UI2 ON WW.SID = UI2.SID'

     -- поступившая документация
     IF 3 = (SELECT DOC_TIP FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
     BEGIN
 IF 'Поручения' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
       BEGIN
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_EXECUTORS EX ON (D.LINK = EX.LINK_DOC) AND (SEC.LINK_EMPL = EX.EXECUTOR)'
END
 IF 'На подпись' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
       BEGIN
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KOMU)'
       END
       IF 'По маршруту' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
       BEGIN
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_ROUTED ERO ON (ERO.LINK_DOC = D.LINK)
                                               INNER JOIN dbo.WF_ROUTED_EMPL WRE ON (ERO.LINK = WRE.LINK_UP) AND (WRE.LINK_EMPL = SEC.LINK_EMPL)'
       END
       IF 'Обработанные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_ROUTED ERO ON (ERO.LINK_DOC = D.LINK) 
					INNER JOIN dbo.WF_ROUTED_EMPL WRE ON (ERO.LINK = WRE.LINK_UP) AND (WRE.LINK_EMPL = SEC.LINK_EMPL)
					INNER JOIN dbo.EVENT_ROU ERU ON ERO.LINK = ERU.LINK_ROU'
	end
       IF 'Необработанные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_ROUTED ERO ON (ERO.LINK_DOC = D.LINK) 
						AND NOT EXISTS (SELECT NULL FROM dbo.EVENT_ROU WHERE LINK_ROU = ERO.LINK)
						INNER JOIN dbo.WF_ROUTED_EMPL WRE ON (ERO.LINK = WRE.LINK_UP) AND (WRE.LINK_EMPL = SEC.LINK_EMPL)'
	end

       IF 'На рассмотрении' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KOMU)
							AND NOT EXISTS (SELECT NULL FROM EVENT_VISA WHERE TOVISA_LINK = ETV.LINK)'
--					      	AND etv.link not in (SELECT etv2.link FROM dbo.EVENT_TOVISA etv2 INNER JOIN EVENT_VISA EV on etv2.link=ev.tovisa_link and etv2.link = etv.link)

	end


       IF 'Завизированные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KOMU)
					      	INNER JOIN dbo.EVENT_VISA EV ON ETV.LINK = EV.TOVISA_LINK AND EV.REJECT = 0'
	 SET @varKSStrWhere = @varKSStrWhere + ' AND d.link not in 
						(SELECT _etv.link_doc 
						 FROM dbo.EVENT_TOVISA _etv LEFT JOIN 
						      dbo.EVENT_VISA   _ev ON _etv.link=_ev.tovisa_link
						 WHERE _ev.link is null)'
	end

       IF 'Отклоненные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KOMU)
					      	INNER JOIN dbo.EVENT_VISA EV ON ETV.LINK = EV.TOVISA_LINK AND EV.REJECT = 1'
	 SET @varKSStrWhere = @varKSStrWhere + ' AND d.link not in (SELECT _etv.link_doc 
						FROM dbo.EVENT_TOVISA _etv LEFT JOIN 
							dbo.EVENT_VISA _ev on _etv.link=_ev.tovisa_link
						WHERE _ev.link is null)'
	end

       -- сформировать запрос
       SET @varKSstrSQL = @varKSStrSelect + @varKSStrFrom + @varKSStrWhere
     END

     -- отправленная документация
     IF 4 = (SELECT DOC_TIP FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
     BEGIN
       IF 'На исполнение' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
       BEGIN
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TASK ET ON (D.LINK = ET.LINK_DOC) AND (SEC.LINK_EMPL = ET.TASK_AUTH OR SEC.LINK_EMPL = ET.EVENT_LINK_EMPL)'
         SET @varKSStrWhere = @varKSStrWhere + ' AND EXISTS (SELECT * FROM dbo.EVENT_TASK_REF WHERE LINK_TASK = ET.LINK)'
       END



       IF 'На визирование' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
      BEGIN
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KTO)'
       END

       IF 'На рассмотрении' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KTO)
							AND NOT EXISTS (SELECT NULL FROM EVENT_VISA WHERE TOVISA_LINK = ETV.LINK)'
	end

       IF 'Завизированные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KTO)
					      	INNER JOIN dbo.EVENT_VISA EV ON ETV.LINK = EV.TOVISA_LINK AND EV.REJECT = 0'
	 SET @varKSStrWhere = @varKSStrWhere + ' AND d.link not in 
						(SELECT _etv.link_doc 
						 FROM dbo.EVENT_TOVISA _etv LEFT JOIN 
						      dbo.EVENT_VISA   _ev ON _etv.link=_ev.tovisa_link
						 WHERE _ev.link is null)'
	end

       IF 'Отклоненные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
         SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_TOVISA ETV ON (D.LINK = ETV.LINK_DOC) AND (SEC.LINK_EMPL = ETV.TOVISA_KTO)
					      	INNER JOIN dbo.EVENT_VISA EV ON ETV.LINK = EV.TOVISA_LINK AND EV.REJECT = 1'
	 SET @varKSStrWhere = @varKSStrWhere + ' AND d.link not in (SELECT _etv.link_doc 
						FROM dbo.EVENT_TOVISA _etv LEFT JOIN 
							dbo.EVENT_VISA _ev on _etv.link=_ev.tovisa_link
						WHERE _ev.link is null)'
	end




       IF 'По маршруту' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
       BEGIN
         SET @varKSStrWhere = @varKSStrWhere + ' AND (EXISTS (SELECT * FROM dbo.EVENT_ROUTED WHERE (EVENT_LINK_EMPL = SEC.LINK_EMPL OR ROUTED_AUTHOR = SEC.LINK_EMPL) AND LINK_DOC = D.LINK) OR
                                                      EXISTS (SELECT * FROM dbo.EVENT_SENDDOC WHERE EVENT_LINK_EMPL = SEC.LINK_EMPL AND LINK_DOC = D.LINK AND SEND_DATE IS NOT NULL))'
       END

	IF 'Обработанные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
	 SET @varKSStrWhere = @varKSStrWhere + ' AND (EXISTS (SELECT * FROM dbo.EVENT_ROUTED WHERE (EVENT_LINK_EMPL = SEC.LINK_EMPL OR ROUTED_AUTHOR = SEC.LINK_EMPL) AND LINK_DOC = D.LINK) OR
	                                      EXISTS (SELECT * FROM dbo.EVENT_SENDDOC WHERE EVENT_LINK_EMPL = SEC.LINK_EMPL AND LINK_DOC = D.LINK AND SEND_DATE IS NOT NULL))
					 AND d.link not in (select _er.link_doc from dbo.event_routed _er inner join 
								dbo.wf_routed_empl _wre on _er.link = _wre.link_up left join
								dbo.event_rou _ero on _er.link = _ero.link_rou
							    where _ero.link is null)'
  	end
	IF 'Необработанные' = (SELECT NAME FROM DOCUMENTS WHERE LINK = @varKSFOLDER)
	begin
	 SET @varKSStrFrom = @varKSStrFrom + ' INNER JOIN dbo.EVENT_ROUTED ERO ON (ERO.LINK_DOC = D.LINK) AND ((ERO.EVENT_LINK_EMPL = SEC.LINK_EMPL) OR (ERO.ROUTED_AUTHOR = SEC.LINK_EMPL))
						INNER JOIN dbo.WF_ROUTED_EMPL WRE ON (ERO.LINK = WRE.LINK_UP) 
						 AND NOT EXISTS (SELECT NULL FROM dbo.EVENT_ROU WHERE LINK_ROU = ERO.LINK AND EVENT_LINK_EMPL = WRE.LINK_EMPL)'
	end

       -- сформировать запрос
       SET @varKSstrSQL = @varKSStrSelect + @varKSStrFrom + @varKSStrWhere
     END
END

IF NOT @varKSSORTFIELD IS NULL
   SET @varKSstrSQL = @varKSstrSQL + ' ORDER BY D.' + @varKSSORTFIELD

IF @varKSDEFASC = 1
   SET @varKSstrSQL = @varKSstrSQL + ' DESC'
IF @varKSDEFASC = 0
   SET @varKSstrSQL = @varKSstrSQL + ' ASC'

--PRINT @varKSStrSQL

EXECUTE(@varKSstrSQL)


RETURN 0








GO


GRANT EXECUTE ON dbo.[DP_GET_DOCUMENTS] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[X_SAVE_DOCUMENTS_PAY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_SAVE_DOCUMENTS_PAY]
GO






/*
© Кейсистемс (Keysystems), 2005
*/

CREATE            
PROCEDURE dbo.X_SAVE_DOCUMENTS_PAY
	@varKSpLINK		int	OUTPUT,
	@varKSpNUMBER		char(25) = null,
	@varKSpDATE		datetime = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment	varchar(254) = null,
	@varKSpKIND           CHAR(50) = null,
	@varKSpS_LINK         INT = null,		
	@varKSpS_ACC_LINK     INT = null,
	@varKSpD_LINK         INT = null,		
	@varKSpD_ACC_LINK     INT = null,
	@varKSpSROK           DATETIME = null,
	@varKSpORDER          CHAR(1) = null,
	@varKSpPAYKIND        CHAR(5) = null,
	@varKSpREASON         CHAR(5) = null,
	@varKSpTARGETTEXT     VARCHAR(1000) = null,
	@varKSpNDS            INT = null,
	@varKSpBK_IN_TGT      tinyint = null,
	@varKSpPRINT_KPP      tinyint = null,
	@varKSpNDS_LINK       INT = null,
	@cObjCode			  varchar(50)
	


AS

SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @varKSERROR	tinyint,
	@varKSstrVALUE	varchar(7000),
	@varKSEventText	varchar(254),
	@varKStrancount	int,
	@varKSiLinkObj	int,
	@cObjName	    varchar(100)
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	
	IF @varKSpS_ACC_LINK IS NULL OR @varKSpS_ACC_LINK = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	select @varKSiLinkObj = LINK, @cObjName = NAME from s_objects where code = @cObjCode
	IF coalesce(@varKSiLinkObj,0)<=0 
	BEGIN
		ROLLBACK
		RETURN 7
	END

	SELECT @varKSpS_LINK = link_up from department_accounts where link = @varKSpS_ACC_LINK
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV @varKSpLINK OUTPUT, @varKSpNUMBER, @varKSpDATE, @varKSiLinkObj, @varKSpDATE_PROV, @varKSpSumma, @varKSpComment, 0, @varKSpS_LINK, @varKSpS_ACC_LINK  
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN @varKSERROR
	END

	IF @varKSpLINK <= 0 
	BEGIN
		ROLLBACK
		RETURN 7
	END
	
	IF exists (select * from FINANSE_PAYS where link = @varKSpLINK)
		UPDATE FINANSE_PAYS
			SET 
			S_Acc = @varKSpS_ACC_LINK,
			D_Acc = @varKSpD_ACC_LINK,
			kind = @varKSpKIND,
			srok = @varKSpSROK,
			order_pay = @varKSpORDER,
			PayKind = @varKSpPAYKIND,
			Reason = @varKSpREASON,
			BK_IN_TGT = @varKSpBK_IN_TGT,
			Print_KPP = @varKSpPRINT_KPP,
			NDS = @varKSpNDS,
			NDS_Link = @varKSpNDS_LINK,
			TargetText = @varKSpTARGETTEXT

		WHERE link = @varKSpLINK
	ELSE
		INSERT INTO FINANSE_PAYS (link, S_Acc, D_Acc, kind, srok, order_pay, PayKind, Reason, BK_IN_TGT, Print_KPP, NDS, NDS_Link, TargetText)
			VALUES (@varKSpLINK, @varKSpS_ACC_LINK, @varKSpD_ACC_LINK, @varKSpKIND, @varKSpSROK, @varKSpORDER, @varKSpPAYKIND, @varKSpREASON, @varKSpBK_IN_TGT, 
				@varKSpPRINT_KPP, @varKSpNDS, @varKSpNDS_LINK, @varKSpTARGETTEXT)

	SET @varKSEventText = @cObjName + ' №' + RTRIM(@varKSpNUMBER) + ' от ' + convert(varchar, @varKSpDATE, 104)
	EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSiLinkObj, 'G_PROV', @varKSpLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_EXPORT_INV_BALANSODER]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_EXPORT_INV_BALANSODER]

GO
CREATE PROCEDURE dbo.BK_EXPORT_INV_BALANSODER
AS
BEGIN
	/*
	DECLARE @TAB_NEDV TABLE
		(NAME1	VARCHAR (255),
		NAME2	VARCHAR (45),
		ADR1	VARCHAR (255),
		ADR2	VARCHAR (255),
		INVNUM	VARCHAR (30),
		BTINUM	VARCHAR (30),
		BTIDATE	DATETIME,
		BALBAL	NUMERIC (18,9),
		BALBALRE	NUMERIC (18,9),
		FULLSQ	NUMERIC (18,9),
		SEQNUM	VARCHAR (14),
		DATEVVOD	VARCHAR (20),
		ETAJ	VARCHAR (15),
		PROTAJ	NUMERIC (18, 3),
		MATER	VARCHAR (25),
		KADNUM	VARCHAR (50)
		)
	*/
	DECLARE @TAB_REST TABLE 
		(DEP_LINK	INT,
		INV	INT,
		SUMMA	NUMERIC (28,4),
		AMORT	NUMERIC (28,4),
		QTY	NUMERIC (28,4),
		LAST_SUM	NUMERIC (28,4))
	
	INSERT INTO @TAB_REST
	SELECT R.DEP_LINK,
		R.INV,
		SUM (R.BALANS),
		SUM (R.AMORT),
		SUM (R.QTY),
		SUM (R.LAST_SUM)
	FROM dbo.BK_GetTableRestINV (DEFAULT, DEFAULT, DEFAULT) R
	GROUP BY R.DEP_LINK,
		R.INV
	HAVING SUM (R.QTY) > 0
	
	--SELECT * FROM @TAB_REST
	
	DECLARE @TAB_DV TABLE
		([NAME]	VARCHAR (100),
		DEP_COST	NUMERIC (18,9),
		COST2	NUMERIC (18,9),
		INOD	VARCHAR (14),
		DAT_EKS	VARCHAR (100),
		GOSNUM	VARCHAR (10),
		DATEVVOD	VARCHAR (20),
		KOL	NUMERIC (18,9)
		)
	
	INSERT INTO @TAB_DV
	SELECT CONVERT (VARCHAR (100), INV.[NAME]),
		LAST_SUM,
		SUMMA,
		CONVERT (VARCHAR (14), INV.CODE),
		CONVERT (VARCHAR (100), ISNULL (YEAR (ASS.DATE_PROD), 0)),
		'',
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_BEGIN , 104), ''),
		CASE
			WHEN ASS.GRP_CALC = 1 THEN R.QTY
			ELSE 0
		END
	FROM dbo.INVENTORY INV
	INNER JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = INV.LINK)
	INNER JOIN @TAB_REST R ON (R.INV = INV.LINK)
	
	SELECT *
	FROM @TAB_DV

	RETURN 0
END

GO


GRANT EXECUTE ON dbo.[BK_EXPORT_INV_BALANSODER] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SAVE_REG]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SAVE_REG]

GO

CREATE  PROCEDURE dbo.DP_SAVE_REG
  @varKSparLINK      INT OUTPUT,
  @varKSparLINK_DOC  INT,
  @varKSparREG_NUM   VARCHAR(50),
  @varKSparRN        INT,	
  @varKSparREG_DATE  DATETIME  
AS

DECLARE @varKSSQLError     TINYINT,
        @varKStrancount    INT,
        @varKSEventText    VARCHAR(254),
        @varKSObjLink      INT,
        @varKSRowCount     INT,
        @varKSDocType      INT,
        @varKSShabPropCode VARCHAR(30),
        @varKSRule         INT,
        @varKSOtdLink      INT,
        @varKSVidLink      INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON

BEGIN TRAN
COMMIT TRAN
	
IF NOT EXISTS(SELECT * FROM dbo.DOCUMENTS WHERE LINK = @varKSparLINK_DOC AND DOC_TIP IN (9,10,11,16))
BEGIN
  ROLLBACK
  RETURN 5
END

SELECT @varKSDocType = DOC_TIP, @varKSVidLink = DOC_VID, @varKSOtdLink = OTD_LINK, @varKSShabPropCode = (CASE DOC_TIP
   WHEN 16 THEN 'WF_NASTR_REGNUM_IN_RULE'
   WHEN 11 THEN 'WF_NASTR_REGNUM_PRIV_RULE'
   WHEN 10 THEN 'WF_NASTR_REGNUM_CITIZ_RULE'
   WHEN 9  THEN 'WF_NASTR_REGNUM_OUT_RULE'
  END)
FROM dbo.DOCUMENTS
WHERE LINK = @varKSparLINK_DOC

CREATE TABLE #tmp4 (link INT)
INSERT INTO #tmp4 (link)
EXECUTE X_GET_NASTR @varKSShabPropCode 
SET @varKSRule = (SELECT LINK FROM #tmp4)
DROP TABLE #tmp4	

-- сквозная нумерация = 1/нумерация по отделам = 2/нумерация по отделам = 3

IF @varKSRule < 2
BEGIN
  IF EXISTS(SELECT * FROM dbo.DOCUMENTS D
              INNER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC
            WHERE (D.DOC_TIP = @varKSDocType) AND
                  (ER.RN = @varKSparRN) AND
                  DATEDIFF(YEAR,ER.REG_DATE,GETDATE()) = 0)
  BEGIN
    ROLLBACK
    RETURN 4
  END
END


IF @varKSRule = 2
BEGIN
  IF EXISTS(SELECT * FROM dbo.DOCUMENTS D
              INNER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC
            WHERE (D.DOC_TIP = @varKSDocType) AND
                  (D.OTD_LINK = @varKSOtdLink) AND
                  (ER.RN = @varKSparRN) AND
                  DATEDIFF(YEAR,ER.REG_DATE,GETDATE()) = 0)
  BEGIN
    ROLLBACK
    RETURN 4
  END
END


IF @varKSRule = 3
BEGIN
  IF EXISTS(SELECT * FROM dbo.DOCUMENTS D
              INNER JOIN dbo.EVENT_REG ER ON D.LINK = ER.LINK_DOC
            WHERE (D.DOC_TIP = @varKSDocType) AND
		  (D.DOC_VID = @varKSVidLink) AND
                  (ER.RN = @varKSparRN) AND
                  DATEDIFF(YEAR,ER.REG_DATE,GETDATE()) = 0)
  BEGIN
    ROLLBACK
    RETURN 4
  END
END

IF NOT EXISTS(SELECT * FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC) 
BEGIN	
     DECLARE @varKSUserRef INT
     SELECT @varKSUserRef = USER_REF FROM WHO_IS_WHO WHERE SID = SUSER_SID()

     INSERT INTO dbo.EVENT_REG (LINK_DOC,RN,REG_NUM,REG_DATE,EVENT_DATE,EVENT_LINK_EMPL) 
     VALUES (@varKSparLINK_DOC, @varKSparRN, @varKSparREG_NUM, @varKSparREG_DATE, GETDATE(), @varKSUserRef) 

     SELECT @varKSSQLError = @@ERROR, @varKSparLINK = SCOPE_IDENTITY()
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END

     IF EXISTS (SELECT * FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC)
	   IF NOT (dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
		OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
				IF EXISTS (SELECT * FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC)	
					AND EXISTS (SELECT * FROM dbo.EOS_JURNAL WHERE INOUT = 0 AND TYPE_M = 1 AND LINK_DOC = @varKSparLINK_DOC)
				EXEC dbo.EOS_EXPORT_REPORT @varKSparLINK_DOC 
     
END
ELSE
BEGIN		
     SELECT @varKSparLINK = LINK FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC
    
     UPDATE dbo.EVENT_REG
     SET RN = @varKSparRN, REG_NUM = @varKSparREG_NUM, REG_DATE = @varKSparREG_DATE
     WHERE LINK = @varKSparLINK
    
     SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END
    
     IF @varKSRowCount = 0
     BEGIN
          ROLLBACK
          RETURN 2
     END
END

IF @@TRANCOUNT > @varKStrancount
   COMMIT TRAN

RETURN 0





GO


GRANT EXECUTE ON dbo.[DP_SAVE_REG] 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_OUTSIDE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CALCULATE_OUTSIDE]
GO


/*
c Кейсистемс (Keysystems), 2009
Проверка междокументных КС
*/
CREATE    PROCEDURE dbo.RO_CALCULATE_OUTSIDE
	@varKSiLSF INT,
	@cProgressTable   VARCHAR(254)  = '',
	@bClearForm       BIT = 1 -- 1 - очищать форму перед заполнением, 0 - иначе.
AS

declare @ExecStr varchar(8000), @strProgressExec varchar(1000)

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 1'
    execute(@strProgressExec)
end

----------------------------------------------------------------------------------------
-- правила:
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), Group_KS varchar(20), Comment varchar(2000), OrderRule int, Group_Name varchar(254), atr_code_sr varchar(254), IsDoschet tinyint)
-- члены правила, используется для вычисления выражения:
create table #t_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), 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, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), 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_Rows_KS (Link_Rule int, Calc_Orders int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), cOrderTable varchar(254), cOrderCol varchar(10), [property] tinyint)
create table #t_Rows_KS_lsf (Link_Rule int, Calc_Orders int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), cOrderTable varchar(254), cOrderCol varchar(10), [property] tinyint)
-- записываем результат левой и правой частей:
create table #t_Result([Value] NUMERIC(20,6), Str_Val varchar(8000), Link_Rule int, orderCol int, CodeRow varchar(50), Link_Table int, Link_Col int, Link_Row int)
-- список отчетов (для хранимок):
create table #ListFormsA (lsf int, linkForm int, codeForm varchar(100), startDate datetime, cPeriod varchar(20), catr varchar(254), cbudg varchar(254), adm varchar(254))
create table #ListForms (lsf int, linkForm int, codeForm varchar(100), startDate datetime, cPeriod varchar(20), catr varchar(254), cbudg varchar(254))
-- результат хранимок (хотя в будущем этого не надо)
create table #tmp (Value float)
-- чтобы не вываливалось, когда проверяют хранимки
create table #atr (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_cur (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_empty (lsf int, atr varchar(50), str_val varchar(50))
-- для вычисления сложных правил (деление и умножение)
declare @t_temp table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), 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 #report_tables (Link_Table int, orders tinyint, Name varchar(254), link_form int, Val_Type tinyint, Link_Code_Col int)
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(50), Link_Table int)
create table #report_Dinamics(Link_SF int, Code_Row varchar(50), link_col int, float_val numeric(20,4), str_val varchar(8000), Link_Table int, OT tinyint)
create table #t_Summa(LSF int, link_col int, link_row int, Code varchar(50), summa float, str_val varchar(8000))
create table #t_Factor (Link_Rule int, OrderRow int, [sign] char(2), atr_code varchar(254), part tinyint, factor float)

Create index #IX_report_dinamics on #report_dinamics (link_sf,code_row,link_col)
Create index #IX_REPORT_SUMMA on #t_summa (link_col,link_row)

declare @MaxCalcOrders int, @CalcOrders  int, @varKSiPeriodType tinyint, @varKSiPeriodNumber tinyint, @varKSdBeginDate datetime
declare @LinkOrg int, @LinkBudg int, @LinkRule int, @atr_code varchar(254), @i int, @maxOrderRow int, @LinkF int, @toBeData tinyint
declare @nprecision float, @orderTable int, @round int, @time_begin datetime, @time_end datetime, @one tinyint, @atr varchar(254), @adm varchar(254), @OrderRow int
set @toBeData = 0 -- если данных для автозаполнения нет, но не очищать отчет
set @nprecision = 0.01
set @time_begin = getdate()
------------------------------------------------------------------------------------
-- получение правил
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение правил'', percents = 2'
    execute(@strProgressExec)
end

select top 1 @varKSiPeriodType = Period_Type, @varKSiPeriodNumber = Period_Number, @varKSdBeginDate = Begin_Date, @LinkOrg = Link_Organization, @LinkBudg = Link_Type_Svod, @LinkF = Link_Form from report_saved_forms RSF where Link_Saved_Form = @varKSiLSF


-- сохранение правил консолидации
DECLARE @LinkObject INT, @sid VARBINARY(85)
IF EXISTS(SELECT * FROM dbo.[BufferGetTableByID]('RV_CONSOLID_RULES')) 
   BEGIN 
      SELECT @LinkObject = LINK FROM dbo.S_OBJECTS WHERE code = 'KONSOLID_RULES'
      SELECT @sid = suser_sid()
      IF @LinkObject IS NOT NULL 
         BEGIN    
            DELETE dbo.S_OPTIONS WHERE OBJECT = @LinkObject AND SID = @sid AND CAST(LEFT(VALUE,10) AS INT) = @LinkF

            INSERT dbo.S_OPTIONS ([OBJECT], VALUE,	SID)
				SELECT @LinkObject, STR(@LinkF,10) + '|' + LTRIM(STR(LINK)), @sid FROM dbo.[BufferGetTableByID]('RV_CONSOLID_RULES')
         END
   END


set @varKSdBeginDate =  convert(datetime, case @varKSiPeriodType when 1 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '1231' when 2 then 
				case @varKSiPeriodNumber when 1 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0331' when 2 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0630' when 3 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0930' else LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '1231' end
				when 4 then dateadd(month, @varKSiPeriodNumber, LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0101') - 1 end)

insert #t_Rules (Link_Rule, Calc_orders, algorithm, [sign_sr], cols, [rows], Str_Rule, Group_KS, Comment, OrderRule, Group_Name, atr_code_sr, IsDoschet) exec dbo.RO_CHECK_KS_LIST_RULES default, 1, @varKSiPeriodType, @varKSiPeriodNumber, default, 1, @varKSiLSF
if not exists(select top 1  * from #t_Rules)
begin
	drop table #t_Col
	drop table #t_KS
	drop table #t_Rules
	drop table #t_Rows_KS
	drop table #t_Result
	drop table #ListFormsA
	drop table #ListForms
	drop table #t_Rows_Static
	drop table #tmp
	drop table #report_dinamics
	drop table #t_Summa
	drop table #atr
	drop table #atr_cur
	drop table #atr_empty
	drop table #report_tables
	return 0
end
-- предварительные действия, которые можно сделать вне цикла
insert #t_Rows_KS (Link_Rule, Calc_Orders, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, 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, Ru.Calc_orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, (case isnull(Ro.period_year,0) when 0 then case period_type when 1 then convert(datetime, LTRIM(STR(YEAR(dateadd(month, Ro.period_form, @varKSdBeginDate)))) + '1231') else dateadd(month, Ro.period_form, @varKSdBeginDate + 1) -1 end  else Ro.begin_date end) , Ro.budg_code, Ro.atr_code, 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, Ru.cols, Ru.[rows], '№' + isnull(ltrim(STR(RT.orders)),'') + ' (' + RTRIM(RT.Name) + ')', '№' + isnull(ltrim(str(RC.export_order)),''), Ro.[property]
from (select distinct Link_Rule, Calc_orders, rows, cols, algorithm from #t_Rules) Ru left join report_control_rows Ro (NOLOCK) on Ro.Link_Rule = Ru.Link_Rule
	left join report_tables RT on Ro.Link_Table = RT.Link_Table
	left join report_coloumns RC on RC.Link_Col = Ro.Link_Col

update #t_Rows_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))
where val_type = 2
update #t_Rows_KS
set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
where val_type = 2

insert #report_tables (Link_Table, orders, Name, link_form, Val_Type, Link_Code_Col)
select Link_Table, orders, Name, link_form, Val_Type, Link_Code_Col
from report_tables (NOLOCK)
where (Link_Table in (select distinct Link_Table from #t_Rows_KS where Link_Table is NOT NULL)	)	
		or 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, '№' + LTRIM(STR(Export_Order))
from #report_coloumns RC
where dbo.RO_AccessColByLink(RC.Link_COl) > 0

insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol, cOrderCol)
select Link_Col, Name, Link_Table, Val_len, orders, '№' + LTRIM(STR(Export_Order))
from #report_coloumns RC
where Link_Table in (select distinct Link_Table from #t_Rows_KS where Link_Table is NOT NULL and part = 1)
	and not exists(select top 1 * from #t_Col C where C.Link_Col = RC.Link_Col)

select @round = max(Val_Len) from #t_Col

insert #t_Rows_Static(Link_Row, Code, Link_Table)
select Link_Row, Code, Link_Table 
from i_report_rows 
where Link_Table in (select Link_Table from #report_tables where Val_Type = 0)

set @adm = rtrim(isnull(dbo.RN_GET_ATR_VALUE(@varKSiLSF, 'REPORTS_ATR_ADM'), ''))

----------------------------------------------------------------------------------------
-- получение слагаемых с lsf (отчеты получаем как обычно) и размножение по атрибутам

set @LinkBudg = isnull(@LinkBudg, 0)

declare @t_Budg table (Link int) -- бюджеты берутся только подведомственных
insert @t_Budg
select Link
from kl_budg_type
where code in (select distinct budg_code from #t_Rows_KS where budg_code <> '') and dbo.RO_SVOD_TREE_POTOMOK_Org_Budg(@LinkOrg, Link, @LinkOrg, @LinkBudg) = 1

insert #t_Rows_KS_lsf (Link_Rule, Calc_Orders, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property])
select Ro.Link_Rule, Ro.Calc_Orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#'), RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows], [property]
from #t_Rows_KS Ro left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, @LinkBudg) RSF on Ro.Link_Form = RSF.Link_Form and RSF.begin_date = Ro.begin_date and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end
where part=1 and budg_code = '' 

-- слагаемые, для которых указан бюджет
insert #t_Rows_KS_lsf (Link_Rule, Calc_Orders, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property])
select Ro.Link_Rule, Ro.Calc_Orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#'), RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows], [property]
from #t_Rows_KS Ro left join kl_budg_type B on B.code = Ro.budg_code	
	left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, NULL) RSF on Ro.Link_Form = RSF.Link_Form and RSF.begin_date = Ro.begin_date  and RSF.Link_Type_Svod = B.Link and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end and Link_Type_Svod in (select Bu.Link from @t_Budg Bu)
where part = 1 and budg_code <> ''

insert #t_Rows_KS_lsf (Link_Rule, Calc_Orders, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property])
select Ro.Link_Rule, Ro.Calc_Orders, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#'), RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows], [property]
from #t_Rows_KS Ro left join kl_budg_type B on B.code = Ro.budg_code	
	left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, NULL) RSF on Ro.Link_Form = RSF.Link_Form and RSF.begin_date = Ro.begin_date  and RSF.Link_Type_Svod = B.Link and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end and Link_Type_Svod in (select Bu.Link from @t_Budg Bu)
where part = 0 and budg_code <> ''

insert #ListFormsA (lsf, linkForm, codeForm, startDate, cPeriod, catr, cbudg, adm)
	select SF.lsf, RSF.Link_Form, RF.code, RF.start_Date, 
		case RSF.Period_Type when 1 then LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' год' 
				when 2 then LTRIM(STR(Period_Number)) + ' квартал ' + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				when 4 then case Period_Number 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   + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				end,
			RSF.atr, case when budg_code <> '' then B.Name else '' end, dbo.RN_GET_ATR_VALUE(SF.lsf, 'REPORTS_ATR_ADM')
	from (select lsf, max(budg_code) budg_code from #t_Rows_KS_lsf where lsf is NOT NULL group by lsf union select @varKSiLSF, '' WHERE NOT EXISTS(select * from #t_Rows_KS_lsf WHERE lsf = @varKSiLSF)) SF
		left join report_saved_forms RSF on SF.lsf = RSF.Link_Saved_Form
		left join report_forms RF on RF.Link_Form = RSF.Link_Form
		left join dbo.kl_budg_type B on RSF.Link_Type_Svod = B.Link
      
	insert #t_summa (lsf, link_col, link_row, code, summa, str_val)
	select RS.link_saved_form, RS.link_col, RS.link_row, case when @adm = '' then LF.adm else '' end + R.code, RS.summa, ''
	from report_summa_all RS (NOLOCK) left join #t_Rows_Static R on RS.Link_Row = R.Link_Row
		inner join #ListFormsA LF on RS.Link_Saved_Form = LF.lsf
		left join #report_tables RT on R.Link_Table = RT.Link_Table
	where RT.Val_Type = 0

	insert #t_summa (lsf, link_col, link_row, code, summa, str_val)
	select RS.link_saved_form, RS.link_col, RS.link_row, case when @adm = '' then LF.adm else '' end + R.code, 0, RS.str_val
	from report_string_all RS (NOLOCK) left join #t_Rows_Static R on RS.Link_Row = R.Link_Row
		inner join #ListFormsA LF on RS.Link_Saved_Form = LF.lsf
		left join #report_tables RT on R.Link_Table = RT.Link_Table
	where RT.Val_Type = 0


	insert #report_dinamics(Link_SF, Code_Row, link_col, float_val, str_val, Link_Table, OT)
	select Link_SF, case when @adm = '' then LF.adm else '' end + Code_Row, D.link_col, float_val, str_val, C.Link_Table, RT.orders
	from report_dinamics_all D (NOLOCK) left join #t_Col C on D.Link_Col = C.Link_Col
			inner join #ListFormsA LF on D.Link_SF = LF.lsf
		left join #report_tables RT on C.Link_Table = RT.Link_Table
	where RT.Val_Type = 1

--select * from #report_dinamics
--select * from #t_summa
------------------------------------------------------------------------------

select @MaxCalcOrders = max(Calc_Orders), @CalcOrders = min(Calc_orders) from #t_Rules


if @MaxCalcOrders = 0
	set @MaxCalcOrders = 1

while @CalcOrders <= @MaxCalcOrders
begin
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+ @cProgressTable + ' set msg = ''Расчет №' + STR(@CalcOrders) + ''', percents = ' + convert(varchar(10), 5 + convert(int, @CalcOrders*90/(@MaxCalcOrders + 1) ))
		execute(@strProgressExec)
	end
	----------------------------------------------------------------------------------------
	-- получение слагаемых с lsf (отчеты получаем как обычно)
	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property])
	select Ro.Link_Rule, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, Ro.atr_code, Ro.lsf, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows], [property]
	from #t_Rows_KS_lsf Ro 
	where Calc_Orders = @CalcOrders 

	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property])
	select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, dbo.[RA_GETWORDNUM](atr_code,1,'#'), 
            case when begin_date = @varKSdBeginDate THEN  @varKSiLSF ELSE NULL end, 
            Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], [property]
	from #t_Rows_KS
	where part = 0 and Calc_Orders = @CalcOrders AND [budg_code] = ''

  
   delete #t_KS WHERE link_RULE IN (SELECT link_rule FROM #t_KS WHERE part = 0 AND lsf IS NULL)
  

	set  @CalcOrders =  @CalcOrders + 1

	if not exists(select top 1 * from #t_KS)
	BEGIN
      CONTINUE
	end


	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@CalcOrders-1)*100/@MaxCalcOrders + 10 + 20/@MaxCalcOrders))
		execute(@strProgressExec)
	end

	-----------------------------------------------------------------------
	-- теперь добавляем атрибуты
	exec dbo.RO_RAZMNOJ_KS_ATR @From = 1
	-----------------------------------------------------------------------
	-- удаление данных, если это нужно
	if @bClearForm = 1 and @toBeData = 0
	begin
		if exists(select top 1 * from #t_KS where part = 1 and (lsf is NOT NULL and isnull(lsf, 0) <> @varKSiLSF or Val_type = 2)) -- найден хотя бы один отчет, из которого будет идти автозаполнение
		BEGIN
         -------------- перед затиранием удаляем в корзину
         EXEC dbo.RO_RECYCLE_SAVE @varKSiLSF
         
			set @toBeData = 1
			delete report_summa
			where Link_Saved_Form = @varKSiLSF

			delete report_dinamics 
			where Link_SF = @varKSiLSF 

			delete #t_summa
			where lsf = @varKSiLSF

			delete #report_dinamics 
			where Link_SF = @varKSiLSF 
		end 
		else
			continue
	end
	------------------------------------------------------------------------------------------
	exec dbo.RO_RAZMNOJ_KS_OUTSIDE -- размножение правил для фильтров и знака '^'
	------------------------------------------------------------------------------------------
	insert #t_KS_LEft 
	select *
	from #t_KS
	where part = 0

	delete #t_KS where part = 0

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@CalcOrders-1)*100/@MaxCalcOrders + 10 + 50/@MaxCalcOrders))
		execute(@strProgressExec)
	end
	-- 	вычисляем правила
	-- обнуляем простые правила 
	update #t_Summa
	set summa = 0, str_val = ''
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 0) K
	where #t_Summa.lsf = @varKSiLSF and #t_Summa.Link_Col = K.Link_Col and #t_Summa.Link_Row = K.Link_Row
	
	update #report_dinamics
	set float_val = 0, str_val = ''
	from (select * from #t_KS_Left where algorithm = 1 and Val_Type = 3) K
	where #report_dinamics.Link_SF = @varKSiLSF and #report_dinamics.Link_Col = K.Link_Col and #report_dinamics.Code_Row = K.Code_Row

	insert #t_Result([Value], Str_Val, 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), max(isnull(S.Str_Val, D.Str_Val)), K.Link_Rule, orderCol, CodeRow
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Col = K.Link_Col and S.Link_Row = K.Link_Row left join #t_Rows_Static RS on RS.Link_Row = K.Link_Row
		left join #report_dinamics D on D.link_sf = K.lsf and D.Link_Col = K.Link_Col and D.Code_Row = K.Code_Row
	where algorithm = 1 -- простое правило
	group by K.Link_Rule, orderCol, CodeRow

	-- правило размножения для диапозона колонок 
	update #t_Summa
	set summa = 0, str_val = ''
	from #t_Summa S left 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.lsf = @varKSiLSF and S.Link_Row = K.Link_Row and (charindex(',' + rtrim(ltrim(str(RC.orderCol))) + ',', ','+cols+',') > 0 or cols = '')

	update #report_dinamics
	set float_val = 0, str_val = ''
	from #report_dinamics S left 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.Link_SF = @varKSiLSF and 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([Value], Str_Val, 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), max(isnull(S.Str_Val, D.Str_Val)), Link_Rule, isnull(RC1.orderCol, RC2.orderCol), CodeRow
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Row = K.Link_Row
		left join #t_Col RC1 on S.link_col = RC1.link_col
		left join #report_dinamics D on D.link_sf = K.lsf and D.Code_Row = K.Code_Row and D.Link_Table = K.Link_Table
		left join #t_Col RC2 on D.link_col = RC2.link_col
	where algorithm = 2 and (charindex(',' + rtrim(ltrim(str(isnull(RC1.orderCol,RC2.orderCol)))) + ',', ','+cols+',') > 0 or cols = '')
	group by Link_Rule, isnull(RC1.orderCol, RC2.orderCol), CodeRow
   
	-- правило размножения для всех строк 
	-- обнуляем
	update #t_Summa
	set summa = 0, str_val = ''
	from #t_Summa S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 0) K
	where S.lsf = @varKSiLSF and S.Link_Col = K.Link_Col
	
	update #report_dinamics
	set float_val = 0, str_val = ''
	from #report_dinamics S, (select * from #t_KS_Left where algorithm = 3 and Val_Type = 3) K
	where S.Link_SF = @varKSiLSF and S.Link_Col = K.Link_Col

	insert #t_Result([Value], Str_Val, 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), max(isnull(S.Str_Val, D.Str_Val)), Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Col = K.Link_Col
		left join #report_dinamics D on D.link_sf = K.lsf and D.Link_Col = K.Link_Col 
		left join #ListFormsA LF on K.lsf = LF.lsf
	where algorithm = 3 --and coalesce(S.Code, D.Code_Row, '') <> ''
	group by Link_Rule, orderCol, coalesce(S.Code, D.Code_Row, '')
   
	--having case when @adm = '' then LF.adm else @adm end  + coalesce(S.Code, D.Code_Row, '') <> ''
	-- диапозон строк 
--select * from #t_KS	
	while exists(select top 1 * from #t_KS where algorithm  = 4 and Link_Rule > 0) --and (@i < 2)
	begin
		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.lsf = ' + STR(@varKSiLSF) + ' and S.Link_Col = K.Link_Col and ' + REPLACE([rows], 'COL(', 'dbo.RO_COL_Static(S.lsf, K.Link_Table, S.Link_Row,') + '
	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_SF = ' + STR(@varKSiLSF) + ' and RD.Link_Col = K.Link_Col  and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,K.Link_Table, RD.Code_Row,') + ')
insert #t_Result([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 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end), Link_Rule, orderCol, S.Code
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Col = K.Link_Col
	where Val_Type = 0 and Link_Rule = ' + STR(Link_Rule) + ' and ' + REPLACE([rows], 'COL(', 'dbo.RO_COL_Static(K.lsf, K.Link_Table, S.Link_Row,') + '
	group by Link_Rule, orderCol, S.Code
	having  S.Code <> ''''
insert #t_Result([Value], Link_Rule, orderCol, CodeRow)
	select sum(case Val_Type 
					when 3 then  case [sign] -- динамическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(RD.float_val,0)*px else isnull(abs(RD.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(RD.float_val, 0)*px else -isnull(abs(RD.float_val), 0)*px end
						end 
					when 1 then  case [sign] -- константа
							when ''+'' then K.Factor
							else -K.Factor
						end 
					else 0
				end),  Link_Rule, orderCol, ' + case when @adm = '' then ' LF.adm + ' else ''''' + '  end  + 'RD.Code_Row 
	from #t_KS K left join #report_dinamics RD on RD.link_sf = K.lsf and RD.Link_Col = K.Link_Col left join #ListFormsA LF on LF.lsf = RD.link_sf
	where Link_Rule = ' + STR(Link_Rule) + ' and (' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,K.Link_Table, RD.Code_Row,') + ')
	group by Link_Rule, orderCol, ' + case when @adm = '' then ' LF.adm + ' else ''''' + '  end  + 'RD.Code_Row 
	having ' + case when @adm = '' then ' LF.adm + ' else ''''' + '  end  + 'RD.Code_Row  <> '''''
		from #t_KS
		where algorithm = 4 and Link_Rule > 0
		

		execute(@ExecStr)
		update #t_KS set Link_Rule = -Link_Rule where Link_Rule = @LinkRule 
	end

	set @ExecStr = ''

	select @ExecStr = @ExecStr + '
	update #t_Result
	set CodeRow = ' + isnull(REPLACE(dbo.[RN_GET_FORMULA_CODE_ROW_f](Link_Table, 'AUTOFILL_CODE='), '$CODE$', 'CodeRow'), 'CodeRow') + '
	from (select distinct Link_Rule, Link_Table from #t_KS_Left) K
	where #t_Result.Link_Rule = K.Link_Rule and K.Link_Table = ' + STR(Link_Table)
	from (select distinct Link_Table from #t_KS_Left) K
	where dbo.[RN_GET_FORMULA_CODE_ROW_f](Link_Table, 'AUTOFILL_CODE=') <> ''
         AND EXISTS(SELECT TOP 1 * FROM #ListFormsA WHERE adm <> '') 

	if @ExecStr <> ''
		execute(@ExecStr)

	set ansi_warnings OFF
    SET ARITHABORT OFF
    SET ARITHIGNORE OFF
	-- хранимки - теперь только одна хранимка в одном правиле!!!
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@CalcOrders-1)*100/@MaxCalcOrders + 10 + 70/@MaxCalcOrders))
		execute(@strProgressExec)
	end

	while exists(select top 1 * from #t_KS where algorithm = 9 )
	begin
		select top 1 @LinkRule = Link_Rule, @ExecStr = REPLACE(Exec_Proc, '#LINK_SAVED_FORM', @varKSiLSF)
		from #t_KS
		where algorithm = 9 and Val_Type = 2 
			
		insert #tmp execute(@ExecStr)
		
		insert #t_Result([Value], Link_Rule, orderCol, CodeRow)
		select (select top 1 Value from #tmp), @LinkRule, 0, ''
		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 <> ''))
		
		delete #t_KS where Link_Rule = @LinkRule 
	end

	update #report_dinamics
	set Link_Table = LT,
		Str_Val = isnull(Str_val, ''),
		float_val = isnull(float_val, 0)
	from (select Link_Table as LT, Link_Col as LC from #report_coloumns) RC
	where LC = Link_Col

	delete #t_KS
	where algorithm in (1,2,3,4, 9)
    set ansi_warnings ON
    SET ARITHABORT ON
    SET ARITHIGNORE ON

	-- деление и умножение и т.д.
	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 else case when K.[property] & 2 = 0 then isnull(RD.Float_Val, 0)*px else isnull(abs(RD.Float_Val), 0)*px end end
	from #t_KS K
		left join #t_summa RS on K.lsf = RS.lsf and K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #report_dinamics RD on RD.link_sf = K.lsf and K.Link_Col = RD.Link_Col and RD.Code_Row = K.Code_Row

	-- чтобы результирующия строка была с администратором, если надо
	update #t_KS
	set CodeRow = case when @adm = '' then LF.adm else @adm end  + CodeRow
	from #ListFormsA LF
	where #t_KS.CodeRow <> '' and LF.lsf = #t_KS.lsf

	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 K.atr_code = K2.atr_code 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 K.atr_code = K2.atr_code and CodeRow <> '')

	-- и для вычисления нужно добавть операнды, которые не размножились
	insert #t_KS
	select K.Link_Rule, K.OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, 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 ([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
--select 	@maxOrderRow
	while @i<=@maxOrderRow
	begin
		update #t_Result
		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 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

--select * from #t_KS
--select * from #t_Result	
----------------------------
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@CalcOrders-1)*100/@MaxCalcOrders + 10 + 80/@MaxCalcOrders))
		execute(@strProgressExec)
	end

	-- записываем результат
	update #t_Result
	set Link_Col = K.Link_Col,
		Link_Table = K.Link_Table,
		Value = case when Ru.IsDoschet & 16 = 0 then round(#t_Result.Value, case when C.Val_Len > 4 then 4 else C.Val_Len end) else abs(round(#t_Result.Value, case when C.Val_Len > 4 then 4 else C.Val_Len end)) end
	from #t_KS_Left K join #t_Col C on K.Link_Col = C.Link_Col  join #t_Rules Ru on Ru.Link_Rule = K.Link_Rule
	where #t_Result.orderCol = 0 and K.Link_Rule = #t_Result.Link_Rule 


	update Re
	set Link_Col = C.Link_Col,
		Link_Table = K.Link_Table,
		Value = case when Ru.IsDoschet & 16 = 0 then round(Re.Value, case when C.Val_Len > 4 then 4 else C.Val_Len end) else abs(round(Re.Value, case when C.Val_Len > 4 then 4 else C.Val_Len end)) end
	from #t_Result Re join #t_KS_Left K on K.Link_Rule = Re.Link_Rule
			join #t_Col C on K.Link_Table = C.Link_Table and Re.orderCol = C.orderCol
			join #t_Rules Ru on Ru.Link_Rule = K.Link_Rule


	update #t_Result
	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
         LEFT JOIN #report_tables rt ON rt.[Link_Table] = K.[Link_Table]
	where isnull(#t_Result.CodeRow, '') = '' and rt.Val_Type = 0 and K.Link_Rule = #t_Result.Link_Rule

	update #t_Result
	set Link_Row = R.Link_Row
	from #t_KS_Left K left join #t_Rows_Static R on K.Link_Table = R.Link_Table
         LEFT JOIN #report_tables rt ON rt.[Link_Table] = K.[Link_Table]
	where isnull(#t_Result.CodeRow, '') <> '' and rt.[Val_Type] = 0 and K.Link_Rule = #t_Result.Link_Rule and R.Code = #t_Result.CodeRow

	update #t_Result
	set CodeRow = K.Code_Row
	from #t_KS_Left K 
	where isnull(#t_Result.CodeRow, '') = '' and K.Val_Type = 3 and K.Link_Rule = #t_Result.Link_Rule --and K.orderCol = #t_Result.orderCol
   
   INSERT  #t_Result ([Value], [Str_Val], [Link_Rule], [orderCol], [CodeRow], [Link_Table],[Link_Col],[Link_Row])
	SELECT max(#t_Result.[Value]), max(#t_Result.[Str_Val]), #t_Result.[Link_Rule], 0, R.Code_Row, K.[Link_Table],  K.LINK_COL, NULL 
	from #t_Result join #t_KS_Left K ON K.Link_Rule = #t_Result.Link_Rule left join #report_dinamics R on K.Link_Table = R.Link_Table
	where isnull(#t_Result.CodeRow, '') = '' and K.Val_Type = 3 AND K.algorithm = 3 AND #t_Result.[Value] <> 0
   GROUP  BY #t_Result.[Link_Rule], R.Code_Row, K.[Link_Table],  K.LINK_COL

	delete #t_Result where Link_Col is NULL or (Link_Row is NULL and isnull(CodeRow, '') = '') or Value is NULL
   
   --select * from #t_Result order by Link_Rule, orderCol, CodeRow


	update #report_dinamics
	set float_val = R.Value,
		str_val = R.str_val
	from #t_Result R
	where #report_dinamics.Link_SF = @varKSiLSF and 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 @varKSiLSF, R.CodeRow, R.Link_Col, max(R.Value), max(R.Str_val), max(R.Link_Table)
	from #t_Result R inner join #report_tables RT on R.Link_Table = RT.Link_Table
	where RT.Val_Type = 1 and R.Link_Row is NULL and not exists(select top 1 * from #report_dinamics S where S.Link_SF = @varKSiLSF and S.Link_Col = R.Link_Col and R.CodeRow = S.Code_Row)
	group by R.CodeRow, R.Link_Col
		

--select * from #report_dinamics where code_row = '049001050008420202002020000151' and link_sf = @varKSiLSF

	update #t_summa
	set Summa = R.Value, str_val = R.str_val
	from #t_Result R
	where #t_summa.lsf = @varKSiLSF and 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, str_val)
	select @varKSiLSF, R.Link_Col, R.Link_Row, max(R.CodeRow), max(R.Value), max(R.str_val)
	from #t_Result R 
	where R.Link_Row is NOT NULL and not exists(select top 1 * from #t_summa S where S.lsf = @varKSiLSF and 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_Result	
	truncate table #t_KS
	truncate table #t_KS_Left

	--truncate table #ListFormsA
end

if @toBeData = 0 and @bClearForm = 1
begin
			select 'Не найдено ни одного отчета-источника для автозаполнения!' as Txt
			drop table #t_Col
			drop table #t_KS
			drop table #t_Rules
			drop table #t_Rows_KS
			drop table #t_Result
			drop table #ListFormsA
			drop table #ListForms
			drop table #t_Rows_Static
			drop table #tmp
			drop table #report_dinamics
			drop table #t_Summa
			drop table #atr
			drop table #atr_cur
			drop table #atr_empty
			drop table #report_tables
			return 0
end

-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Сохранение данных статических таблиц'', percents = 80'
         execute(@strProgressExec)
 end

delete #t_Summa
where lsf <> @varKSiLSF

delete #report_dinamics
where Link_SF <> @varKSiLSF

delete #report_tables
where Link_Form <> @LinkF

update report_summa
set summa = isnull(RS.summa,0)
from #t_summa RS
where Link_saved_form = @varKSiLSF 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 @varKSiLSF, Link_Col, Link_Row, isnull(max(Summa),0)
from #t_summa RS
where not exists(select top 1 * from report_summa RS1 where link_saved_form = @varKSiLSF and RS1.Link_Col = RS.Link_Col and RS.Link_Row = RS1.Link_Row)
group by Link_Col, Link_Row

update report_string
set str_val = isnull(RS.str_val,'')
from #t_summa RS
where Link_saved_form = @varKSiLSF and RS.Link_Col = report_string.Link_Col and RS.Link_Row = report_string.Link_Row

insert report_string (Link_Saved_form, Link_Col, Link_Row, Str_Val)
select @varKSiLSF, Link_Col, Link_Row, isnull(max(Str_Val),'')
from #t_summa RS
where not exists(select top 1 * from report_string RS1 where link_saved_form = @varKSiLSF and RS1.Link_Col = RS.Link_Col and RS.Link_Row = RS1.Link_Row)
group by Link_Col, Link_Row

-------------------------------------------------------------------------------
if @cProgressTable <>'' begin
  set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Приведение кодовых строк по маске и загрузка данных'', percents = 85'
         execute(@strProgressExec)
 end

if @bClearForm = 1
BEGIN
	exec dbo.[RO_KS_SET_MASK] @varKSiLSF
end
else begin
	update report_dinamics
	set float_val = isnull(RD.float_val,0),
		str_val = isnull(RD.str_val,'')
	from report_dinamics D inner merge join #report_dinamics RD on D.Link_SF = @varKSiLSF and RD.Link_Col = D.Link_Col and RD.Code_Row = D.Code_Row

	delete report_dinamics where Link_SF = @varKSiLSF and isnull(Float_val, 0) = 0 and isnull(Str_Val, '') = ''

	insert report_dinamics (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
	select @varKSiLSF, Link_Col, Code_Row, isnull(max(Float_Val),0), isnull(max(Str_Val),'')
	from #report_dinamics RD
	where (float_val <> 0 or exists(select top 1 * from #report_dinamics RD1 where RD.Code_Row = RD1.Code_Row and RD.Link_Table = RD1.Link_Table and float_val <> 0)) and not exists(select top 1 * from report_dinamics RD1 where RD1.Link_SF = @varKSiLSF and RD1.Link_Col = RD.Link_Col and RD1.Code_Row = RD.Code_Row)
	group by Link_Col, Code_Row

	if object_id('tempdb..#t_CodeRow') is NOT NULL
		drop table #t_CodeRow
	create table #t_CodeRow (Code varchar(50))
	create table #t_Abcent_Code(Code varchar(100))
	declare @liORDER int, @liLINK_TABLE int

	DECLARE curTable CURSOR FOR
	   SELECT [ORDERS], [LINK_TABLE]
	   FROM dbo.[REPORT_TABLES]
	   WHERE [LINK_FORM] = @LinkF
	   
	OPEN curTable

	FETCH NEXT 	FROM curTable
	INTO @liORDER,  @liLINK_TABLE


	WHILE @@FETCH_STATUS=0
	BEGIN
		insert #t_CodeRow
		select distinct Code_Row
		from report_dinamics where link_sf = @varKSiLSF and Link_Col in (select Link_Col from report_coloumns where Link_Table = @liLINK_TABLE)

		exec dbo.RN_FILL_WITH_CodeRow @varKSiLSF, @LinkF, @liORDER

		truncate table #t_CodeRow

		EXEC dbo.[RN_FILL_WITH_DICT] @varKSiLSF, NULL,	@liORDER, @varKSiNotUpdate = 0, @varKSTableAbcentCode = '#t_Abcent_Code'

		delete report_dinamics
		where Link_SF = @varKSiLSF and exists(select top 1 * from #t_Abcent_Code A where A.Code = Code_Row) and Link_Col in (select Link_Col from #report_coloumns where Link_Table = @liLINK_TABLE)
	    
	   FETCH NEXT FROM curTable
	   INTO @liORDER,@liLINK_TABLE
	END

	CLOSE curTable
	DEALLOCATE curTable

	drop table  #t_Abcent_Code
	drop table #t_CodeRow	
	EXEC dbo.[RN_SPLIT_CODE_ROW] @varKSiLSF

end

drop table #report_coloumns
drop table #t_Col
drop table #t_KS
drop table #t_Rules
drop table #t_Rows_KS
drop table #t_Result
drop table #ListFormsA
drop table #ListForms
drop table #t_Rows_Static
drop table #tmp
drop table #report_dinamics
drop table #t_Summa
drop table #atr
drop table #atr_cur
drop table #atr_empty
drop table #report_tables

declare @varKSEventStr2 varchar(100), @varKSEventStr varchar(8000), @varKSLink_Task int

if @bClearForm = 1
begin
	SET @varKSEventStr2 = 'Автозаполнение сохраненной формы'
end
else
	SET @varKSEventStr2 = 'Консолидация сохраненной формы'
--select * from #Rules

create table #itables (link_table int)
exec dbo.RO_CALCULATE_INSIDE @varKSiLSF
drop table #itables --(link_table int)


select @varKSLink_Task = link_task from user_info
select @varKSEventStr = 'Форма: ' + rtrim(code) + ' Период: ' + 
	 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 = @varKSiLSF
	
exec RO_GENERATEEVENT @varKSEventStr2, @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSiLSF


--drop table #Rules
GO
GRANT ALL ON dbo.[RO_CALCULATE_OUTSIDE] 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.[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(50)='''',
@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(50),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(50),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(50),'''') 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 * FROM #tabTable6 

        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(50),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(50),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(50),'''') 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 

        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(50)='''',
@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].[RN_EXPORT_REPORT_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_EXPORT_REPORT_KBK]
GO
/*

  © Кейсистемс (Keysystems), 2006
  Возвращает список атрибутов
*/


CREATE       PROCEDURE dbo.RN_EXPORT_REPORT_KBK
    @LinkTree int , -- линк узла
    @del int=0, --выгружать с удалением предыдущего справочника
    @header int=0 -- выгружать только заголовок
AS

--выгружаем дерево заголовков
create table #link_header (ord int identity(1,1),link int)
create table #res (ord int identity(1,1),txt varchar(7000))
declare @count int,@i int,@code varchar(50),@code_form varchar(50),@name varchar(250),@link_self int,@code_self varchar(50)
create table #tmp (link int IDENTITY,cstr varchar(8000), Link_Self int default (0))

insert #link_header
select  @LinkTree
--select coalesce(M.link,L.link,K.link,J.link,H.link,G.link,F.link,E.link,D.link,C.link,B.link,A.link) as link FROM report_kbk A 
--left join report_kbk B ON A.link=B.link_self
--left join report_kbk C ON B.link=C.link_self
--left join report_kbk D ON C.link=D.link_self
--left join report_kbk E ON D.link=E.link_self
--left join report_kbk F ON E.link=F.link_self
--left join report_kbk G ON F.link=G.link_self
--left join report_kbk H ON G.link=H.link_self
--left join report_kbk J ON H.link=J.link_self
--left join report_kbk K ON J.link=K.link_self
--left join report_kbk L ON K.link=L.link_self
--left join report_kbk M ON L.link=M.link_self
--where A.link=@linktree
while @@ROWCOUNT<>0
    begin
        insert #link_header
        select link from report_kbk A where A.link_self in (select link from #link_header B) and not exists(select * from  #link_header B where A.link=B.link)
    end


set @count=0
select @count=count(*) from #link_header

set @i=1
while @i<=@count
    begin
        select @Code=Code,@Code_Form=Code_Form,@Name=Name from report_kbk where link=(select link from #link_header where ord=@i)
        insert #res (txt)
        select 'exec RN_SAVE_REPORT_KBK 0,'''+rtrim(@code)+''',0,'''+rtrim(@name)+''','''+rtrim(@code_form)+'''
GO'
        set @i=@i+1
    end

--расстановка link_self
set @i=1
while @i<=@count
    begin
        select @Code=Code,@Code_Form=Code_Form,@Name=Name,@link_self=link_self from report_kbk where link=(select link from #link_header where ord=@i)
        set @code_self=''
        select @code_self=code from report_kbk where link=@link_self
        insert #res (txt)
        select
'
declare @link_self int
 select @link_self=link from report_kbk where code='''+rtrim(@code_self)+''' and code_form=''HEADER''
 exec RN_SAVE_REPORT_KBK 0,'''+rtrim(@code)+''',@link_self,'''+rtrim(@name)+''','''+rtrim(@code_form)+'''
GO'
        set @i=@i+1
    end

if @header=0
begin
--выгружаем справочник
set @i=1
while @i<=@count
    begin

        select @Code=Code,@Code_Form=Code_Form,@Name=Name,@link_self=link_self from report_kbk where link=(select link from #link_header where ord=@i)
IF @del=0
    begin
        insert #res (txt)
        SELECT txt
        FROM (
        select 'declare @link_self int, @link int 
'+
        case when isnull(A.link_self,0)<>0 then 'select @link_self = Link from report_kbk where Code_Form = ''' + rtrim(K2.code_form) + ''' and  Code = ''' + isnull(K2.Code,'') +  ''' and begin_date ' + case when K2.begin_date is NULL then ' is NULL and end_date ' else '=''' + convert(varchar(10), K2.begin_date, 112) + ''' and end_date ' end + case when K2.end_date is NULL then ' is NULL' else '=''' + convert(varchar(10), K2.end_date, 112) + '''' end + '' else 'set @link_self=0' end +
'
exec RN_SAVE_REPORT_KBK @link output,'''+RTRIM(A.code)+''',@link_self,'''+REPLACE(RTRIM(A.name), '''', '''''') +''','''+RTRIM(A.code_form)+''',0,'''+REPLACE(RTRIM(A.code_str), '''', '''''')+''','+LTRIM(STR(ISNULL(A.property,0)))+','''+REPLACE(RTRIM((ISNULL(A.add_info,''))), '''', '''''')+''','''+REPLACE(rtrim(isnull(A.long_name,'')), '''', '''''')+''',' + isnull('''' + convert(varchar(8), A.begin_date, 112) + ''',', 'NULL,') + isnull('''' + convert(varchar(8), A.end_date, 112) + '''', 'NULL') + '
delete dbo.report_kbk_hist where link_up = @link
' AS txt, A.link, 1 AS orders
        from report_kbk A
           left join report_kbk K2 on A.Link_Self = K2.Link
        where A.code_form=@code 
        UNION ALL  
        select 'exec dbo.RO_KBK_HIST_SAVE @link, ''' + RTRIM(rkh.[NAME]) + ''', ''' + RTRIM(rkh.[LONG_NAME]) + ''', ''' + CONVERT(VARCHAR(10), rkh.[DATE],112) + '''
        ' AS txt, A.link, 2 AS orders
        from report_kbk A
           JOIN [dbo].[REPORT_KBK_HIST] rkh ON rkh.[LINK_UP] = A.[link]  
        where A.code_form=@code 
        UNION ALL 
        select '
GO' AS txt, A.link, 3 AS orders
        from report_kbk A
        where A.code_form=@code) A 
        order by link, orders
        
        set @i=@i+1
    end
ELSE
begin    
    insert #res (txt)
select 
'delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= '''+@code+''')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= '''+@code+''')
delete report_kbk where code_form= '''+@code+'''
declare @LS int'
delete #tmp 

insert #tmp (Link_Self, cstr)
        select K.Link,
'set @LS = 0
select @LS = Link from report_kbk where Code_Form = ''' + rtrim(K2.code_form) + ''' and  Code = ''' + isnull(K2.Code,'') +  ''' and begin_date ' + case when K2.begin_date is NULL then ' is NULL and end_date ' else '=''' + convert(varchar(10), K2.begin_date, 112) + ''' and end_date ' end + case when K2.end_date is NULL then ' is NULL' else '=''' + convert(varchar(10), K2.end_date, 112) + '''' end + '
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '''+rtrim(K.code)+''',@LS,'''+rtrim(K.code_form)+''',1,'''+REPLACE(rtrim(K.name), '''', '''''')+''',0,'''+REPLACE(rtrim(K.code_str), '''', '''''')+''','+ltrim(str(isnull(K.property,0)))+','''+REPLACE(rtrim(isnull(K.add_info,'')), '''', '''''')+''','''+REPLACE(rtrim(isnull(K.long_name,'')), '''', '''''') + ''', ' + isnull('''' + convert(varchar(8), K.begin_date, 112) + ''',', 'NULL,') + isnull('''' + convert(varchar(8), K.end_date, 112) + '''', 'NULL') + ',' + LTRIM(STR(isnull(K.orders,0))) + char(13)+char(10) 
from report_kbk K  left join report_kbk K2 on K.Link_Self = K2.Link 
where K.code_form=@code 
and not exists(select top 1 * from report_kbk K1 where K1.code_form=@code and isnull(K1.link, 0) = isnull(K.link_self, 0))
and isnull(K.link_self, 0) <> 0
order by K.code

insert #tmp (Link_Self, cstr)
        select K.Link,
'insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '''+rtrim(K.code)+''',0,'''+rtrim(K.code_form)+''',1,'''+REPLACE(rtrim(K.name), '''', '''''')+''',0,'''+REPLACE(rtrim(K.code_str), '''', '''''')+''','+ltrim(str(isnull(K.property,0)))+','''+REPLACE(rtrim(isnull(K.add_info,'')), '''', '''''')+''','''+REPLACE(rtrim(isnull(K.long_name,'')), '''', '''''') + ''', ' + isnull('''' + convert(varchar(8), K.begin_date, 112) + ''',', 'NULL,') + isnull('''' + convert(varchar(8), K.end_date, 112) + '''', 'NULL') + ',' + LTRIM(STR(isnull(K.orders,0))) + char(13)+char(10) 
from report_kbk K  
where K.code_form=@code 
and isnull(K.link_self, 0) = 0
order by K.code

while @@ROWCOUNT > 0
begin
	insert #tmp (Link_Self, cstr)
			select K.Link,
	'set @LS = 0
	select @LS = Link from report_kbk where Code_Form = ''' + rtrim(K1.code_form) + ''' and  Code = ''' + isnull(K1.Code,'') +  ''' and begin_date ' + case when K1.begin_date is NULL then ' is NULL and end_date ' else '=''' + convert(varchar(10), K1.begin_date, 112) + ''' and end_date ' end + case when K1.end_date is NULL then ' is NULL' else '=''' + convert(varchar(10), K1.end_date, 112) + '''' end + '
	insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
	select '''+rtrim(K.code)+''',@LS,'''+rtrim(K.code_form)+''',1,'''+REPLACE(rtrim(K.name), '''', '''''')+''',0,'''+REPLACE(rtrim(K.code_str), '''', '''''')+''','+ltrim(str(isnull(K.property,0)))+','''+REPLACE(rtrim(isnull(K.add_info,'')), '''', '''''')+''','''+REPLACE(rtrim(isnull(K.long_name,'')), '''', '''''')+''',' + isnull('''' + convert(varchar(8), K.begin_date, 112) + ''',', 'NULL,') + isnull('''' + convert(varchar(8), K.end_date, 112) + '''', 'NULL') + ',' + LTRIM(STR(isnull(K.orders,0))) +char(13)+char(10) 
	from report_kbk K left join report_kbk K1 on K.Link_Self = K1.Link where K.code_form=@code and K.link_self in (select Link_Self from #tmp) 
	and not exists(select top 1 * from #tmp T where T.Link_Self = K.Link) order by K.code
end


INSERT #tmp (cStr)
SELECT 'insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, ''' + convert(varchar(10), H.date, 112)+ ''', ''' + RTRIM(H.Name) + ''', ''' + RTRIM(H.Long_Name) + '''
from dbo.report_kbk 
where code_form = ''' + @code + ''' and code = ''' + K.code + ''' and begin_date ' + case when K.begin_date is NULL then ' is NULL and end_date ' else '=''' + convert(varchar(10), K.begin_date, 112) + ''' and end_date ' end + case when K.end_date is NULL then ' is NULL' else '=''' + convert(varchar(10), K.end_date, 112) + '''' end  
FROM dbo.report_kbk_hist H
      JOIN dbo.report_kbk K ON K.[link] = H.[LINK_UP]
WHERE K.code_form=@code

INSERT #tmp (cStr)
SELECT 'exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = ''' + @code + '''' 
 

insert #res  (txt)
select cstr+
case when link%100=0 then char(13)+char(10)+'GO'+char(13)+char(10) + 'declare @LS int
' else '' end  
 from #tmp order by link
        set @i=@i+1
    end

insert #res  (txt)
select char(13)+char(10)+'GO'+char(13)+char(10)
end
end 

select txt from #res order by ord

GRANT ALL ON dbo.[RN_EXPORT_REPORT_KBK] 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.[K_FILL_T_STAFF]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[K_FILL_T_STAFF]

GO

CREATE      PROCEDURE [dbo].K_FILL_T_STAFF

AS
BEGIN

	DECLARE @CURRENT_DATE DATETIME
	SET @CURRENT_DATE = (SELECT REP_DATE FROM OBJECT_VAR_DATE WHERE SID = SUSER_SID() )



	CREATE TABLE #OTDEL0 (
		LINK INT, CODE VARCHAR(15), NAME VARCHAR(254), 
		LINK_SELF INT, ORDERS INT IDENTITY (1,1), DEP_LINK INT)
	INSERT INTO #OTDEL0  (LINK,CODE,NAME,LINK_SELF,DEP_LINK)
	SELECT LINK, CODE, [NAME], LINK_SELF, DEP_LINK
	FROM SUBDIVISION(@CURRENT_DATE) WHERE deleted=0
	ORDER BY ORDERS

	CREATE TABLE #OTDEL  (
		link INT, code VARCHAR(10) ,name VARCHAR (254), 
		orders INT,  
		dep_link INT,  LINK_PARENT INT,
		SUBD_LEVEL INT, REAL_ORDERS INT, NUM_PARENT INT
	)

	CREATE TABLE #OTDEL1  (
		link INT, code VARCHAR(10) ,name VARCHAR (254), 
		orders INT, dep_link INT,  LINK_PARENT INT,
		SUBD_LEVEL INT, REAL_ORDERS INT, NUM_PARENT INT)

	DECLARE #TMP_CUR_DEP CURSOR LOCAL FOR 
		SELECT LINK FROM DICTIONARY_DEPARTMENT WHERE TYPE IN (2, 4 ) or zb = 1
	OPEN #TMP_CUR_DEP
	DECLARE @LINK_DEP INT
	FETCH #TMP_CUR_DEP INTO @LINK_DEP
	WHILE @@FETCH_STATUS=0 BEGIN
		DELETE FROM #OTDEL

		EXEC MK_STAFF_TREE_MAKE @LINK_DEP, @CURRENT_DATE
		INSERT INTO #OTDEL1 SELECT * FROM #OTDEL
		FETCH #TMP_CUR_DEP INTO @LINK_DEP
	END
	CLOSE #TMP_CUR_DEP 
	DEALLOCATE #TMP_CUR_DEP 

	INSERT INTO #STAFF 
		SELECT 
			[num_otd] = REAL_ORDERS,
			[LNK] = DS.STAFF_LINK, 
			[LINK_OTD] = O.LINK, 
			[SUBDIV_CODE] = O.CODE, 
			[SUBDIV_NAME] = O.NAME, 
			[LINK_DOL] = DS.POST_LINK, 
			[POST_CODE] =RIGHT(DS.POST_CODE,6), 
			[POST_NAME] = DS.POST_NAME, 
			[NORM] = DS.NUM_STAKE, 
			[FACT] = CAST(0.0 AS FLOAT), 
			[VAC] = DS.FREE_STAKES, 
			[OKLAD] = DS.OKLAD, 
			[FOT] = DS.OKLAD, 
			[LEVEL_OTD] = SUBD_LEVEL,
			[CHIN_LINK] = DP.LINK, 
			[CHIN_CODE] = DP.CODE, 
			[CHIN] = DP.NAME, 
			[CONFIRMED] = 0,		--Ds.num_stake, 
			[DEYAT_TYPE_LINK] = 0,		--Ds.dey_link, 
			[DEYAT_TYPE] = '',		--DS.DEY_NAME,
			[KATEG_LINK] = Ds.kat_link, 
			[KATEG_CODE] = DS.KAT_CODE,
			[KATEG_DOL] = LEFT(DS.KAT_NAME,40),
			[GOSSL] = ISNULL(DS.GOSSL, 0),
			[FEDERAL] = ISNULL(DS.FIN, 0),
			[FOND] =  ISNULL(DS.FIN_FOND, 0),
			[LINK_DEP] = O.DEP_LINK, 
			[LINK_PARENT] = O.LINK_PARENT, 
			[NUM_PARENT] = O.NUM_PARENT,
			[KAT_GOS_LINK] = DS.KAT_GOS_LINK,
			[KAT_GOS_CODE] = DS.KAT_GOS_CODE,
			[KAT_GOS_NAME] = DS.KAT_GOS_NAME,
			[GR_GOS_LINK] = DS.GR_GOS_LINK,
			[GR_GOS_CODE] = DS.GR_GOS_CODE,
			[GR_GOS_NAME] = DS.GR_GOS_NAME
		FROM #OTDEL1 O 
		LEFT JOIN DICTIONARY_STAFF_FN(@CURRENT_DATE)  DS ON  DS.SUBDIV_LINK=O.LINK and ds.deleted=0
		LEFT OUTER JOIN DICTIONARY_POST DP ON DS.POST_LINK = DP.LINK
		ORDER BY REAL_ORDERS
	
	DECLARE @nLinkFIeld INT

	UPDATE #STAFF SET  FACT=( NORM - VAC)
	UPDATE #STAFF SET  FOT= FOT*NORM

	DROP TABLE #OTDEL

END



GO


GRANT EXECUTE ON dbo.[K_FILL_T_STAFF] 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_CHECK_KS_SVERKA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_KS_SVERKA]
GO


/*
c Кейсистемс (Keysystems), 2010
сверка
*/
CREATE    PROCEDURE dbo.RO_CHECK_KS_SVERKA

AS
if object_id('tempdb..#t_KS') is NULL
begin
  return -1
end

create table #t_KS2 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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_KS1 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)

insert #t_KS1
select *
from #t_KS
where algorithm = 5

delete #t_KS where algorithm = 5

declare @LF int,  @i int, @LT int
declare @link_table int,@calc_maska int,@ExecStr nvarchar(4000), @LinkRule int, @LinkTable int, @ValType tinyint, @CondRows varchar(3000),@get_str varchar(250),@ExecStr1 varchar(8000)
declare  @lsf int, @str_i varchar(10), @Fields varchar(8000), @NameFields varchar(8000), @dBeginDate DATETIME, @iDiffDate INT

create table #t_temp (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)

-- РАЗМНОЖАЕМ СТРОКИ С ФИЛЬТРОМ, с учетом МАСКИ
declare @t_table table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)  

insert #t_temp
  select * from #t_KS1 where [Filter] <> '' or Mask <> ''

insert @t_table
select * from #t_temp

SELECT @dBeginDate = max(rsf.[Begin_Date])
FROM  #t_temp T 
   JOIN dbo.[REPORT_SAVED_FORMS] rsf ON T.[lsf] = rsf.[Link_Saved_Form]
WHERE lsf IS NOT null

SET @iDiffDate = DATEDIFF(DAY, '20111231', @dBeginDate)

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'
EXEC dbo.[BufferPush] @iDiffDate, 'RO_RAZMNOJ_KS_OUTSIDE'

declare @condFilter varchar(3000),@orderrow int,@condMaska varchar(200), @lsf_left int
while exists(select top 1 * from #t_temp)
begin
  select top 1 @LinkRule = Link_Rule, @CondFilter ='('+rtrim([Filter])+')' + case when [rows] <> '' then ' and (' + [rows] + ')' else '' end ,@CondMaska =[Mask], @orderrow = orderrow, @lsf = lsf, @lt = lINK_tABLE, @lf = Link_Form from #t_temp order by orderrow desc
	set @lsf_left = 0
	select @lsf_left = lsf from #t_temp where @LinkRule = Link_Rule and part = 0
--print  dbo.RN_GET_ATR_VALUE(@lsf_left, B.code)
	-- атрибуты в фильтрах
	select  @CondFilter = REPLACE(@CondFilter, '$' + rtrim(B.code) + '$', '''' + dbo.RN_GET_ATR_VALUE(@lsf_left, B.code) + '''')
	from N_REPORT_ATRIBUTS_VIEW B 

	-- атрибуты в фильтрах
	select  @CondFilter = REPLACE(@CondFilter, '#' + rtrim(B.code) + '#', '''' + dbo.RN_GET_ATR_VALUE(@lsf, B.code) + '''')
	from N_REPORT_ATRIBUTS_VIEW B 

	set @CondFilter = REPLACE(REPLACE(@CondFilter,'$ОТЧЕТ$', LTRIM(STR(@lf))),'$ТАБЛИЦА$',LTRIM(STR(@lt)))

	if @CondFilter = '()'
		set @CondFilter = '(1=1)'

  select top 1 @LinkTable = Link_Table  from #t_temp where Link_Rule = @LinkRule and Link_Table is NOT NULL and orderrow = @orderrow
  select top 1 @valtype=val_type from #report_tables RT join report_forms RF on RT.Link_Form = RF.Link_Form where link_table=@linkTable 
  if @ValType = 0 -- таблица статическая
  begin
       set @condMaska= RTRIM(case when @condMaska<>'' then '+'+REPLACE(REPLACE(@condMaska, 'CODE', 'B.CODE'), 'COL(', 'dbo.RO_COL_Static(A.lsf,' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')   else '' end)
       set @ExecStr=''
       set @ExecStr = 'insert #t_KS1 
		select Link_Rule, OrderRow, 0, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, ' + case when @condMaska = '' then '''''' else @condMaska end + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join #t_Rows_Static B on A.link_table = B.link_table
        where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and ' + REPLACE(@CondFilter, 'COL(', 'dbo.RO_COL_Static(A.lsf,' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')
  end
  else begin -- таблица динамическая
    set @condMaska= RTRIM(case when @condMaska<>'' then '+'+REPLACE(REPLACE(@CondMaska, 'CODE', 'RD.Code_Row'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,' + LTRIM(STR(@LinkTable)) + ', RD.Code_Row,')   else '' end)

    set @ExecStr = '
       insert #t_KS1 
		select Link_Rule, OrderRow, 3, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, ' + case when @condMaska = '' then '''''' else @condMaska end + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join 
        (select distinct Link_SF, Code_Row, Link_Table from #report_dinamics) RD on A.lsf = RD.Link_sf and A.Link_table = RD.Link_table '+
        'where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and ' + REPLACE(REPLACE(REPLACE(@CondFilter, 'CODE', 'RD.Code_Row'),'.RD.Code_Row','.Code'), 'COL(','(select top 1 case when RC.Col_Type = 1 then str_val else float_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 =' + LTRIM(STR(@LinkTable))+' and RC.orders =') 

	if @condMaska = ''
        set @ExecStr = @ExecStr + ' IF @@rowcount=0 
        insert #t_KS1 
		select Link_Rule, OrderRow, 1, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, NULL, ''нет строк'', Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, CodeRow, cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp  where orderrow='+LTRIM(STR(@orderrow))+ ' and Link_Rule = ' + LTRIM(STR(@LinkRule))
    
  end

PRINT @ExecStr
exec sp_executesql @ExecStr

--добавим недостающие слагаемые
--  INSERT #t_KS1
--        select Link_Rule, OrderRule, OrderRow,1, Sign, LinkTable, LinkCol, NULL, '', CodeRow, [Rows], 0, Exec_Proc, Exec_Proc_Desc, Filter, Mask, 0, A.ORDERS, Filter_Desc, Mask_Desc,isLeftPart
--        from #t_temp A where not Exists(select * from #t_ks1 B where B.link_rule=@LinkRule and B.OrderRow=@orderRow)

  delete #t_temp where Link_Rule = @LinkRule and orderrow = @orderrow 
end

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'
update #t_KS1
set CodeRow = K.CodeRow
from (select * from #t_KS1 where CodeRow <> '') K
where  #t_KS1.Code_Row = 'нет строк' and K.Link_Rule = #t_KS1.Link_Rule and K.orderCol = #t_KS1.orderCol

insert #t_KS1
select T.Link_Rule, T.OrderRow, 3, T.[sign],  T.Link_Form, T.period_form, T.period_type, T.period_year, T.begin_date, T.budg_code, T.atr_code, T.lsf, T.Link_Table, T.Link_Col, NULL, K.CodeRow, T.Factor, T.px, T.Exec_Proc, T.Filter, T.Filter_desc, T.Mask , T.part, T.algorithm, T.cols, T.[rows], T.[Value], T.orderCol, K.CodeRow, T.cOrderTable, T.cOrderCol, px_comment, [property]
from (select distinct Link_Rule, orderCol, CodeRow, atr_code from #t_KS1 where CodeRow <> '' ) K inner join @t_table T on K.Link_Rule = T.Link_Rule and K.orderCol = T.orderCol and K.atr_code = T.atr_code
where T.val_type <> 0 and not exists(select top 1 * from #t_KS1 K1 where K1.Link_Rule = T.Link_Rule and K1.orderCol = T.orderCol and K1.orderrow = T.orderRow and K1.CodeRow = K.CodeRow and K1.atr_code = K.atr_code)

delete #t_ks1
where isnull(CodeRow,'') = '' and (isnull(Code_Row,'') = '' or Code_Row = 'нет строк') and part = 0

update #t_KS1
set Code_Row = CodeRow
where Code_Row = 'нет строк' and isnull(CodeRow, '') <>''

delete #t_ks1 where isnull(CodeRow, '') = ''

---------------------------------------------------------------------
-- ФОРМИРУЕМ ПРОТОКОЛ
declare @LT1 int, @LT2 int, @DataDesc varchar(300), @lf1 int, @lf2 int, @cOrderTable1 varchar(100), @cOrderTable2 varchar(100), @countError int,
      @strDelNoError nvarchar(4000), @catr varchar(1000), @bManyTable BIT 

insert #t_KS2
select *
from #t_KS1


--delete K
--from #t_KS1 K left join #report_dinamics RD on K.Link_Col = RD.Link_Col and K.Code_Row = RD.Code_Row and K.lsf = RD.link_sf
--where round(isnull(RD.float_val, 0),2) = 0 

declare cur_tables cursor local static for select distinct L.Link_Table, R.Link_Table, L.link_form, R.link_form, L.corderTable, R.corderTable from #t_KS2 L full join #t_KS2 R on L.Link_Rule = R.Link_Rule and L.CodeRow = R.CodeRow and L.atr_code = R.atr_code where L.part = 0 and R.part = 1 order by L.cOrderTable

open cur_Tables

fetch next from cur_Tables into @LT1, @LT2, @lf1, @lf2, @cOrderTable1, @cOrderTable2

while @@fetch_status = 0
begin
	set @countError = 0
	create table #t_Protokol_Sverka (Code_Row varchar(50), atr_code varchar(1000))

   select top 1 @catr = atr_code from #t_ks1 K where K.Link_Table in (@LT1, @LT2)

   SET @bManyTable = 0

	insert #t_Protokol_Sverka(Code_Row, atr_code)
	select distinct CodeRow, atr_code
	from #t_ks1 K 
	where K.Link_Table in (@LT1, @LT2)
   AND NOT EXISTS(SELECT * FROM #t_ks1 k2 WHERE K.link_rule = K2.link_rule and K2.[Link_Table] NOT IN (@LT1, @LT2))
   
   IF @@ROWCOUNT = 0
   BEGIN 
	   insert #t_Protokol_Sverka(Code_Row, atr_code)
	   select distinct CodeRow, atr_code
	   from #t_ks1 K 
	   where K.Link_Table in (@LT1, @LT2)
      set @bManyTable = 1
   END 

	set @i = 1
	set @Fields = '<field name=''Code_Row''></field>'
	set @NameFields = 'Код строки'
   set @strDelNoError = ''

   if @catr <> ''
   begin
	      set  @Fields = '<field name=''atr_code''></field>' + @Fields
		   set @NameFields = 'Атрибут|' + @NameFields 
    end

	while exists(select top 1 * from #t_ks1 k where Link_Table in (@LT1, @LT2) AND (NOT EXISTS(SELECT * FROM #t_ks1 k2 WHERE K.link_rule = K2.link_rule and K2.[Link_Table] NOT IN (@LT1, @LT2)) OR @bManyTable = 1))
	begin
		select top 1 @LinkRule = Link_Rule from #t_ks1 K left join #report_coloumns RC on K.Link_col = RC.Link_Col where K.Link_Table in (@LT1, @LT2) AND (NOT EXISTS(SELECT * FROM #t_ks1 k2 WHERE K.link_rule = K2.link_rule and K2.[Link_Table] NOT IN (@LT1, @LT2)) OR @bManyTable = 1) order by part, RC.orders

		set @str_i = LTRIM(RTRIM(STR(@i)))
		set  @Fields = @Fields + '<field name=''Left' + @str_i + '''></field><field name=''Right' + @str_i + '''></field><field name=''Otkl' + @str_i + '''></field>'
		select top 1 @NameFields = @NameFields + '|' + REPLACE(R.Str_Rule,'=','|') + '|Отклонение' from #t_KS2 K left join #t_Rules R on K.link_rule = R.link_rule where K.Link_Rule = @LinkRule 
		
		set @ExecStr = 'ALTER TABLE #t_Protokol_Sverka ADD Left' + @str_i + ' float  ALTER TABLE #t_Protokol_Sverka ADD Right' + @str_i + ' float ALTER TABLE #t_Protokol_Sverka ADD Otkl' + @str_i + ' varchar(100)'
		exec sp_executesql @ExecStr
		set @ExecStr = 'update #t_Protokol_Sverka set Left' + @str_i + ' = isnull(L1.value,0), Right' + @str_i + ' = isnull(R1.Value,0), Otkl' + @str_i + ' = ''<font color=#FF0000>'' + dbo.[rn_convert_number](isnull(R1.Value,0) - isnull(L1.Value,0),2,'' '') + ''</font>''
	from (select L.CodeRow , L.atr_code, sum(case when [sign] =''+'' then LD.float_val else -LD.float_val end) as Value 
			from #t_ks1 L 
				left join #report_dinamics LD on LD.Link_SF = L.lsf and LD.Link_Col = L.Link_Col and LD.Code_Row = L.Code_Row
			where part = 0 and Link_Rule = @LinkRule group by L.CodeRow, L.atr_code) L1
		full join
			(select R.CodeRow, R.atr_code , sum(case when [sign] =''+'' then RD.float_val else -RD.float_val end) as Value 
			from #t_ks1 R 
				left join #report_dinamics RD on RD.Link_SF = R.lsf and RD.Link_Col = R.Link_Col and RD.Code_Row = R.Code_Row
			where part = 1 and Link_Rule = @LinkRule group by R.CodeRow, R.atr_code) R1
		on L1.CodeRow = R1.CodeRow and L1.atr_code = R1.atr_code
	where isnull(L1.CodeRow, R1.CodeRow) = #t_Protokol_Sverka.Code_Row and isnull(L1.atr_code, R1.atr_code) = #t_Protokol_Sverka.atr_code
	select @countError = @countError + count(*) from #t_Protokol_Sverka where Otkl' + @str_i + '<>''<font color=#FF0000>0.00</font>''
	update #t_Protokol_Sverka set Left' + @str_i + ' = 0.00, Right' + @str_i + ' = 0.00,Otkl' + @str_i + ' = ''<font color=#FF0000>0.00</font>''
	where isnull(Left' + @str_i + ','''') = '''' and isnull(Right' + @str_i + ','''') = '''' and isnull(Otkl' + @str_i + ','''') = ''''
--	update #t_Protokol_Sverka set Left' + @str_i + ' = ''<B>'' + Left' + @str_i + ' +''</B>'', Right' + @str_i + ' = ''<B>'' + Right' + @str_i + '  +''</B>'',Otkl' + @str_i + ' = ''<B>'' + Otkl' + @str_i + '  +''</B>''
--	where LEFT(Code_Row,10) in (''0008500000'', ''0009600000'', ''0007900000'', ''5000009000'', ''8500000000'', ''9600000000'', ''7900000000'', ''5009000000'')
'
      set @strDelNoError = @strDelNoError + 'Otkl' + @str_i + ' = ''<font color=#FF0000>0.00</font>'' and ' 

		exec sp_executesql @ExecStr, N'@LinkRule int,  @lt1 int, @lt2 int, @countError int output', @LinkRule = @LinkRule, @lt1 = @lt1, @lt2 = @lt2, @countError = @countError output
		set @i = @i + 1
		delete #t_ks1 where Link_Rule = @LinkRule  
	end

   if @strDelNoError <> ''
      set @strDelNoError = 'delete #t_Protokol_Sverka where ' + LEFT(@strDelNoError, LEN(@strDelNoError) - 4)

   if (exists(select top 1 CodeForm from #ListFormsA where linkform in (@lf1, @lf2) and CodeForm like '0503151%') and isnull((select val_int from dbo.report_options where razdel = 'form_151' and code = 'sverka_only_error'),0) = 1)
       or (exists(select top 1 CodeForm from #ListFormsA where linkform in (@lf1, @lf2) and CodeForm like '0503152%') and isnull((select val_int from dbo.report_options where razdel = 'form_152' and code = 'sverka_only_error'),0) = 1)
      exec sp_executesql @strDelNoError
   set @strDelNoError = ''

	select  @DataDesc = 'Протокол сверки форм: ' + codeForm  + ' Таблица ' + @cOrderTable1 + ' и ' from #ListFormsA where linkform = @lf1
	select  @DataDesc = @DataDesc + codeForm  +  ' Таблица' + @cOrderTable2 from #ListFormsA where linkform = @lf2
	set @DataDesc = @DataDesc + '<font size=4> Количество ошибок:' + LTRIM(STR(@countError)) + ' </font>' 

	update #t_Protokol_Sverka
	set Code_Row = '<B>' + RTRIM(Code_Row) + '</B>'
	where LEFT(Code_Row,10) in ('0008500000', '0009600000', '0007900000', '5000009000', '8500000000', '9600000000', '7900000000', '5009000000')

   IF exists(select * from #t_Protokol_Sverka)
	     exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = @DataDesc, @cDataTableName  = '#t_Protokol_Sverka',@cShowFields  = @Fields
	   , @cFieldsDesc  = @NameFields, @cOrderFields = 'atr_code, Code_Row'
	
	drop table #t_Protokol_Sverka		
	fetch next from cur_Tables into @LT1, @LT2, @lf1, @lf2, @cOrderTable1, @cOrderTable2
end    
close cur_Tables
deallocate cur_Tables
drop table #t_temp
drop table #t_KS1
drop table #t_KS2

GO
GRANT ALL ON dbo.[RO_CHECK_KS_SVERKA] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_ANALYZE_XML]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_ANALYZE_XML]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
-- Процедура анализа импортируемой формы (получения ее параметров).
-- Вход: таблица #IMPORT_TABLE с загруженными данными формы.
-- Коды ошибок
-- -1  - Неправильный формат даты				
-- -2  - Отсутствует раздел кода вида бюджета (ВБ или ВИД)   
-- -3  - Отсутствует раздел кода бюджетополучателя (БП, КБП или ИСТ)
-- -4  - Отсутствует раздел периодичности формы (ПРД)
-- -5  - Неправильная дата. Число должно быть 01
-- -6  - Неправильная дата. Месяц квартальной формы должен быть 01,04,07 или 10
-- -7  - Неправильная дата. Неправильная дата. Месяц для годовой формы должен быть 01
-- -9  - Организации с таким кодом бюджетополучателя не существует
-- -10 - В отчете отсутствует код бюджета
-- -11 - Выгружаемый код бюджета не уникален
-- -12 - Выгружаемый код бюджета не найден
-- -13 - Ошибка в dbo.[RA_IMPORT_FORM_GET_LINK_FORM]
-- -14 - Неверное значение в разделе периодичности формы (ПРД)
-- -15 - Неуникальный КБП в базе данных
-- -16 - Отсутствует лицензия на использование Свод-EXCEL.

-- 2010.05.26 Olga теперь работает и на 2000 сервере, но ограничение файла 2 Мб
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_ANALYZE_XML]
   @cCODE_FORM       CHAR(20)       OUTPUT,   
   @vcKBP            VARCHAR(100)   OUTPUT,
   @vcVB             VARCHAR(10)    OUTPUT,
   @dDT              DATETIME       OUTPUT,
   @vcSOFT           VARCHAR(500)   OUTPUT,
   @vbVF0            BIT            OUTPUT,
   @iXML_DOC_HANDLE  INT            OUTPUT,
   @txtXML           TEXT = ''
WITH ENCRYPTION
AS

SET NOCOUNT ON
SET DATEFORMAT ymd

print 'dbo.[RA_IMPORT_FORM_ANALYZE_XML]'

DECLARE @vcDateEnd         VARCHAR(20),
        @cTypeInf          CHAR(1),
        @binTEXTPTR        BINARY(16),
        @iDATALENGTH       INT,
        @vcTxt             VARCHAR(8000),
        @vcTxt2            VARCHAR(8000),
        @vcTxt3            VARCHAR(8000),
        @iOffset           INT,
        @vcFormatVersionNo VARCHAR(10),
        
   	@vcINN				varchar(100),
		@LinkOrg			int,
		@LinkBudg			int,
		@date				datetime

UPDATE #IMPORT_TABLE
SET [TXT] = '<?xml version="1.0" encoding="windows-1251"?>'
WHERE [TXT] = '?<?xml version="1.0" encoding="UTF-8"?>'

DECLARE @iLen INT


SELECT @iLen = ISNULL(SUM(LEN([TXT])),0)
FROM #IMPORT_TABLE 

IF @iLen = 0
BEGIN
   RETURN 0
END


if left(convert(char(2), serverproperty('productversion')), 2)=N'8.'  -- если 2000-ый сервер
begin
	CREATE TABLE #tabXML2 ([ORDER] INT IDENTITY(1,1) PRIMARY KEY, [TXT] varchar(8000))
	create table #handle (value int)

	insert #tabXML2 (TXT)
	values ('declare @iXML_DOC_HANDLE int
	EXEC sp_xml_preparedocument @iXML_DOC_HANDLE OUTPUT, ''')

	insert #tabXML2 (TXT)
	   SELECT [TXT] = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([TXT],'''', ''''''),'xmlns="urn:mfrf-ru:ed:v2.0"',''),'xmlns="urn:schemas-1c-ru:reports/data"',''),'budg:',''),'/>','/>'+CHAR(13)+CHAR(10))
	   FROM #IMPORT_TABLE
	   WHERE LEFT([TXT],4) NOT IN ('ВИД=','ИСТ=','КБП=') AND LEFT([TXT],3) NOT IN ('ВБ=','КБ=')
	  ORDER BY [ORDER]

	insert #tabXML2 (TXT)
	values ('''
	insert #handle (value) values(@iXML_DOC_HANDLE)')

	exec dbo.ssp_execresultset 'select TXT from #tabXML2 order by [ORDER]'

	drop table #tabXML2

	select  @iXML_DOC_HANDLE = value from #handle

	drop table #handle
end
else
begin
	 -- Код который работает только на 2005
	CREATE TABLE #tabXML ([ORDER] INT IDENTITY(1,1) PRIMARY KEY, [TXT] TEXT)
	INSERT #tabXML([TXT]) VALUES ('')--'(REPLICATE(' ',@iLen + 300000))

	DECLARE curTxt CURSOR LOCAL FORWARD_ONLY STATIC	FOR 
	   SELECT [TXT] = REPLACE(REPLACE(REPLACE([TXT],'xmlns="urn:mfrf-ru:ed:v2.0"',''),'xmlns="urn:schemas-1c-ru:reports/data"',''),'budg:','')
	   FROM #IMPORT_TABLE
	   WHERE LEFT([TXT],4) NOT IN ('ВИД=','ИСТ=','КБП=') AND LEFT([TXT],3) NOT IN ('ВБ=','КБ=')
	   ORDER BY [ORDER]

	OPEN curTxt 

	FETCH NEXT 
	FROM curTxt
	INTO @vcTxt

	SELECT @binTEXTPTR = TEXTPTR([TXT]),
		   @iDATALENGTH = 0,
		   @iOffset = 0
	FROM #tabXML


	WHILE @@FETCH_STATUS=0
	BEGIN	
	   SET @vcTxt2 = REPLACE(SUBSTRING(@vcTxt,4001,8000),'/>','/>'+CHAR(13)+CHAR(10))
	   SET @vcTxt  = REPLACE(LEFT(@vcTxt,4000),'/>','/>'+CHAR(13)+CHAR(10))
	 
	   SET @iDATALENGTH = DATALENGTH(@vcTxt)
		UPDATETEXT #tabXML.[TXT] @binTEXTPTR @iOffset 0 @vcTxt

	   SET @iOffset = @iOffset + @iDATALENGTH      

	   SET @iDATALENGTH = DATALENGTH(@vcTxt2)
		UPDATETEXT #tabXML.[TXT] @binTEXTPTR @iOffset 0 @vcTxt2
	   SET @iOffset = @iOffset + @iDATALENGTH      

	   FETCH NEXT 
	   FROM curTxt
	   INTO @vcTxt
	   
	END

	CLOSE curTxt
	DEALLOCATE curTxt

	select @txtXML = [TXT]
	from #tabXML

	DROP TABLE #tabXML

	EXEC sp_xml_preparedocument @iXML_DOC_HANDLE OUTPUT, @txtXML

end



IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] like '%<envelope%generator%')
BEGIN
	exec dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C]
	   @cCODE_FORM = @cCODE_FORM OUTPUT,   
	   @vcKBP = @vcKBP           OUTPUT,
	   @vcVB = @vcVB             OUTPUT,
	   @dDT = @dDT               OUTPUT,
	   @vcSOFT = @vcSOFT         OUTPUT,
	   @vbVF0 = @vbVF0           OUTPUT,
	   @iXML_DOC_HANDLE = @iXML_DOC_HANDLE,
	   @txtXML = @txtXML    
	return 0
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] like '%<SchemaVersion Number="2" Owner="%" Application="%"/>')
BEGIN
	exec dbo.[RO_IMPORT_FORM_ANALYZE_XML_125]
	   @cCODE_FORM       OUTPUT,   
	   @vcKBP            OUTPUT,
	   @vcVB             OUTPUT,
	   @dDT              OUTPUT,
	   @vcSOFT           OUTPUT,
	   @vbVF0            OUTPUT,
	   @iXML_DOC_HANDLE,
	   @txtXML    
	return 0
END
IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] like '%xml version="1.0" encoding="windows-1251"%')
	AND EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] LIKE '%FORM_CODE="426"%')
 
BEGIN
	exec dbo.[RO_IMPORT_FORM_ANALYZE_015]
	   @cCODE_FORM       OUTPUT,   
	   @vcKBP            OUTPUT,
	   @vcVB             OUTPUT,
	   @dDT              OUTPUT,
	   @vcSOFT           OUTPUT,
	   @vbVF0            OUTPUT,
	   @iXML_DOC_HANDLE,
	   @txtXML    
	return 0
END
IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] LIKE '%<HEADER GUID=%FORM_CODE="003"%')
 
BEGIN
	exec dbo.[RO_IMPORT_FORM_ANALYZE_003]
	   @cCODE_FORM       OUTPUT,   
	   @vcKBP            OUTPUT,
	   @vcVB             OUTPUT,
	   @dDT              OUTPUT,
	   @vcSOFT           OUTPUT,
	   @vbVF0            OUTPUT,
	   @iXML_DOC_HANDLE,
	   @txtXML    
	return 0
END
SELECT @vcFormatVersionNo = [FormatVersionNo]
FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED',1) WITH ([FormatVersionNo] VARCHAR(10) '@FormatVersionNo')  

IF @vcFormatVersionNo = '2008.04'
BEGIN
   SET @vbVF0 = 0

   SELECT @vcSOFT = [SoftwareProduct]
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED',1) WITH ([SoftwareProduct] VARCHAR(300) '@SoftwareProduct')  

   SELECT @vcSOFT = @vcSOFT + ISNULL(' ' + [SoftwareProductVersion],'')
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED',1) WITH ([SoftwareProductVersion] VARCHAR(150) '@SoftwareProductVersion')  

   SELECT @cCODE_FORM = [CODE]
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED/Inf',1) WITH ([CODE] CHAR(20) '@Code')  

   SELECT @cTypeInf  = [TypeInf]
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED',1) WITH ([TypeInf] CHAR(1) 'TypeInf')    

   SELECT @vcDateEnd = [DateEnd]
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED',1) WITH ([DateEnd] VARCHAR(50) 'DateEnd')    

	print @vcDateEnd

   IF @vcDateEnd LIKE ('%____-__-__%') AND 
      ISDATE(@vcDateEnd) = 1
   BEGIN
      SET @dDT = CASE @cTypeInf
                    WHEN '1' THEN CAST(LEFT(LTRIM(@vcDateEnd),4)+'0101' AS DATETIME) -- Плановая информация на следующий год.
                    WHEN '2' THEN CONVERT(DATETIME,@vcDateEnd,120) + 1 -- Уточненная информация на текущий год.
                 END
	  set @date = CONVERT(DATETIME,@vcDateEnd,120)
   END

	print @vcDateEnd
   SELECT @vcKBP = LTRIM(SUBSTRING([TXT],CHARINDEX('=',[TXT]),50))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR LEFT([TXT],3) IN ('KБ=')

   SELECT @vcVB = LTRIM(SUBSTRING([TXT],CHARINDEX('=',[TXT]),50))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

   IF @vcKBP IS NULL
   BEGIN
      SELECT @vcKBP = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'RRO' AND
            [CODE] = 'IMPORT_KBP_RRO'
   END
   
   IF @vcVB IS NULL 
   BEGIN
      SELECT @vcVB = [VAL_STR]
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'RRO' AND
            [CODE] = 'IMPORT_VB_RRO'
   END

	select @vcINN = Code
   FROM OPENXML (@iXML_DOC_HANDLE ,'/PacketED/From',1) WITH ([CODE] CHAR(20) '@Code')  

	if LEFT(@vcINN,1) = 'I' -- значит это ИНН организации и загрузка происходит с БКС
	begin
		select @vcKBP = budg, @LinkOrg = Link from dictionary_department where INN = RIGHT(RTRIM(@vcINN),LEN(@vcINN)-1)
		select @LinkBudg = min(link_report_budg) from report_svod_tree where link_org = @LinkOrg and link_history = dbo.RO_SVOD_TREE_Link_History(@date)
		if  @LinkBudg is NULL	
		begin
			select @LinkBudg = min(link_report_budg) from report_svod_tree where link_report_org = @LinkOrg and link_history = dbo.RO_SVOD_TREE_Link_History(@date)
		end
		SELECT @vcVB = OutCode from kl_budg_type where link = @LinkBudg 		
	end	
 

END

/*
IF @bDelXML_DOC = 1
BEGIN
   EXEC sp_xml_document @iXML_DOC_HANDLE
END
*/



RETURN 0
--RETURN dbo.[RA_GET_ERROR](OBJECT_ID('dbo.[RA_IMPORT_FORM_ANALYZE_XML]'))
GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_ANALYZE_XML] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select @@datalength
sp_help RA_IMPORT_FORM_ANALYZE_XML
*/	

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_DIS_FACE_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_DIS_FACE_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE [dbo].KU_DIS_FACE_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparNumber  varchar(30),
	@varKSparDate   datetime,
	@varKSparDIS_DATE     DATETIME = null,
	@varKSparREASON_LINK      INT = null,
	@varKSparOSN	VARCHAR(254) = null,
	@varKSparPROF_DATE       DATETIME = null,
	@varKSparPROF_NUM      VARCHAR(15) = null,
	@varKSparEMPL_LINK      INT = null,
	@varKSparORDER_LINK INT = null,
	@varKSparVAC_KOMPENS_DAY numeric(6,2) = 0,
	@varKSparDEP_LINK int = null,
	@varKSparORDER_STATUS int = 0
AS
DECLARE @varKSERROR tinyint, @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSparDIS_DATE IS NULL or @varKSparREASON_LINK is null
	BEGIN
		ROLLBACK
		RETURN 5
	END

	
	SELECT @varKSparREASON_LINK = link FROM diction WITH (UPDLOCK) WHERE LINK = @varKSparREASON_LINK
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 3
	END

	
	SELECT @varKSparORDER_LINK = link FROM ORDERS WITH (UPDLOCK) WHERE LINK = @varKSparORDER_LINK
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	
	IF @varKSRowCount = 0
	BEGIN
		SET @varKScomment='Об увольнении '+dbo.ku_GetEmplFio(@varKSparEMPL_LINK)
		EXECUTE @varKSERROR = KU_ORDER_SAVE @varKSparORDER_LINK OUTPUT, 3, @varKSparNumber, @varKSparDate, @varKScomment, 0, @varKSparDEP_LINK
		IF @varKSERROR <> 0
			RETURN @varKSERROR
	END

	
	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN
		INSERT INTO item_dis_face WITH (ROWLOCK) (dis_date, reason, osn, prof_date, prof_num, empl_link, order_link, VAC_KOMPENS_DAY)
			VALUES (@varKSparDIS_DATE, @varKSparREASON_LINK, @varKSparOSN, @varKSparPROF_DATE, @varKSparPROF_NUM,
				 @varKSparEMPL_LINK, @varKSparORDER_LINK, @varKSparVAC_KOMPENS_DAY)
		SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	ELSE
	BEGIN
		UPDATE item_dis_face SET dis_date=@varKSparDIS_DATE, reason=@varKSparREASON_LINK,
				osn = @varKSparOSN, prof_date=@varKSparPROF_DATE, prof_num=@varKSparPROF_NUM, empl_link=@varKSparEMPL_LINK, order_link=@varKSparORDER_LINK, VAC_KOMPENS_DAY = @varKSparVAC_KOMPENS_DAY
		WHERE link=@varKSparLINK
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

	IF @varKSparORDER_STATUS=1
		UPDATE orders SET status = 1 WHERE link=@varKSparORDER_LINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[KU_DIS_FACE_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].[BK_PRINTDOC_F0504833ZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BK_PRINTDOC_F0504833ZB]
GO


/*
© Кейсистемс (Keysystems), 2005
*/


CREATE  PROCEDURE BK_PRINTDOC_F0504833ZB
AS BEGIN
	DECLARE @intANALIT INT,
		@intPRN_RUK	INT,
		@intPRN_GLBUH	INT

	DECLARE @RES0 TABLE  (LINK INT, LINK_REESTR INT)
	
	DECLARE @ERR  TABLE (NUMBER VARCHAR(254), [DATE] DATETIME, DOC_LINK INT, VALUE VARCHAR(254), ERR_TYPE INT)
	DECLARE @RES1 TABLE (
		LINK_DOC INT,
		DOC_DATE VARCHAR (10),
		PROV_DATE VARCHAR (10),
		DOC_NUM VARCHAR(30),
		COMMENT VARCHAR (254),
		DOC_TITLE VARCHAR(254),
		DEP_LINK INT,
		DEP_NAME VARCHAR(254),
		OKPO VARCHAR(254),
		SUBDIV VARCHAR(254),
		SUBDIV_C VARCHAR(10),
		REASON VARCHAR(254),
		DT VARCHAR(254),
		KT VARCHAR(254),
		QTY NUMERIC(20,4),
		SUMMA NUMERIC(20,2),
		GLBUH VARCHAR(254),
		ORD1 INT, ORD2 INT,
		LINK_G2 INT,
		PRN_ANALIT INT,
		APD_NAME VARCHAR (3000),
		APK_NAME VARCHAR (3000),
		PRN_RUK	INT,
		PRN_GLBUH INT,
		LIST_JO	VARCHAR (100),
		ECON_OPER INT
	)

	INSERT INTO @RES1
	SELECT 
		T1.LINK_DOC,
		T1.DOC_DATE,
		T1.PROV_DATE,
		T1.DOC_NUM,
		T1.COMMENT, '',
		T1.DEP_LINK, T1.DEP_NAME, T1.OKPO,
		T2.OTDEL_NAME, T2.OTDEL_CODE, 
		T1.REASON,
		T1.DT,
		T1.KT,
		T1.QTY,
		T1.SUMMA,
		ISNULL (dbo.BK_Get_EMPL_Signature (T2.FACE_LINK, DEFAULT), ''),
		T1.ORD1, T1.ORD2,
		T1.LINK_G2,
		PRN_ANALIT,
		T1.APD_NAME,
		T1.APK_NAME,
		PRN_RUK, 
		PRN_GLBUH,
		LIST_JO,
		ECON_OPER 
	FROM dbo.BK_PrintDoc_F0504033_DATA ('PRINT_DOCUMENTS_F0504833ZB', DEFAULT) T1
	INNER JOIN dbo.DOCUMENTS_F0504833_ZB T2 ON (T2.LINK = T1.LINK_DOC)

	INSERT INTO @ERR (NUMBER, [DATE], DOC_LINK, VALUE, ERR_TYPE)
	SELECT DISTINCT DOC_NUM, DOC_DATE, LINK_DOC, 'Не указана организация', 2
	FROM @RES1 WHERE DEP_LINK IS NULL

	DELETE FROM @RES1 WHERE LINK_DOC IN (SELECT DOC_LINK FROM @ERR)

	SELECT * FROM @RES1 order by link_doc, ORD1, ORD2

	SELECT * FROM @RES0

	SELECT * FROM @ERR WHERE ERR_TYPE = 1
	SELECT * FROM @ERR WHERE ERR_TYPE = 2
	SELECT * FROM @ERR WHERE ERR_TYPE = 3

	DECLARE @varKSLOG_STR VARCHAR(1000), @varKSnLink int
	DECLARE #TMP_CUR2 CURSOR LOCAL FOR 
		SELECT DP.LINK, LTRIM(RTRIM(NUMBER)) + ' от ' + CONVERT(VARCHAR(10), DATE, 104)
		FROM dbo.DOCUMENTS_F0504833_ZB DP, dbo.BufferGetTableByID('PRINT_DOCUMENTS_F0504833ZB') B
		WHERE DP.LINK = B.LINK
	OPEN #TMP_CUR2 
	FETCH #TMP_CUR2 INTO @varKSnLink, @varKSLOG_STR
	WHILE @@FETCH_STATUS = 0 BEGIN
		EXEC dbo.XD_GENERATE_EVENT_SO 'DOCUMENTS_F0504833_ZB', @varKSLOG_STR, @varKSnLink
		FETCH #TMP_CUR2 INTO @varKSnLink, @varKSLOG_STR
	END
	CLOSE #TMP_CUR2 
	DEALLOCATE #TMP_CUR2 

	EXEC dbo.BufferClear
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_ANALIZ_25]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_ANALIZ_25]
GO
CREATE PROCEDURE [dbo].[RT_ANALIZ_25]
	@varKSsFLink int,
	@inCode_Row varchar(50),
	@link_table int
AS

declare @LSF int,
        @rowcount int,
        @cAccount varchar(9),
        @cNameform varchar(8000),
        @IS_RBS int,
        @j int,
        @jj int,
        @i int,
        @iLink_col int,
        @code_row varchar(50),
        @float_val numeric(20,4),
        @str_val varchar(250),
		@varKSLinkF int,
		@iLink_Table int,
		@nowTab tinyint,
		@tab int,
		@sql_script varchar(3000)

-- если пользователь пытается анализировать итоговые строчки (кроме строки Итого) возвращаем пустую таблицу
if right(rtrim(@inCode_Row),2) in ('ИП','ИД','ИН')begin
	select null as ord, null as org, null as col1, null as col2
	return
end

create table #report_dinamics (Link_SF	int,Link_Col	int,Code_Row	varchar(50),Float_Val	numeric(20,4),Str_Val	varchar(8000))
Create index #IX_report_dinamics on #report_dinamics (Link_SF,link_col,code_row)

insert into #report_dinamics (Link_SF,Link_Col,Code_Row,Float_Val,Str_Val) select Link_SF,Link_Col,Code_Row,Float_Val,Str_Val from dbo.report_dinamics_all where link_sf = @varKSsFLink

select @varKSLinkF = link_form from dbo.report_saved_forms where link_saved_form = @varKSsFLink
select @tab = orders from dbo.report_tables where link_table = @link_table

select @cAccount = rtrim(rav.str_val) 
from dbo.report_atribut_values as rav 
where rav.link_saved_form = @varKSsFLink and rav.code_atr like 'REPORTS_ATR_ACC%'

declare @t_lsf table (link_saved_form int)
insert into @t_lsf (link_saved_form) select link_saved_form from dbo.[RA_SELECT_SVOD_FORMS](@varKSsFLink) where FilterField = 1

insert into #report_dinamics (Link_SF,Link_Col,Code_Row,Float_Val,Str_Val) select Link_SF,Link_Col,Code_Row,Float_Val,Str_Val from dbo.report_dinamics_all where link_sf in (select link_saved_form from @t_lsf)

--select * from #report_dinamics

-- создаём временную табличку в которую будем помещать данные всех форм
declare @table2 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), dnd tinyint, link varchar(50), wTab tinyint, lsf int)
create table #table3 (nn int IDENTITY(1,1), col1 numeric(20,4), col2 numeric(20,4),lsf int)

declare the_cursor cursor local static for
select link_saved_form from @t_lsf

open the_cursor
fetch next from the_cursor into @LSF
while @@fetch_status = 0
begin
	select @iLink_Table = @link_table 
	if @tab in (1,3) begin
		insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab,lsf)
		select coalesce(rd1.Str_Val,''),substring(coalesce(rd2.Str_Val,''),1,3),substring(coalesce(rd3.Str_Val,''),1,11),substring(coalesce(rd4.Str_Val,''),1,2),left(ltrim(coalesce(rd5.Str_Val,'')),3)+left(ltrim(coalesce(rd6.Str_Val,'')),14),@cAccount,isnull(rd7.Float_Val,0.00),isnull(rd8.Float_Val,0.00),substring(coalesce(rd9.Str_Val,''),1,9),case when cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) not in ('0','1') then NULL else cast(rtrim(isnull(rd10.Str_Val,'0')) as tinyint) end,srows.Code_Row, @tab,@LSF
		from (
				select Code_Row from #report_dinamics
				where link_sf = @LSF 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)
	end
	if @tab = 2 begin
		insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab,lsf)
		select 
			coalesce(rd1.Str_Val,''),
			substring(coalesce(rd2.Str_Val,''),1,3),
			substring(coalesce(rd3.Str_Val,''),1,11),
			substring(coalesce(rd4.Str_Val,''),1,2),
			left(ltrim(coalesce(rd5.Str_Val,'')),3)+left(ltrim(coalesce(rd6.Str_Val,'')),4)+left(ltrim(coalesce(rd7.Str_Val,'')),7)+left(ltrim(coalesce(rd8.Str_Val,'')),3),
			@cAccount,
			isnull(rd9.Float_Val,0.00),
			isnull(rd10.Float_Val,0.00),
			substring(coalesce(rd11.Str_Val,''),1,9),
			case 
				when 
					cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) not in ('0','1') 
				then 
					NULL 
				else 
					cast(rtrim(isnull(rd12.Str_Val,'0')) as tinyint) 
			end,
			srows.Code_Row, 
			@tab,
			@LSF
		from (
				select Code_Row from #report_dinamics
				where link_sf = @LSF and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
				group by Code_Row
			 ) as srows
		left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd11 on rd11.link_sf = @LSF and rd11.Code_Row = srows.Code_Row and 11 = (select Orders from dbo.report_coloumns where link_col = rd11.link_col) and rd11.link_col = (select link_col from dbo.report_coloumns where Orders = 11 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd12 on rd12.link_sf = @LSF and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12 and Link_Table = @iLink_Table)
	end
	if @tab = 4 begin
		insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab, lsf)
		select coalesce(rd1.Str_Val,''),substring(coalesce(rd2.Str_Val,''),1,3),substring(coalesce(rd3.Str_Val,''),1,11),substring(coalesce(rd4.Str_Val,''),1,2),'',@cAccount,isnull(rd6.Float_Val,0.00),isnull(rd7.Float_Val,0.00),substring(coalesce(rd8.Str_Val,''),1,9),NULL,srows.Code_Row, @tab, @LSF
		from (
				select Code_Row from #report_dinamics
				where link_sf = @LSF 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)
	end
    fetch next from the_cursor into @LSF
end
close the_cursor
deallocate the_cursor

--в таблице @table2 строчки данных всех форм. 
--select * from @table2

insert into #table3 (col1,col2,lsf)
select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
where rtrim(link) = 'итог_денежные_рассчёты' and rtrim(@inCode_Row) = rtrim(link) 
group by lsf

insert into #table3 (col1,col2,lsf)
select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
where rtrim(link) = 'итог_неденежные_рассчёты' and rtrim(@inCode_Row) = rtrim(link) 
group by lsf

insert into #table3 (col1,col2,lsf)
select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
where rtrim(link) = 'Итого' and rtrim(@inCode_Row) = rtrim(link) 
group by lsf

if  right(rtrim(@cAccount),8) in ('30404000','21100560','21100660','21200560','21200660','30800730','30800830','30900730','30900830') begin 

	insert into #table3 (col1,col2,lsf)
	select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
	where right(rtrim(link),1) like '[0-9]'
	and substring(rtrim(@inCode_Row),1,3) = left(rtrim(ppp)+'000',3) /* ППП */
	and substring(rtrim(@inCode_Row),4,11) = left(ltrim(rtrim(okato))+'           ',11) /* OКATO */
	and substring(ltrim(@inCode_Row),15,2) = right('00'+ltrim(rtrim(el_bud)),2) /* Эл. Бюдж. */
	and substring(ltrim(@inCode_Row),34,9) = right('000000000'+ltrim(rtrim(korr_acc)),9) /* Корр. Счёт */
	group by lsf
end

if  right(rtrim(@cAccount),8) in ('40101241','40101180') begin 
	insert into #table3 (col1,col2,lsf)
	select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
	where right(rtrim(link),1) like '[0-9]'
	and substring(rtrim(@inCode_Row),1,3) = left(rtrim(ppp)+'000',3) /* ППП */
	and substring(ltrim(@inCode_Row),17,17)= left(rtrim(rtrim(KBK))+'00000000000000000',17) /* КБК */
	and substring(ltrim(@inCode_Row),34,9) = right('000000000'+ltrim(rtrim(korr_acc)),9) /* Корр. Счёт */
	group by lsf
end

if  right(rtrim(@cAccount),8) in ('40101251','20612560','20612660','20702540','30101810','30212830','40101151','20505560','20505660','30101710','20702640','20505000','20612000','20702000','30101000','30212000') begin
--print substring(rtrim(@inCode_Row),1,3)
--print substring(rtrim(@inCode_Row),4,11)
--print substring(ltrim(@inCode_Row),15,2)
--print substring(ltrim(@inCode_Row),17,17)
--print substring(ltrim(@inCode_Row),34,9)
--
--select * from @table2

	insert into #table3 (col1,col2,lsf)
	select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
	where right(rtrim(link),1) like '[0-9]'
	and substring(rtrim(@inCode_Row),1,3) = left(rtrim(ppp)+'000',3) /* ППП */
	and substring(rtrim(@inCode_Row),4,11) = left(ltrim(rtrim(okato))+'           ',11) /* OКATO */
	and substring(ltrim(@inCode_Row),15,2) = right('00'+ltrim(rtrim(el_bud)),2) /* Эл. Бюдж. */
	and substring(ltrim(@inCode_Row),17,17)= left(rtrim(rtrim(KBK))+'00000000000000000',17) /* КБК */
	and substring(ltrim(@inCode_Row),34,9) = right('000000000'+ltrim(rtrim(korr_acc)),9) /* Корр. Счёт */
	group by lsf
end

-- для 2011 года 
IF NOT EXISTS(SELECT * FROM #table3)
	insert into #table3 (col1,col2,lsf)
	select isnull(SUM(summa_db),0.0),isnull(SUM(summa_kr),0.0),lsf from @table2
	where right(rtrim(link),1) like '[0-9]'
	and substring(rtrim(@inCode_Row),1,3) = left(rtrim(ppp)+'000',3) /* ППП */
	and substring(rtrim(@inCode_Row),4,11) = left(ltrim(rtrim(okato))+'           ',11) /* OКATO */
	and substring(ltrim(@inCode_Row),15,2) = right('00'+ltrim(rtrim(el_bud)),2) /* Эл. Бюдж. */
	and substring(ltrim(@inCode_Row),17,17)= left(rtrim(rtrim(KBK))+'00000000000000000',17) /* КБК */
	and substring(ltrim(@inCode_Row),34,9) = right('000000000'+ltrim(rtrim(korr_acc)),9) /* Корр. Счёт */
	group by lsf


insert into #table3 (col1,col2,lsf) 
select 0.00, 0.00, link_saved_form from dbo.[RA_SELECT_SVOD_FORMS](@varKSsFLink) where FilterField = 1 and link_saved_form not in (select lsf from #table3)


set @sql_script = '
select 
	A.nn as ord,
	(select [name] from dbo.departments where link = (select link_organization from dbo.report_saved_forms where link_saved_form = A.lsf)) as org, 
	A.col1 as '+case @tab when 1 then 'col7' when 2 then 'col9'  when 3 then 'col7' else 'col6' end+', 
	A.col2 as '+case @tab when 1 then 'col8' when 2 then 'col10' when 3 then 'col8' else 'col7' end+', 1 as FilterField, 1 as childrens, 0 as Link_Tree, 1 as Link_Self, 0 as Link_Tree_Self
from #table3 as A'

PRINT @sql_script
execute(@sql_script)

drop table #report_dinamics
drop table #table3

GO
GRANT EXECUTE ON dbo.[RT_ANALIZ_25] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
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_PRINT_114_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_114_ITOG]
GO

/*

	c Кейсистемс (Keysystems), 2011
	Печать форм 114 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_114_ITOG
	@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

set @varKSiParam = 0

if object_id('tempdb..#Param_Print') is NOT NULL
begin
	select @varKSiParam = convert(int, Value) from #Param_Print where Param = 'Poditog'
	select @varKSiNoItog = convert(int, Value) from #Param_Print where Param = 'NoPoditog'
end
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, @iYear int
select @iLF = Link_Form, @iYear =YEAR(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(1000), Col2 varchar(1000), Col3 varchar(1000), 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

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'
	   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

select * from #doh order by left(code, 3), orders, Code
drop table #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(2000), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 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)
exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1

---------------------------------------------
/*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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,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(col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(R.Code,3) + '00000000000000000', max(SPR.NAME), max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(col10,3) + '00000000000000000'
	from #rash R left join dbo.[R_SPR_ADM_2011] SPR on left(R.Code,3) = SPR.Code
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
	group by left(R.Code,3) + '00000000000000000', left(Col10,3) + '00000000000000000'
end

   UPDATE #rash
   SET col1 = SPR.Name
   FROM dbo.[R_SPR_ADM_2011] SPR
   WHERE substring(#rash.code,4,17) = '00000000000000000' AND SPR.CODE = LEFT(#rash.code,3) AND #rash.col1 = ''

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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), left(Col10,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(Col10,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
----------------------------------------------

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, Col10)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, '00096000000000000000', 'Расходы - всего', '200','9600', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), '00096000000000000000'
	from #rash
	where COL6 NOT IN ('000','200', '210', '220', '230', '240','250', '260', '300', '500', '600')
end

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 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, Col10 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))
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, '500', '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,4,3) IN ('710', '720', '510', '520') and substring(D.code,11,10) = '0000000000' --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 * 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 ALL ON dbo.[RO_PRINT_114_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[X_UPDATE_RECEPTION_CASH_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_UPDATE_RECEPTION_CASH_TABLE]
GO


/*
© Кейсистемс (Keysystems), 2005
Соколов С.В.
*/

CREATE    PROCEDURE X_UPDATE_RECEPTION_CASH_TABLE
	@varKSintLINK	int	OUTPUT,
	@varKSintLINK_UP	int,
	@varKSintSource		int,
	@iVidSr				int,
	@varKSintKBK		int,
	@varKSintEKR		int,
	@varKSintDOP_CLASS	int,
	@varKSintSUMMA 		numeric(19,2),
	@varKSnRECORD_NO	int,
	@cReason			varchar(254),
	@cTitle				varchar(254),
	@cKP				char(2)


AS
Declare
	@varKSERROR	int,
	@varKSRowCount	int,
	@varKStrancount	int

SET @varKStrancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
	IF @varKSintLINK is null OR @varKSintLINK = 0
	BEGIN
		INSERT INTO RECEPTION_CASH_TABLE(LINK_UP, SOURCE, KBK, EKR, DOP_CLASSIF, SUMMA, RECORD_NO, REASON, TITLE, KP, VID_SR)
			VALUES (@varKSintLINK_UP, @varKSintSource, @varKSintKBK, @varKSintEKR, @varKSintDOP_CLASS, @varKSintSUMMA, @varKSnRECORD_NO, @cReason, @cTitle, @cKP, @iVidSr)
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE RECEPTION_CASH_TABLE
			SET LINK_UP = @varKSintLINK_UP,
				RECORD_NO =@varKSnRECORD_NO,
				SOURCE = @varKSintSource,
				KBK = @varKSintKBK,
				EKR = @varKSintEKR,
				DOP_CLASSIF = @varKSintDOP_CLASS,
				SUMMA = @varKSintSUMMA,
				REASON = @cReason,
				TITLE = @cTitle,
				KP = @cKP,
				VID_SR = @iVidSr
		WHERE LINK = @varKSintLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BK_PRINTDOC_F0504833]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BK_PRINTDOC_F0504833]
GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   PROCEDURE dbo.BK_PRINTDOC_F0504833
AS BEGIN
	DECLARE @intANALIT INT,
		@intPRN_RUK	INT,
		@intPRN_GLBUH	INT

	DECLARE @RES0 TABLE  (LINK INT, LINK_REESTR INT)
	
	DECLARE @ERR  TABLE (NUMBER VARCHAR(254), [DATE] DATETIME, DOC_LINK INT, VALUE VARCHAR(254), ERR_TYPE INT)
	DECLARE @RES1 TABLE (
		LINK_DOC INT,
		DOC_DATE VARCHAR (10),
		PROV_DATE VARCHAR (10),
		DOC_NUM VARCHAR(30),
		COMMENT VARCHAR (254),
		DOC_TITLE VARCHAR(254),
		DEP_LINK INT,
		DEP_NAME VARCHAR(254),
		OKPO VARCHAR(254),
		SUBDIV VARCHAR(254),
		SUBDIV_C VARCHAR(10),
		REASON VARCHAR(254),
		DT VARCHAR(254),
		KT VARCHAR(254),
		QTY NUMERIC(20,4),
		SUMMA NUMERIC(20,2),
		GLBUH VARCHAR(254),
		ORD1 INT, ORD2 INT,
		LINK_G2 INT,
		PRN_ANALIT INT,
		APD_NAME VARCHAR (3000),
		APK_NAME VARCHAR (3000),
		PRN_RUK	INT,
		PRN_GLBUH INT,
		LIST_JO	VARCHAR (100),
		ECON_OPER INT
	)

	INSERT INTO @RES1
	SELECT 
		T1.LINK_DOC,
		T1.DOC_DATE,
		T1.PROV_DATE,
		
		T1.DOC_NUM,
		T1.COMMENT, '',
		T1.DEP_LINK, T1.DEP_NAME, T1.OKPO,
		T2.OTDEL_NAME, T2.OTDEL_CODE, 
		T1.REASON,
		T1.DT,
		T1.KT,
		T1.QTY,
		T1.SUMMA,
		ISNULL (dbo.BK_Get_EMPL_Signature (T2.FACE_LINK, DEFAULT), ''),
		T1.ORD1, T1.ORD2,
		T1.LINK_G2,
		PRN_ANALIT,
		T1.APD_NAME,
		T1.APK_NAME,
		PRN_RUK, 
		PRN_GLBUH,
		LIST_JO,
		ECON_OPER 
	FROM dbo.BK_PrintDoc_F0504033_DATA ('PRINT_DOCUMENTS_F0504833', DEFAULT) T1
	INNER JOIN dbo.DOCUMENTS_F0504833 T2 ON (T2.LINK = T1.LINK_DOC)

	INSERT INTO @ERR (NUMBER, [DATE], DOC_LINK, VALUE, ERR_TYPE)
	SELECT DISTINCT DOC_NUM, DOC_DATE, LINK_DOC, 'Не указана организация', 2
	FROM @RES1 WHERE DEP_LINK IS NULL

	DELETE FROM @RES1 WHERE LINK_DOC IN (SELECT DOC_LINK FROM @ERR)

	SELECT * FROM @RES1 order by link_doc, ORD1, ORD2

	
	SELECT * FROM @RES0

	SELECT * FROM @ERR WHERE ERR_TYPE = 1
	SELECT * FROM @ERR WHERE ERR_TYPE = 2
	SELECT * FROM @ERR WHERE ERR_TYPE = 3

	DECLARE @varKSLOG_STR VARCHAR(1000), @varKSnLink int
	DECLARE #TMP_CUR2 CURSOR LOCAL FOR 
		SELECT DP.LINK, LTRIM(RTRIM(NUMBER)) + ' от ' + CONVERT(VARCHAR(10), DATE, 104)
		FROM DOCUMENTS_F0504833             DP, dbo.BufferGetTableByID('PRINT_DOCUMENTS_F0504833') B
		WHERE DP.LINK = B.LINK
	OPEN #TMP_CUR2 
	FETCH #TMP_CUR2 INTO @varKSnLink, @varKSLOG_STR
	WHILE @@FETCH_STATUS = 0 BEGIN
		EXEC dbo.XD_GENERATE_EVENT_SO 'DOCUMENTS_F0504833', @varKSLOG_STR, @varKSnLink
		FETCH #TMP_CUR2 INTO @varKSnLink, @varKSLOG_STR
	END
	CLOSE #TMP_CUR2 
	DEALLOCATE #TMP_CUR2 

	EXEC dbo.BufferClear
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.[SZV4_EXPORT_PFR_700_10]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_EXPORT_PFR_700_10]

GO

CREATE      PROCEDURE [dbo].SZV4_EXPORT_PFR_700_10 (
@Link int /*Ссылка на расчет*/
) AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT  ON

DECLARE @SPV_ONLY TINYINT

SET @SPV_ONLY = (SELECT TOP 1 [type] FROM dbo.SA_SZV4_PACHKA WHERE link = @Link)

--Опись на пачку
CREATE TABLE #ADV63 (
	[YEAR] NUMERIC(4),
	[NGROUP] NUMERIC(5),
	[DOCCOUNT] int,
	PERS_CNT int,
	[cGRP] varchar(5),
	[OPT1] tinyint,
	[OPT2] tinyint,
	[OPT3] tinyint,
	[OPT4] tinyint,
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	[PFNUMBER] VARCHAR(20),
	DEP_NAME VARCHAR(254),
	OKPO VARCHAR(40),
	INN VARCHAR(12),
	KPP VARCHAR(9),
	CODE VARCHAR(20),
	[PER] TINYINT,
	[PER10] TINYINT,
	[TYPE] TINYINT, 	
	[PER_EDT] TINYINT,
	[YEAR_EDT] INT,
	DATE_CRT datetime,
	DATE_DOC datetime,
	SZV TINYINT )	

	INSERT INTO #ADV63
	exec dbo.SZV4_PRINT_ADV63 @Link

	--Вдруг ПФР номер не указан
	UPDATE #ADV63 SET PFNUMBER = REPLACE(SPACE(12),' ','0') WHERE LEN(RTRIM(LTRIM(COALESCE(PFNUMBER,'')))) < 12

CREATE TABLE #SZV61 (
	[YEAR] int,
	INN VARCHAR(12),
	KPP VARCHAR(9),
	OKPO VARCHAR(40),
	CODE VARCHAR(30),
	[PER] TINYINT,
	[PER10] TINYINT,
	[TYPE] TINYINT,
	[PER_EDT] TINYINT,
	[YEAR_EDT] DATETIME,
	[ID] int,
	[NGROUP] int,
	[PF_NUM] VARCHAR(20),
	[FIO] VARCHAR(254),
	[FM] VARCHAR(100),
	[IM] VARCHAR(100),
	[OT] VARCHAR(100),
	[ADDRESS] VARCHAR(254),
	[ADDRESS2] VARCHAR(254),
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	[DOP] numeric(18,2),
	[ID_EX] int,
	[DATE_BEGIN] datetime,
	[DATE_END] datetime,
	[STR_DIS] varchar(254),
	dper_vn_m numeric(10,2),
	dper_vn_d numeric(10,2),
	[STR_VAC2] varchar(254),
	dper_oz_m numeric(10,2),
	dper_oz_d numeric(10,2),
	[TU_CODE] varchar(254),
	ter_usl varchar(254),
	ter_koef numeric(10,2),
	[OS_CODE] varchar(254),
	osob_usl varchar(254),
	osob_spis varchar(254),
	[EX_CODE] varchar(254),
	is_dop_m numeric(10,2), 
	is_dop_d numeric(10,2),
	is_dop varchar(254),
	f_is_dop varchar(254),
	[P_CODE] varchar(254),
	ud_dop_m numeric(10,2),
	ud_dop_d numeric(10,2),
	ud_dop_k numeric(10,2),
	f_ud_dop varchar(254),
	PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime )

IF @SPV_ONLY = 1
BEGIN
	INSERT INTO #SZV61
	exec dbo.SZV4_PRINT_SZV61 @Link
	
	update #SZV61 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2), f_is_dop = UPPER(f_is_dop)
END

SELECT 
	[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [TYPE], [PER_EDT], [YEAR_EDT],
	[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
	[INSUR], [INSUR1], [GAIN], [GAIN1], [DOP], [ID_EX], [DATE_BEGIN], [DATE_END],
	[STR_DIS], dper_vn_m, dper_vn_d, [STR_VAC2], dper_oz_m, dper_oz_d,
	[TU_CODE], ter_usl, ter_koef,
	[OS_CODE], osob_usl, osob_spis, 
	[EX_CODE], 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,
	PFNUMBER, DEP_NAME, DATE_CRT, DATE_DOC
INTO #PERS_INFO2
FROM #SZV61

CREATE TABLE #SZV62 (
	[YEAR] int, 
	INN VARCHAR(12),
	KPP VARCHAR(9),
	OKPO VARCHAR(40),
	REG_NOM_PF varchar(20),
	CODE VARCHAR(30),
	[TYPE] TINYINT,
	[PER] TINYINT,
	[PER10] TINYINT,
	[PER_EDT] TINYINT,
	[YEAR_EDT] DATETIME,
	[CNT] int,
	[ID] int,
	[NGROUP] int,
	[NDOC] int,
	[FIO] VARCHAR(254),
	[FM] VARCHAR(100),
	[IM] VARCHAR(100),
	[OT] VARCHAR(100),
	[ADDRESS] VARCHAR(254),
	[ADDRESS2] VARCHAR(254),
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	[DATE_BEGIN] datetime,
	[DATE_END] datetime,
	PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime )

IF @SPV_ONLY = 1
BEGIN
	INSERT INTO #SZV62
	exec dbo.SZV4_PRINT_SZV62 @Link

	update #SZV62 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2)

	INSERT INTO #PERS_INFO2(
		[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [TYPE], [PER_EDT], [YEAR_EDT],
		[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
		[INSUR], [INSUR1], [GAIN], [GAIN1], [DOP], [ID_EX], [DATE_BEGIN], [DATE_END],
		[STR_DIS], dper_vn_m, dper_vn_d, [STR_VAC2], dper_oz_m, dper_oz_d,
		[TU_CODE], ter_usl, ter_koef,
		[OS_CODE], osob_usl, osob_spis, 
		[EX_CODE], 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,
		PFNUMBER, DEP_NAME, DATE_CRT, DATE_DOC)
	SELECT 
		[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [TYPE], [PER_EDT], [YEAR_EDT],
		[ID], [NGROUP], [PF_NUM] = PFNUMBER, [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
		[INSUR], [INSUR1], [GAIN], [GAIN1], [DOP] = 0, [ID_EX]=1, [DATE_BEGIN], [DATE_END],
		[STR_DIS]=NULL, dper_vn_m=NULL, dper_vn_d=NULL, [STR_VAC2]=NULL, dper_oz_m=NULL, dper_oz_d=NULL,
		[TU_CODE]=NULL, ter_usl=NULL, ter_koef=NULL,
		[OS_CODE]=NULL, osob_usl=NULL, osob_spis=NULL, 
		[EX_CODE]=NULL, is_dop_m=NULL, is_dop_d=NULL, is_dop=NULL, f_is_dop=NULL,
		[P_CODE]=NULL, ud_dop_m=NULL, ud_dop_d=NULL, ud_dop_k=NULL, f_ud_dop=NULL,
		PFNUMBER = REG_NOM_PF, DEP_NAME, DATE_CRT, DATE_DOC	
	FROM #SZV62
END	

CREATE TABLE #SPV1 (
	[YEAR] int,
	INN VARCHAR(12),
	KPP VARCHAR(9),
	OKPO VARCHAR(40),
	CODE VARCHAR(20),
	[PER] TINYINT,
	[PER10] TINYINT,
	[TYPE] TINYINT,
	[ID] int,
	[NGROUP] int,
	[PF_NUM] VARCHAR(20),
	[FIO] VARCHAR(254),
	[FM] VARCHAR(100),
	[IM] VARCHAR(100),
	[OT] VARCHAR(100),
	[ADDRESS] VARCHAR(254),
	[ADDRESS2] VARCHAR(254),
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	[ID_EX] int,
	[DATE_BEGIN] datetime,
	[DATE_END] datetime,
	[STR_DIS] varchar(254),
	dper_vn_m numeric(10,2),
	dper_vn_d numeric(10,2),
	[STR_VAC2] varchar(254),
	dper_oz_m numeric(10,2),
	dper_oz_d numeric(10,2),
	[TU_CODE] varchar(254),
	ter_usl varchar(254),
	ter_koef numeric(10,2),
	[OS_CODE] varchar(254),
	osob_usl varchar(254),
	osob_spis varchar(254),
	[EX_CODE] varchar(254),
	is_dop_m numeric(10,2), 
	is_dop_d numeric(10,2),
	is_dop varchar(254),
	f_is_dop varchar(254),
	[P_CODE] varchar(254),
	ud_dop_m numeric(10,2),
	ud_dop_d numeric(10,2),
	ud_dop_k numeric(10,2),
	f_ud_dop varchar(254),
	PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime,
	DD INT, MM varchar(10), YY INT
	 )

IF @SPV_ONLY = 2
BEGIN
	INSERT INTO #SPV1
	exec dbo.SZV4_PRINT_SPV1 @Link

	update #SPV1 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2)

	INSERT INTO #PERS_INFO2(
		[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [TYPE], [PER_EDT], [YEAR_EDT],
		[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
		[INSUR], [INSUR1], [GAIN], [GAIN1], [DOP], [ID_EX], [DATE_BEGIN], [DATE_END],
		[STR_DIS], dper_vn_m, dper_vn_d, [STR_VAC2], dper_oz_m, dper_oz_d,
		[TU_CODE], ter_usl, ter_koef,
		[OS_CODE], osob_usl, osob_spis, 
		[EX_CODE], 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,
		PFNUMBER, DEP_NAME, DATE_CRT, DATE_DOC)

	SELECT 
		[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [TYPE], [PER_EDT]=0, [YEAR_EDT]=0,
		[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
		[INSUR], [INSUR1], [GAIN], [GAIN1], [DOP]=0, [ID_EX], [DATE_BEGIN], [DATE_END],
		[STR_DIS], dper_vn_m, dper_vn_d, [STR_VAC2], dper_oz_m, dper_oz_d,
		[TU_CODE], ter_usl, ter_koef,
		[OS_CODE], osob_usl, osob_spis, 
		[EX_CODE], 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,
		PFNUMBER, DEP_NAME, DATE_CRT, DATE_DOC
	FROM #SPV1
END	

DECLARE @NN INT, @PN INT, @ON INT
SELECT @NN = 0, @PN = 0, @ON = 0

SELECT *
INTO #PERS_INFO 
FROM #PERS_INFO2 ORDER BY NGROUP, [ID]

DECLARE @PI_NGROUP INT, @PI_ID INT
DECLARE @Cur_PI CURSOR
SET @Cur_PI = CURSOR FORWARD_ONLY

FOR select NGROUP, [ID]  from #PERS_INFO order by NGROUP, [ID]

OPEN @Cur_PI
FETCH NEXT FROM @Cur_PI INTO @PI_NGROUP, @PI_ID
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SET @NN = (CASE WHEN @PI_NGROUP <> @PN THEN 1 ELSE (CASE WHEN @ON <> @PI_ID THEN @NN + 1 ELSE @NN END) END)
		SET @PN = (CASE WHEN @PI_NGROUP <> @PN THEN @PI_NGROUP ELSE @PN END)

		UPDATE A
		SET 
			ID = @NN
		FROM #PERS_INFO A 
		WHERE NGROUP = @PI_NGROUP AND ID = @PI_ID

		SET @ON = @NN				

	END

	FETCH NEXT FROM @Cur_PI INTO @PI_NGROUP, @PI_ID
END

CLOSE @Cur_PI
DEALLOCATE @Cur_PI

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------

DECLARE @Cur1 CURSOR, @NGROUP int /*Номер пачки*/, @lcFNAME varchar(254) /*регистрационный номер ПФР*/, 
	@TIPD varchar(254), @DATE_DOC VARCHAR(10), 
	@INN VARCHAR(12), @KPP VARCHAR(9), @DEP_NAME VARCHAR(254), @PFNUMBER VARCHAR(254), @PACHNUM VARCHAR(5),
	@DOCCOUNT VARCHAR(10), @TYPDOC VARCHAR(254), @PERSCNT VARCHAR(3), @DATE_CRT VARCHAR(10),
	@YEAR VARCHAR(4), @SZV tinyint, @TYP_SVED VARCHAR(20),
	@VID_KOR VARCHAR(20), @INSUR VARCHAR(20), @INSUR1 VARCHAR(20), @GAIN VARCHAR(20), @GAIN1 VARCHAR(20), 
	@EGRUL varchar(15), @PER VARCHAR(1), @PER_EDT VARCHAR(1), @YEAR_EDT VARCHAR(4), @TYPE VARCHAR(20),
	@KATEG VARCHAR(20), @PER_NAME VARCHAR(20), @PER_EDT_NAME VARCHAR(20)

SELECT 
	@EGRUL = LTRIM(RTRIM(EGRUL))
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
WHERE P.link = @Link

SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
select 	NGROUP, 
	FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END) + '-ORG-' + RTRIM(LTRIM(COALESCE(PFNUMBER,''))) + '-DCK-' + REPLACE(STR(COALESCE(cGRP,''),5),' ','0') + '-DPT-000000-DCK-00000.XML',
	INN = 	RTRIM(LTRIM(COALESCE(INN,''))),
	KPP = RTRIM(LTRIM(COALESCE(KPP,''))),
	DEP_NAME = RTRIM(LTRIM(COALESCE(DEP_NAME,''))),
	PFNUMBER = RTRIM(LTRIM(COALESCE(PFNUMBER,''))),
	PACHNUM = RTRIM(LTRIM(CONVERT(VARCHAR(10),NGROUP))), 	
	DOCCOUNT = RTRIM(LTRIM(CONVERT(VARCHAR(10),DOCCOUNT))), 	
	TYPDOC = CASE WHEN OPT2 = 1 THEN 'СПВ-1' ELSE (CASE WHEN SZV = 1 THEN 'СЗВ-6-1' ELSE 'СЗВ-6-2' END) END,
	PERSCNT = RTRIM(LTRIM(STR(PERS_CNT))),
	DATE_CRT = CONVERT(VARCHAR(10),DATE_CRT,104),
	DATE_DOC = CONVERT(VARCHAR(10),DATE_DOC,104),
	[YEAR] = CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END),
	SZV,
	TYP_SVED = (CASE WHEN OPT1 = 1 THEN 'ИСХОДНАЯ' else (CASE WHEN OPT2 = 1 THEN 'ПЕНСИОННАЯ' else '' end) end),
	VID_KOR = (CASE WHEN OPT3 = 1 THEN 'КОРРЕКТИРУЮЩАЯ' else (CASE WHEN OPT4 = 1 THEN 'ОТМЕНЯЮЩАЯ' else '' end) end),
	INSUR = RTRIM(LTRIM(STR(COALESCE([INSUR],0),15,2))), 
	INSUR1 = RTRIM(LTRIM(STR(COALESCE([INSUR1],0),15,2))),
	GAIN = RTRIM(LTRIM(STR(COALESCE([GAIN],0),15,2))),
	GAIN1 = RTRIM(LTRIM(STR(COALESCE([GAIN1],0),15,2))),
	[PER] = CONVERT(VARCHAR(1),CASE WHEN [PER] = 0 THEN [PER10] ELSE [PER] END),
	[TYPE], 
	PER_EDT = CONVERT(VARCHAR(1),[PER_EDT]), 
	YEAR_EDT = CONVERT(VARCHAR(4),[YEAR_EDT]), 
	PER_EDT_NAME = CASE PER_EDT WHEN 1 THEN 'I квартал' WHEN 2 THEN 'I полугодие' WHEN 3 THEN '9 месяцев' WHEN 4 THEN 'год' ELSE '' END,
	[TYPE] = (CASE [TYPE] WHEN 1 THEN 'ИСХОДНАЯ' WHEN 2 THEN 'КОРРЕКТИРУЮЩАЯ' WHEN 3 THEN 'ОТМЕНЯЮЩАЯ' ELSE '' end),
	KATEG = CODE,
	PER_NAME = CASE (CASE WHEN [PER] = 0 THEN [PER10] ELSE [PER] END) WHEN 1 THEN 'I квартал' WHEN 2 THEN 'I полугодие' WHEN 3 THEN '9 месяцев' WHEN 4 THEN 'год' ELSE '' END
from #ADV63 order by NGROUP

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @NGROUP, @lcFNAME, @INN, @KPP, @DEP_NAME, @PFNUMBER, @PACHNUM, @DOCCOUNT, @TYPDOC, @PERSCNT, @DATE_CRT, @DATE_DOC, @YEAR,
	@SZV, @TYP_SVED, @VID_KOR, @INSUR, @INSUR1, @GAIN, @GAIN1, @PER, @TYPE, @PER_EDT, @YEAR_EDT, @PER_EDT_NAME, @TYPE, @KATEG, @PER_NAME
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		  SELECT @lcFNAME, 'OEM' --Имя файла
		  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
		  UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
			UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
			
			UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
			    UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
			    UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
			UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
			
			UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">'
			  
			  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>'
			   
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<СоставительПачки>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НалоговыйНомер>'
			       UNION ALL SELECT @lcFNAME, SPACE(5) + '<ИНН>' + @INN + '</ИНН>'
			       UNION ALL SELECT @lcFNAME, SPACE(5) + '<КПП>' + @KPP + '</КПП>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '</НалоговыйНомер>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<КодЕГРЮЛ>' + @EGRUL + '</КодЕГРЮЛ>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаименованиеОрганизации>' + @DEP_NAME + '</НаименованиеОрганизации>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаименованиеКраткое>' + @DEP_NAME + '</НаименованиеКраткое>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<РегистрационныйНомер>' + @PFNUMBER + '</РегистрационныйНомер>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '</СоставительПачки>'
			   
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерПачки>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<Основной>' + @PACHNUM + '</Основной>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '</НомерПачки>'
			   
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<СоставДокументов>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<Количество>' + '1' /*@DOCCOUNT*/ + '</Количество>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаличиеДокументов>'
			       UNION ALL SELECT @lcFNAME, SPACE(5) + '<ТипДокумента>СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>'
			       UNION ALL SELECT @lcFNAME, SPACE(5) + '<Количество>' + @PERSCNT + '</Количество>'
			     UNION ALL SELECT @lcFNAME, SPACE(4) + '</НаличиеДокументов>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '</СоставДокументов>'

			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ДатаСоставления>' + @DATE_DOC + '</ДатаСоставления>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ТипСведений>' + @TYPE + '</ТипСведений>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодКатегории>' + @KATEG + '</КодКатегории>'

			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОтчетныйПериод>'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE WHEN @YEAR = '2010' THEN (CASE @PER WHEN '2' THEN '1' ELSE '2' END) ELSE @PER END + '</Квартал>'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR + '</Год>'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' 
							+	CASE WHEN @YEAR = '2010' THEN
										CASE @PER 
											WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '4' THEN 'С 01.07.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END
									ELSE
										CASE @PER 
											WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
											WHEN '2' THEN 'С 01.04.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '3' THEN 'С 01.07.'+@YEAR+' ПО 30.09.'+@YEAR
											WHEN '4' THEN 'С 01.10.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END									
								END	+ '</Название>'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '</ОтчетныйПериод>'

			   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КорректируемыйОтчетныйПериод>' WHERE @PER_EDT <> '0'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE WHEN @YEAR_EDT = '2010' THEN (CASE @PER_EDT WHEN '2' THEN '1' ELSE '2' END) ELSE @PER_EDT END + '</Квартал>' WHERE @PER_EDT <> '0'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' WHERE @PER_EDT <> '0'
				UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' + 
								CASE WHEN @YEAR_EDT = '2010' THEN
										CASE @PER_EDT 
											WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '4' THEN 'С 01.07.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END
									ELSE
										CASE @PER_EDT 
											WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
											WHEN '2' THEN 'С 01.04.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '3' THEN 'С 01.07.'+@YEAR+' ПО 30.09.'+@YEAR
											WHEN '4' THEN 'С 01.10.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END									
								END	+ '</Название>' WHERE @PER_EDT <> '0'
			   UNION ALL SELECT @lcFNAME, SPACE(3) + '</КорректируемыйОтчетныйПериод>' WHERE @PER_EDT <> '0'

		        UNION ALL SELECT @lcFNAME, SPACE(3) + '<СуммаВзносовНаСтраховую>' 
		        UNION ALL SELECT @lcFNAME, SPACE(4) + '<Начислено>' + @INSUR + '</Начислено>'  
		        UNION ALL SELECT @lcFNAME, SPACE(4) + '<Уплачено>' + @INSUR1 + '</Уплачено>'  
		       UNION ALL SELECT @lcFNAME, SPACE(3) + '</СуммаВзносовНаСтраховую>' 

		        UNION ALL SELECT @lcFNAME, SPACE(3) + '<СуммаВзносовНаНакопительную>' 
		        UNION ALL SELECT @lcFNAME, SPACE(4) + '<Начислено>' + @GAIN + '</Начислено>'  
		        UNION ALL SELECT @lcFNAME, SPACE(4) + '<Уплачено>' + @GAIN1 + '</Уплачено>'  
		       UNION ALL SELECT @lcFNAME, SPACE(3) + '</СуммаВзносовНаНакопительную>'		       

			  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>'

		--Экспорт СЗВ-6-1
		DECLARE @Cur2 CURSOR, @PERS_ID int, @PERS_INFO1 varchar(8000), @PERS_INFO2 varchar(8000)
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR 
		Select ID,
		SPACE(1) +  CHAR(10) + '<СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>'  + CHAR(10)
		+	SPACE(3) + '<НомерВпачке>' + RTRIM(LTRIM(STR(ID+1))) + '</НомерВпачке>' + CHAR(10)
		+ 	SPACE(3) + '<ВидФормы>'+@TYPDOC+'</ВидФормы>' + CHAR(10)
		+ 	SPACE(3) + '<ТипСведений>'+ @TYPE +'</ТипСведений>' + CHAR(10)
		+ 	SPACE(3) + '<РегистрационныйНомер>'+ @PFNUMBER +'</РегистрационныйНомер>' + CHAR(10)
		+ 	SPACE(3) + '<НаименованиеКраткое>'+ @DEP_NAME +'</НаименованиеКраткое>' + CHAR(10)
		+ 	SPACE(3) + '<НалоговыйНомер>' + CHAR(10)
		+ 		SPACE(4) + '<ИНН>' + @INN + '</ИНН>' + CHAR(10)
		+ 		SPACE(4) + '<КПП>' + @KPP + '</КПП>' + CHAR(10)		
		+ 	SPACE(3) + '</НалоговыйНомер>' + CHAR(10)
		+ 	SPACE(3) + '<КодКатегории>' + @KATEG + '</КодКатегории>' + CHAR(10)
		+ 	SPACE(3) +  '<ОтчетныйПериод>' + CHAR(10)
		+ 	 SPACE(4) + '<Квартал>' + CASE WHEN @YEAR = '2010' THEN (CASE @PER WHEN '2' THEN '1' ELSE '2' END) ELSE @PER END + '</Квартал>'+ CHAR(10)
		+ 	 SPACE(4) + '<Год>' + @YEAR + '</Год>' + CHAR(10)
		+ 	 SPACE(4) + '<Название>' + 
								CASE WHEN @YEAR = '2010' THEN
										CASE @PER 
											WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '4' THEN 'С 01.07.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END
									ELSE
										CASE @PER 
											WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
											WHEN '2' THEN 'С 01.04.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '3' THEN 'С 01.07.'+@YEAR+' ПО 30.09.'+@YEAR
											WHEN '4' THEN 'С 01.10.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END	
								END	+ '</Название>' + CHAR(10)
		+ 	SPACE(3) + '</ОтчетныйПериод>' + CHAR(10)
		+	CASE WHEN @PER_EDT <> '0' THEN
		 	SPACE(3) +  '<КорректируемыйОтчетныйПериод>' + CHAR(10)
		+ 	 SPACE(4) + '<Квартал>' + CASE WHEN @YEAR_EDT = '2010' THEN (CASE @PER_EDT WHEN '2' THEN '1' ELSE '2' END) ELSE @PER_EDT END + '</Квартал>'+ CHAR(10)
		+ 	 SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' + CHAR(10)
		+ 	 SPACE(4) + '<Название>' + 
								CASE WHEN @YEAR_EDT = '2010' THEN
										CASE @PER_EDT 
											WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '4' THEN 'С 01.07.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END
									ELSE
										CASE @PER_EDT 
											WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
											WHEN '2' THEN 'С 01.04.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '3' THEN 'С 01.07.'+@YEAR+' ПО 30.09.'+@YEAR
											WHEN '4' THEN 'С 01.10.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END 
								END	+ '</Название>' + CHAR(10)
		+ 	SPACE(3) + '</КорректируемыйОтчетныйПериод>' + CHAR(10)								
			ELSE '' END
		+ 	SPACE(3) + '<СтраховойНомер>'+ RTRIM(LTRIM(COALESCE(PF_NUM,''))) +'</СтраховойНомер>' + CHAR(10)
		+ 	SPACE(3) + '<ФИО>' + CHAR(10)
		+ 		SPACE(4) + '<Фамилия>'+ RTRIM(LTRIM(COALESCE(FM,''))) +'</Фамилия>' + CHAR(10)
		+ 		SPACE(4) + '<Имя>'+ RTRIM(LTRIM(COALESCE(IM,''))) +'</Имя>' + CHAR(10)
		+ 		SPACE(4) + '<Отчество>'+ RTRIM(LTRIM(COALESCE(OT,''))) +'</Отчество>' + CHAR(10)
		+ 	SPACE(3) + '</ФИО>' + CHAR(10)
		
		+ CASE WHEN @TYPDOC <> 'СПВ-1' THEN 
		
		 			SPACE(3) + '<АдресЗЛ>' + CHAR(10)
				+ 		SPACE(4) + '<ТипАдреса>РОССИЙСКИЙ</ТипАдреса>' + CHAR(10)
				+ 		CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,2,',') <> '' THEN SPACE(4) + '<Индекс>'+ dbo.SA_GET_WORD_NUM(ADDRESS2,2,',') +'</Индекс>' + CHAR(10) ELSE '' END
				+ 		SPACE(4) + '<РоссийскийАдрес>' + CHAR(10)
				+ 			SPACE(5) + '<СостояниеАдреса>ПРАВИЛЬНЫЙ</СостояниеАдреса>' + CHAR(10)
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,3,',') <> '' 
								THEN 	SPACE(5) + '<Регион>' + CHAR(10)
									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' ')) ))+'</Сокращение>' + CHAR(10) 
									+ SPACE(5) + '</Регион>' + CHAR(10)	
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,4,',') <> '' 
								THEN SPACE(5) + '<Район>' + CHAR(10)
									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' ')) ))+'</Сокращение>' + CHAR(10) 
									+ SPACE(5) + '</Район>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,5,',') <> '' 
								THEN SPACE(5) + '<Город>' + CHAR(10)
									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' ')) ))+'</Сокращение>' + CHAR(10) 
									+ SPACE(5) + '</Город>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,6,',') <> '' 
								THEN SPACE(5) + '<НаселенныйПункт>' + CHAR(10)
									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' ')) ))+'</Сокращение>' + CHAR(10) 
									+ SPACE(5) + '</НаселенныйПункт>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,7,',') <> '' 
								THEN SPACE(5) + '<Улица>' + CHAR(10)
									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' ')) ))+'</Сокращение>' + CHAR(10) 
									+ SPACE(5) + '</Улица>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,8,',') <> '' 
								THEN SPACE(5) + '<Дом>' + CHAR(10)
									+ SPACE(6) + '<Сокращение>Д</Сокращение>' + CHAR(10) 
									+ SPACE(6) + '<Номер>'+ RTRIM(LTRIM(dbo.SA_GET_WORD_NUM(ADDRESS2,8,','))) +'</Номер>' + CHAR(10) 
									+ SPACE(5) + '</Дом>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,9,',') <> '' 
								THEN SPACE(5) + '<Корпус>' + CHAR(10)
									+ SPACE(6) + '<Сокращение>КОРП</Сокращение>' + CHAR(10) 
									+ SPACE(6) + '<Номер>'+ RTRIM(LTRIM(dbo.SA_GET_WORD_NUM(ADDRESS2,9,',')))  +'</Номер>' + CHAR(10) 
									+ SPACE(5) + '</Корпус>' + CHAR(10)
								ELSE '' END
				+			CASE WHEN dbo.SA_GET_WORD_NUM(ADDRESS2,10,',') <> '' 
								THEN SPACE(5) + '<Квартира>' + CHAR(10)
									+ SPACE(6) + '<Сокращение>КВ</Сокращение>' + CHAR(10) 
									+ SPACE(6) + '<Номер>'+ RTRIM(LTRIM(dbo.SA_GET_WORD_NUM(ADDRESS2,10,','))) +'</Номер>' + CHAR(10) 
									+ SPACE(5) + '</Квартира>' + CHAR(10)
								ELSE '' END
				+ 		SPACE(4) + '</РоссийскийАдрес>' + CHAR(10)
				+ 	SPACE(3) + '</АдресЗЛ>' + CHAR(10)
			ELSE ''
			END	
		+ 	SPACE(3) + '<СуммаВзносовНаСтраховую>' + CHAR(10) 
		+ 	 SPACE(4) + '<Начислено>' + RTRIM(LTRIM(STR(COALESCE([INSUR],0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	 SPACE(4) + '<Уплачено>' + RTRIM(LTRIM(STR(COALESCE([INSUR1],0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(3) + '</СуммаВзносовНаСтраховую>' + CHAR(10)
		+ 	SPACE(3) + '<СуммаВзносовНаНакопительную>' + CHAR(10) 
		+ 	  SPACE(4) + '<Начислено>' + RTRIM(LTRIM(STR(COALESCE(GAIN,0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	  SPACE(4) + '<Уплачено>' + RTRIM(LTRIM(STR(COALESCE(GAIN1,0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(3) + '</СуммаВзносовНаНакопительную>' + CHAR(10)
		+ 	SPACE(3) + '<ДатаЗаполнения>' + @DATE_DOC + '</ДатаЗаполнения>' + CHAR(10)
		+ 	CASE WHEN @TYPDOC = 'СПВ-1' THEN SPACE(3) + '<ДатаСоставленияНа>' + @DATE_DOC + '</ДатаСоставленияНа>' ELSE '' END,

		--В этом промежутки блоки со стажем
		---------------------------------------------------
		SPACE(1) + '</СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>'
		from #PERS_INFO where NGROUP = @NGROUP and ID_EX = 1
		ORDER BY [ID]

		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @PERS_ID, @PERS_INFO1, @PERS_INFO2
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, @PERS_INFO1

				IF EXISTS (select * from #PERS_INFO where NGROUP = @NGROUP and ID_EX >= 1) --AND @SZV = 1 AND @TYPDOC = 'СПВ-1'
				BEGIN
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					Select @lcFNAME,
			SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
		+		SPACE(4) + '<НомерСтроки>' + RTRIM(LTRIM(STR(ID_EX))) + '</НомерСтроки>' + CHAR(10)
		+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN,104) + '</ДатаНачалаПериода>' + CHAR(10)
		+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END,104) + '</ДатаКонцаПериода>' + CHAR(10)
		+				CASE WHEN RTRIM(LTRIM(COALESCE(ter_usl,''))) <> '' OR RTRIM(LTRIM(COALESCE(osob_usl,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN 
		+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(ter_usl,''))) <> '' OR RTRIM(LTRIM(COALESCE(osob_usl,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(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(ter_usl,''))) <> '' THEN
							SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
		+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(ter_usl,''))) + '</ОснованиеТУ>' + CHAR(10)
		+						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
		+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
							ELSE '' END
		+ 					CASE WHEN RTRIM(LTRIM(COALESCE(osob_usl,''))) <> '' THEN
							SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
		+						SPACE(8) + '<ОснованиеОУТ>' + RTRIM(LTRIM(COALESCE(osob_usl,''))) + '</ОснованиеОУТ>' + CHAR(10)
		+						SPACE(8) + '<ПозицияСписка>' + RTRIM(LTRIM(COALESCE(osob_spis,''))) + '</ПозицияСписка>' + CHAR(10)
		+ 					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(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
		+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
		+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
					ELSE '' END
		+	SPACE(3) + '</СтажевыйПериод>'
					from #PERS_INFO where NGROUP = @NGROUP AND [ID] = @PERS_ID
					ORDER BY [ID]

				END

				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, @PERS_INFO2
				
			END
		
			FETCH NEXT FROM @Cur2 INTO @PERS_ID, @PERS_INFO1, @PERS_INFO2
		END
		
		CLOSE @Cur2
		DEALLOCATE @Cur2

	END

	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	 SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'	
	UNION ALL SELECT @lcFNAME, '</ФайлПФР>'

	FETCH NEXT FROM @Cur1 INTO  @NGROUP, @lcFNAME, @INN, @KPP, @DEP_NAME, @PFNUMBER, @PACHNUM, @DOCCOUNT, @TYPDOC, @PERSCNT, @DATE_CRT, @DATE_DOC, @YEAR,
	@SZV, @TYP_SVED, @VID_KOR, @INSUR, @INSUR1, @GAIN, @GAIN1, @PER, @TYPE, @PER_EDT, @YEAR_EDT,@PER_EDT_NAME, @TYPE, @KATEG, @PER_NAME
END

CLOSE @Cur1
DEALLOCATE @Cur1

CREATE TABLE #ADV62A (
	[YEAR] INT,
	[PER] TINYINT,
	[PER10] TINYINT,
	[COUNT_P] INT,
	[COUNT_PK] INT,
	[PFNUMBER] VARCHAR(20), 
	[DEP_NAME] VARCHAR(256),
	[OKPO] VARCHAR(20),
	[INN] VARCHAR(20),
	[KPP] VARCHAR(20),
	DATE_CRT DATETIME,
	DATE_DOC DATETIME
)

INSERT INTO #ADV62A
exec dbo.SZV4_PRINT_ADV62 @Link, 1

CREATE TABLE #ADV62B1 (
	[ID] INT,
	[NGROUP] INT,
	[cGRP] VARCHAR(5),
	[CODE] VARCHAR(20),
	[INSUR] NUMERIC(20,2),
	[INSUR1] NUMERIC(20,2),
	[GAIN] NUMERIC(20,2),
	[GAIN1] NUMERIC(20,2),
	[PERS_CNT] INT,
	[FNAME] VARCHAR(256),
	[IT_ROUND] TINYINT 
)

INSERT INTO #ADV62B1 ([NGROUP],[cGRP],[CODE],[INSUR],[INSUR1],[GAIN],[GAIN1],[PERS_CNT],[FNAME],[IT_ROUND])
exec dbo.SZV4_PRINT_ADV62 @Link, 2

SELECT * INTO #ADV62B FROM #ADV62B1 ORDER BY [CODE], [NGROUP]
SELECT @NN = 0, @PN = 0, @ON = 0
UPDATE A
SET 
	@NN = @NN + 1,
	ID = @NN
FROM #ADV62B A

CREATE TABLE #ADV62C1 (
	[ID] INT,
	[NGROUP] INT,
	[cGRP] VARCHAR(5),
	[CODE] VARCHAR(20),
	[INSUR] NUMERIC(20,2),
	[INSUR1] NUMERIC(20,2),
	[GAIN] NUMERIC(20,2),
	[GAIN1] NUMERIC(20,2),
	[PERS_CNT] INT,
	[FNAME] VARCHAR(256),
	[IT_ROUND] TINYINT 
)

INSERT INTO #ADV62C1 ([NGROUP],[cGRP],[CODE],[INSUR],[INSUR1],[GAIN],[GAIN1],[PERS_CNT],[FNAME],[IT_ROUND])
exec dbo.SZV4_PRINT_ADV62 @Link, 3

SELECT * INTO #ADV62C FROM #ADV62C1 ORDER BY [CODE], [NGROUP]
SELECT @NN = 0, @PN = 0, @ON = 0
UPDATE A
SET 
	@NN = @NN + 1,
	ID = @NN
FROM #ADV62C A

DECLARE @IT_ROUND_TYPE tinyint, @IT_ROUND_LEN tinyint
Set @IT_ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT5')
Set @IT_ROUND_LEN = (case when @IT_ROUND_TYPE <= 1 then 2 else 0 end)
Set @IT_ROUND_TYPE = (case when @IT_ROUND_TYPE = 3 then 1 else 0 end)

IF COALESCE(dbo.sa_get_option_by_code('SA_SZV4_OPT3'),0) = 1
	Set @NGROUP = COALESCE((Select MIN(NGROUP) from #ADV63),2) - 1
ELSE
	Set @NGROUP = COALESCE(@NGROUP,0) + 1

DECLARE @COUNT_P VARCHAR(10), @COUNT_PK VARCHAR(10)

SELECT TOP 1  
	@lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END) + '-ORG-' + @PFNUMBER + '-DCK-' + REPLACE(STR(COALESCE(@NGROUP,1),5),' ','0') + '-DPT-000000-DCK-00000.XML' ,
	@INN = RTRIM(LTRIM(COALESCE(INN,''))),
	@KPP = RTRIM(LTRIM(COALESCE(KPP,''))),
	@DEP_NAME = RTRIM(LTRIM(COALESCE(DEP_NAME,''))),
	@PFNUMBER = RTRIM(LTRIM(COALESCE(PFNUMBER,''))),
	@COUNT_P = RTRIM(LTRIM(CONVERT(VARCHAR(10),COUNT_P))),
	@COUNT_PK = RTRIM(LTRIM(CONVERT(VARCHAR(10),COUNT_PK))),
	@DATE_DOC = CONVERT(VARCHAR(10),DATE_DOC,104),
	@PER = CONVERT(VARCHAR(1),CASE WHEN [PER] = 0 THEN [PER10] ELSE [PER] END),
	@YEAR = CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END)
from #ADV62A

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, 'OEM' --Имя файла
UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
    UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
    UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">'
  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<СоставительПачки>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НалоговыйНомер>'
       UNION ALL SELECT @lcFNAME, SPACE(5) + '<ИНН>' + @INN + '</ИНН>'
       UNION ALL SELECT @lcFNAME, SPACE(5) + '<КПП>' + @KPP + '</КПП>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '</НалоговыйНомер>'
	 UNION ALL SELECT @lcFNAME, SPACE(4) + '<КодЕГРЮЛ>' + @EGRUL + '</КодЕГРЮЛ>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаименованиеОрганизации>' + @DEP_NAME + '</НаименованиеОрганизации>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаименованиеКраткое>' + @DEP_NAME + '</НаименованиеКраткое>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<РегистрационныйНомер>' + @PFNUMBER + '</РегистрационныйНомер>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '</СоставительПачки>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерПачки>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<Основной>' + REPLACE(STR(COALESCE(@NGROUP,1),5),' ','0') + '</Основной>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '</НомерПачки>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<СоставДокументов>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<Количество>1</Количество>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '<НаличиеДокументов>'
       UNION ALL SELECT @lcFNAME, SPACE(5) + '<ТипДокумента>ОПИСЬ_СВЕДЕНИЙ_ПЕРЕДАВАЕМЫХ_СТРАХОВАТЕЛЕМ</ТипДокумента>'
       UNION ALL SELECT @lcFNAME, SPACE(5) + '<Количество>1</Количество>'
     UNION ALL SELECT @lcFNAME, SPACE(4) + '</НаличиеДокументов>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '</СоставДокументов>'
   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ДатаСоставления>' + @DATE_DOC + '</ДатаСоставления>'
 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>'
 
 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ОПИСЬ_СВЕДЕНИЙ_ПЕРЕДАВАЕМЫХ_СТРАХОВАТЕЛЕМ>'
 UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>2</НомерВпачке>'
--- Новый блок появился
UNION ALL SELECT @lcFNAME, SPACE(3) + '<Страхователь>' 
UNION ALL SELECT @lcFNAME, SPACE(4) +	'<НалоговыйНомер>'
UNION ALL SELECT @lcFNAME, SPACE(5) +		'<ИНН>' + @INN + '</ИНН>'
UNION ALL SELECT @lcFNAME, SPACE(5) +		'<КПП>' + @KPP + '</КПП>'
UNION ALL SELECT @lcFNAME, SPACE(4) +	'</НалоговыйНомер>' 
UNION ALL SELECT @lcFNAME, SPACE(4) +	'<КодЕГРЮЛ>' + @EGRUL + '</КодЕГРЮЛ>'
UNION ALL SELECT @lcFNAME, SPACE(4) +	'<НаименованиеОрганизации>' + @DEP_NAME + '</НаименованиеОрганизации>' 
UNION ALL SELECT @lcFNAME, SPACE(4) +	'<НаименованиеКраткое>' + @DEP_NAME + '</НаименованиеКраткое>' 
UNION ALL SELECT @lcFNAME, SPACE(4) +	'<РегистрационныйНомер>' + @PFNUMBER + '</РегистрационныйНомер>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '</Страхователь>'

UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОтчетныйПериод>'
	UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE WHEN @YEAR = '2010' THEN (CASE @PER WHEN '2' THEN '1' ELSE '2' END) ELSE @PER END + '</Квартал>'
	UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR + '</Год>'
	UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' +
								CASE WHEN @YEAR = '2010' THEN
										CASE @PER 
											WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '4' THEN 'С 01.07.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END
									ELSE
										CASE @PER 
											WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
											WHEN '2' THEN 'С 01.04.'+@YEAR+' ПО 30.06.'+@YEAR
											WHEN '3' THEN 'С 01.07.'+@YEAR+' ПО 30.09.'+@YEAR
											WHEN '4' THEN 'С 01.10.'+@YEAR+' ПО 31.12.'+@YEAR
											ELSE ''
										END									
								END	
							+ '</Название>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '</ОтчетныйПериод>' 

UNION ALL SELECT @lcFNAME, SPACE(3) + '<ЧислоИсходныхПачек>' + @COUNT_P + '</ЧислоИсходныхПачек>'

UNION ALL SELECT @lcFNAME, SPACE(3) + '<ЧислоКорректирующихПачек>' + @COUNT_PK + '</ЧислоКорректирующихПачек>'

UNION ALL SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + @DATE_DOC + '</ДатаЗаполнения>'

DECLARE @NEXT_NUM INT, @ITER INT
SELECT @ITER = 0 SET @NEXT_NUM = 0

DECLARE @CurI CURSOR, @KATEG_CODE VARCHAR(20)
SET @CurI = CURSOR FORWARD_ONLY

FOR select DISTINCT CODE from #ADV62B order by CODE

OPEN @CurI
FETCH NEXT FROM @CurI INTO @KATEG_CODE
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
	
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
		SPACE(3) + '<СведенияОбИсходныхСведениях>' + CHAR(10)
		+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(ISNULL([ID]+@ITER,0),2))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО ПАЧКЕ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<СуммаВзносовНаСтраховую>' + CHAR(10) 
		+ 	 SPACE(5) + '<Начислено>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	 SPACE(5) + '<Уплачено>' + + RTRIM(LTRIM(STR(COALESCE(INSUR1,0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(4) + '</СуммаВзносовНаСтраховую>' + CHAR(10)

		+ 	SPACE(4) + '<СуммаВзносовНаНакопительную>' + CHAR(10) 
		+ 	  SPACE(5) + '<Начислено>' + + RTRIM(LTRIM(STR(COALESCE(GAIN,0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	  SPACE(5) + '<Уплачено>' + RTRIM(LTRIM(STR(COALESCE(GAIN1,0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(4) + '</СуммаВзносовНаНакопительную>' + CHAR(10)

		+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL([PERS_CNT],0),5))) + '</КоличествоЗЛ>' + CHAR(10)
		+	SPACE(4) + '<ИмяФайла>' + RTRIM(LTRIM([FNAME])) + '</ИмяФайла>' + CHAR(10)
		+SPACE(3) + '</СведенияОбИсходныхСведениях>'
		FROM #ADV62B WHERE NGROUP IS NOT NULL AND RTRIM(LTRIM(CODE)) = @KATEG_CODE ORDER BY ID

		SET @NEXT_NUM = @NEXT_NUM + @@ROWCOUNT + 1

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
		SPACE(3) + '<СведенияОбИсходныхСведениях>' + CHAR(10)
		+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(@NEXT_NUM))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО КАТЕГОРИИ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<СуммаВзносовНаСтраховую>' + CHAR(10) 
		+ 	 SPACE(5) + '<Начислено>' + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR),0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	 SPACE(5) + '<Уплачено>' + + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR1),0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(4) + '</СуммаВзносовНаСтраховую>' + CHAR(10)

		+ 	SPACE(4) + '<СуммаВзносовНаНакопительную>' + CHAR(10) 
		+ 	  SPACE(5) + '<Начислено>' + + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN),0),15,2))) + '</Начислено>' + CHAR(10)  
		+ 	  SPACE(5) + '<Уплачено>' + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN1),0),15,2))) + '</Уплачено>' + CHAR(10)  
		+ 	SPACE(4) + '</СуммаВзносовНаНакопительную>' + CHAR(10)

		+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL(SUM([PERS_CNT]),0),5))) + '</КоличествоЗЛ>' + CHAR(10)
		+SPACE(3) + '</СведенияОбИсходныхСведениях>'
		FROM #ADV62B T1 WHERE NGROUP IS NOT NULL  AND RTRIM(LTRIM(CODE)) = @KATEG_CODE GROUP BY [CODE]
		
		SET @ITER = @ITER + 1

	END

	FETCH NEXT FROM @CurI INTO @KATEG_CODE
END

CLOSE @CurI
DEALLOCATE @CurI

IF EXISTS (SELECT * FROM #ADV62B T1 WHERE NGROUP IS NOT NULL)
BEGIN

	SET @NEXT_NUM = @NEXT_NUM + 1
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, 
	SPACE(3) + '<СведенияОбИсходныхСведениях>' + CHAR(10)
	+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(@NEXT_NUM))) + '</ПорядковыйНомер>' + CHAR(10)
	+	SPACE(4) + '<ТипСтрокиОсведениях>ПО СТРАХОВАТЕЛЮ</ТипСтрокиОсведениях>' + CHAR(10)

	+ 	SPACE(4) + '<СуммаВзносовНаСтраховую>' + CHAR(10) 
	+ 	 SPACE(5) + '<Начислено>' + RTRIM(LTRIM(STR(COALESCE(ROUND(CONVERT(NUMERIC(15,2),SUM(INSUR)),@IT_ROUND_LEN,@IT_ROUND_TYPE),0),15,2))) + '</Начислено>' + CHAR(10)  
	+ 	 SPACE(5) + '<Уплачено>' + + RTRIM(LTRIM(STR(COALESCE(ROUND(CONVERT(NUMERIC(15,2),SUM(INSUR1)),@IT_ROUND_LEN,@IT_ROUND_TYPE),0),15,2))) + '</Уплачено>' + CHAR(10)  
	+ 	SPACE(4) + '</СуммаВзносовНаСтраховую>' + CHAR(10)

	+ 	SPACE(4) + '<СуммаВзносовНаНакопительную>' + CHAR(10) 
	+ 	  SPACE(5) + '<Начислено>' + + RTRIM(LTRIM(STR(COALESCE(ROUND(CONVERT(NUMERIC(15,2),SUM(GAIN)),@IT_ROUND_LEN,@IT_ROUND_TYPE),0),15,2))) + '</Начислено>' + CHAR(10)  
	+ 	  SPACE(5) + '<Уплачено>' + RTRIM(LTRIM(STR(COALESCE(ROUND(CONVERT(NUMERIC(15,2),SUM(GAIN1)),@IT_ROUND_LEN,@IT_ROUND_TYPE),0),15,2))) + '</Уплачено>' + CHAR(10)  
	+ 	SPACE(4) + '</СуммаВзносовНаНакопительную>' + CHAR(10)

	+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL(SUM([PERS_CNT]),0),5))) + '</КоличествоЗЛ>' + CHAR(10)
	+SPACE(3) + '</СведенияОбИсходныхСведениях>'
	FROM #ADV62B T1 WHERE NGROUP IS NOT NULL

END	

SELECT @ITER = 0 SET @NEXT_NUM = 0

SET @CurI = CURSOR FORWARD_ONLY

FOR select DISTINCT CODE from #ADV62C order by CODE

OPEN @CurI
FETCH NEXT FROM @CurI INTO @KATEG_CODE
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
		SPACE(3) + '<СведенияОкорректирующихСведениях>' + CHAR(10)
		+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(ISNULL([ID]+@ITER,0),2))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО ПАЧКЕ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<ДоначисленоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(GAIN,0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)

		+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(INSUR1,0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(GAIN1,0),15,2))) + '</ДоуплаченоНаНакопительную>' + CHAR(10)

		+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL([PERS_CNT],0),5))) + '</КоличествоЗЛ>' + CHAR(10)
		+	SPACE(4) + '<ИмяФайла>' + RTRIM(LTRIM([FNAME])) + '</ИмяФайла>' + CHAR(10)
		+SPACE(3) + '</СведенияОкорректирующихСведениях>'
		FROM #ADV62C WHERE NGROUP IS NOT NULL AND RTRIM(LTRIM(CODE)) = @KATEG_CODE ORDER BY ID

		SET @NEXT_NUM = @NEXT_NUM + @@ROWCOUNT + 1

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
		SPACE(3) + '<СведенияОкорректирующихСведениях>' + CHAR(10)
		+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(@NEXT_NUM))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО КАТЕГОРИИ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<ДоначисленоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR),0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN),0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)


		+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR1),0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN1),0),15,2))) + '</ДоуплаченоНаНакопительную>' + CHAR(10)

		+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL(SUM([PERS_CNT]),0),5))) + '</КоличествоЗЛ>' + CHAR(10)
		+SPACE(3) + '</СведенияОкорректирующихСведениях>'
		FROM #ADV62C T1 WHERE NGROUP IS NOT NULL  AND RTRIM(LTRIM(CODE)) = @KATEG_CODE GROUP BY [CODE]

		SET @ITER = @ITER + 1		

	END

	FETCH NEXT FROM @CurI INTO @KATEG_CODE
END

CLOSE @CurI
DEALLOCATE @CurI			

IF EXISTS (SELECT * FROM #ADV62C T1 WHERE NGROUP IS NOT NULL)
BEGIN

	SET @NEXT_NUM = @NEXT_NUM + 1
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, 
	SPACE(3) + '<СведенияОкорректирующихСведениях>' + CHAR(10)
	+	SPACE(4) + '<ПорядковыйНомер>' + RTRIM(LTRIM(STR(@NEXT_NUM))) + '</ПорядковыйНомер>' + CHAR(10)
	+	SPACE(4) + '<ТипСтрокиОсведениях>ПО СТРАХОВАТЕЛЮ</ТипСтрокиОсведениях>' + CHAR(10)

	+ 	SPACE(4) + '<ДоначисленоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR),0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
	+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN),0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)

	+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM(INSUR1),0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
	+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM(GAIN1),0),15,2))) + '</ДоуплаченоНаНакопительную>' + CHAR(10)

	+	SPACE(4) + '<КоличествоЗЛ>' + RTRIM(LTRIM(STR(ISNULL(SUM([PERS_CNT]),0),5))) + '</КоличествоЗЛ>' + CHAR(10)
	+SPACE(3) + '</СведенияОкорректирующихСведениях>'
	FROM #ADV62C T1 WHERE NGROUP IS NOT NULL

END	

---------------------------------------------------------------
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
	 SELECT @lcFNAME, SPACE(2) + '</ОПИСЬ_СВЕДЕНИЙ_ПЕРЕДАВАЕМЫХ_СТРАХОВАТЕЛЕМ>'
UNION 	ALL 	SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
UNION	ALL 	SELECT @lcFNAME, SPACE(1) + '</ФайлПФР>'

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]
--select OUT_TEXT from #OUTPUT order by [ID]




GO


GRANT EXECUTE ON dbo.[SZV4_EXPORT_PFR_700_10] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_PFR_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_PFR_PREPARE]

GO


CREATE PROCEDURE dbo.RSA_RSV_1_PFR_PREPARE 
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT

select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF
set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, FACE_GROUP TINYINT, I TINYINT, E TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E)
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,@nYEAR))),
	F.ENVD	 
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) S
	inner join PERSON P on S.REF_PHYS_PERS = P.link
	inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
WHERE WAY_CALC not in (2,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],@nYEAR))),F.ENVD
FROM 
	DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join PERSON P on GT.PERS_LINK = P.link
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  not in (2,5)
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK


DELETE FROM #SPR_ESN
WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)

CREATE TABLE #RES2(CODE_STR VARCHAR(10), C1 NUMERIC(18,2), C2 NUMERIC(18,2),  C3 NUMERIC(18,2), C4 NUMERIC(18,2), C5 NUMERIC(18,2), C6 NUMERIC(18,2))
/*
для заполнения показателя "количество застрахованных лиц", указывается количество застрахованных лиц,
за которых должны быть представлены сведения индивидуального (персонифицированного) учета за отчетный период.
*/

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @C1_PERIOD_BEG DATETIME, @C1_PERIOD_END DATETIME
IF @nYEAR = 2010
	SELECT @C1_PERIOD_BEG = CASE WHEN @nMONTH3 <= 6 THEN '20100101' ELSE '20100701' END,
		   @C1_PERIOD_END = CASE WHEN @nMONTH3 <= 6 THEN '20100630' ELSE '20101231' END
ELSE
	SELECT @C1_PERIOD_BEG = @START_DATE,
		   @C1_PERIOD_END = @END_DATE
		   
--------------
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int
SELECT @NAvgCount = COUNT(pers_link) 
FROM
(
	SELECT DISTINCT E.pers_link
	FROM 
		dbo.EMPL E inner join dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
		left join dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
	WHERE 
		P.DATE_BEGIN <= @C1_PERIOD_END
		and
		coalesce(U.DIS_DATE,'20990101') >= @C1_PERIOD_BEG
		And 
		E.DEP_LINK = @DEP_LINK
	UNION 
	Select DISTINCT
		DFG.link
	FROM PERSON DFG inner join SALARY_REESTR_DGH DGH on DFG.link = DGH.PERS_LINK
	WHERE 
		DGH.DATE1 = (
			Select max(DATE1)  from SALARY_REESTR_DGH as DGH0 
					where DGH.PERS_LINK = DGH0.PERS_LINK AND DGH0.DEP_LINK = DGH.DEP_LINK
						AND
						(
							ISNULL(DATE1, '19000101') between  @C1_PERIOD_BEG and @C1_PERIOD_END
							or ISNULL(DATE2, '20990101') between @C1_PERIOD_BEG and @C1_PERIOD_END
						)
					)
		And 
		DGH.DEP_LINK = @DEP_LINK
) AS T		

--
INSERT INTO #RES2(CODE_STR, C1)
SELECT '1', ISNULL(@NAvgCount,0)

/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
--
UPDATE #RES2 SET C2 = ISNULL(@NAvgCount,0) WHERE CODE_STR = '1'

--Раздел 2. Расчет страховых взносов по тарифу, установленному для плательщика страховых взносов
Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 6)

--Фактическая база для договорников
SELECT 
	GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 6
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK 
GROUP BY 
	GT.PERS_LINK, MONTH(G.[DATE]), F.ENVD

SELECT  PERS_LINK, MONTH_BASE, SUMMA_BASE = SUM(SUMMA_BASE)
INTO #DGH_FAKT_BASE1
FROM #DGH_FAKT_BASE
GROUP BY PERS_LINK, MONTH_BASE

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

------
CREATE TABLE #CALCULATE_JURNAL (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2))
INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA)
SELECT LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL CJ
WHERE
	Year(period_begin) = @nYEAR 
	and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
GROUP BY
	LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL

------	у кого была инвалидность в заданном периоде
SELECT DISTINCT PERS_LINK 
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate

--Заготовка для #SALARY_SUM2
CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), FACE_GROUP TINYINT, SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT)
--Сотрудники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, FACE_GROUP, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV)
select
	E.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END
from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	INNER JOIN DBO.PERSON P1 ON P1.LINK = E.PERS_LINK
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	E.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, ( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )
--Договрники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, FACE_GROUP, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV)
select
	CJ.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B1.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END	
from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	--База по договорникам в разрезе ЕНВД
	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1
	--Общая база по договорникам
	LEFT JOIN #DGH_FAKT_BASE1 B1 ON B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = CJ.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	CJ.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, ( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )	
	
--корректировка в соотвествие с тем, в каком есяце кто был инвалидом
UPDATE D SET 
	SUMMA_ALL_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL ELSE 0 END), 
	SUMMA_NO_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO ELSE 0 END), 
	SUMMA_ALL_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL_E ELSE 0 END), 
	SUMMA_NO_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO_E ELSE 0 END)
FROM #SALARY_SUM_DATA D
WHERE INV = 1 --которые имели инвалидность в каком-то месяце периода	

--Данные о начисленной зарплате
SELECT MON = Month(PERIOD_BEGIN), 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)
INTO #SALARY_SUM2
FROM #SALARY_SUM_DATA
GROUP BY
	Month(PERIOD_BEGIN), FACE_GROUP

--
DROP TABLE #SALARY_SUM_DATA	

--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '201', 
			 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 1

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '202', 

			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,
			 
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 2

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '211',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 9),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 10),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 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 FACE_GROUP = 1 AND MON = 11),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 0 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 12),0))			
	END,	
	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '212',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 9),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 10),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 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 FACE_GROUP = 2 AND MON = 11),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 0 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 12),0))			
	END,
		
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))
----
--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 1 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 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, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '217',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 9) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 10) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 11) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '218',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 9) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 10) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 11) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 12) ,0))										
	END,	
		
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))

--Начислено страховых взносов на обяза-тельное пенсионное страхование
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '241',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '242',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	
	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '243',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '244',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0) ,0))
	ELSE	
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = @nMONTH3) ,0))	

---В отношении выплат в пользу работников, являющихся инвалидами I, II или III группы
--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '301', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2	
WHERE FACE_GROUP = 1	 

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '302', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 2

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '311',
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 10),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 11),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 12),0))			
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '312',
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))					
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 10),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 11),0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 12),0))			
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))


SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 2 AND  WAY_CALC = 7 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 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, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1I T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1I T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '317',
	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 9) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 10) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 11) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 12) ,0))										
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '318',
	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 9) ,0))			
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 10) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 11) ,0))
			+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 12) ,0))										
	END,
		
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))


--Начислено страховых взносов на обяза-тельное пенсионное страхование
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '341',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH3) ,0))
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '342',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH3) ,0))		
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH3) ,0))	
	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '343',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH3) ,0))	

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '344',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 2 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH3) ,0))	

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '351', CASE WHEN @nMONTH3 > 3 THEN Convert(numeric(18),SUM(SUMMA_ALL_E))
			ELSE
				 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_E ELSE 0 END))
 				 + Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_E ELSE 0 END))
 				 + Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_E ELSE 0 END))			
			END,
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2	
WHERE FACE_GROUP = 1	 

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '352', CASE WHEN @nMONTH3 > 3 THEN Convert(numeric(18),SUM(SUMMA_ALL_E))
			ELSE
				 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_E ELSE 0 END))
 				 + Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_E ELSE 0 END))
 				 + Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_E ELSE 0 END)) 			
			END,
			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_E ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 2

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '361',
	CASE WHEN @nMONTH3 > 3 THEN 
		CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1),0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '362',
	CASE WHEN @nMONTH3 > 3 THEN 
		CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2),0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(DED_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND E = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1E FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE I = 1 AND E = 1 AND  WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 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, @END_DATE) 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

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '364',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '365',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2E WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))


--Начислено страховых взносов на обяза-тельное пенсионное страхование
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '391',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH3) ,0))
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 6 AND MONTH_BASE = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '392',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH3) ,0))		
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 7 AND MONTH_BASE = @nMONTH3) ,0))	
	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '393',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 3 AND MONTH_BASE = @nMONTH3) ,0))	

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '394',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4) ,0))
	ELSE
		CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH3) ,0))	
	END,
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE I = 1 AND E = 1 AND WAY_CALC = 4 AND MONTH_BASE = @nMONTH3) ,0))	

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferClear
EXEC dbo.BufferPush -116, @Table_Razd1

DROP TABLE #RES2



GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PFR_PREPARE] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_CHECK_CODE_ROW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_CHECK_CODE_ROW]
GO

--проверка наличия строк в формах 
CREATE                     PROCEDURE dbo.RN_CHECK_CODE_ROW  
  @code_form1 varchar(500),
  @code_form2 varchar(500),
  @table int, --номер таблицы
  @col1 int, --номер колонки 1 таблицы
  @col2 int --номер колонки 1 таблицы
 AS

declare @lsf1 int,@lsf2 int,@i int,@link_table1 int,@link_table2 int,@link_form1 int,@link_form2 int,@nomErr int,@link_col1 int,@link_col2 INT
DECLARE @dBeginDate DATETIME, @iDiffDate INT 
select @code_form1=codeForm,@lsf1=lsf,@link_form1=linkForm from  #ListForms where codeForm like @code_form1
select @code_form2=codeForm,@lsf2=lsf,@link_form2=linkForm from  #ListForms where codeForm like @code_form2


IF @lsf2 is null or @lsf1 is null
 RETURN 
 
SELECT @dBeginDate = max(rsf.[Begin_Date])
FROM  dbo.[REPORT_SAVED_FORMS] rsf 
WHERE link_saved_form  =@lsf2 

SET @iDiffDate = DATEDIFF(DAY, '20111231', @dBeginDate)

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'
EXEC dbo.[BufferPush] @iDiffDate, 'RO_RAZMNOJ_KS_OUTSIDE'
 

--итоговые строки
create table #TMP_ITOG1 (link_table int,code varchar(50))
create table #TMP_ITOG2 (link_table int,code varchar(50))

insert #TMP_ITOG1 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form1,1)  

if left(@code_form1,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form1,1)  
end

if left(@code_form1,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form1,1)  
end

insert #TMP_ITOG2 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form2,1)  

if left(@code_form2,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form2,1)  
end

if left(@code_form2,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form2,1)  
end

create table #err (code varchar(250),code_form1 varchar(50),code_form2 varchar(50))
declare @cstr varchar(8000)
set @i=@table 
--while @i<=3
--	begin
		select @link_table1=link_table from #report_tables where link_form=@link_form1 and orders=@i
		select @link_table2=link_table from #report_tables where link_form=@link_form2 and orders=@i
		select @link_col1=link_col from #report_coloumns where link_table=@link_table1 and orders=@col1
		select @link_col2=link_col from #report_coloumns where link_table=@link_table2 and orders=@col2

IF @code_form1 in ('0503117M','0503127M', '0503127G', '0503117G') and @table=2
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 and substring(code_row,15,3) IN ('200','000','210','220','230','240','250','260','300','500','600')
	end

IF @code_form1 in ('0503317M') and @table=3 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and substring(code_row,1,3) IN ('751', '752', '753', '754', '755', '756')
	end

IF @code_form1 in ('0503317M') and @table=1 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00087000000000000151', '00087000000000001151', '00087000000000002151', '00087000000000000120')
	end

IF @code_form1 in ('0503317M') and @table=2 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00097000000000000251', '00097000000000000231')
	end

		
		--проверка
--		insert #err (code,code_form1,code_form2)		
--		select distinct code_row,@code_form1,@code_form2 from #report_dinamics A where link_sf=@lsf1 and link_col=@link_col1 and float_val<>0
--		and not exists(select * from #report_dinamics B where link_sf=@lsf2 and link_col in (select link_col from #report_coloumns where link_table=@link_table2)  and A.code_row=B.code_row)


   IF @link_col2 IS NOT NULL 
		insert #err (code,code_form1,code_form2)		
		select distinct code_row,@code_form2,@code_form1 from #report_dinamics A where link_sf=@lsf2 and link_col=@link_col2 and float_val<>0
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 and link_col in (select link_col from #report_coloumns where link_table=@link_table1) and float_val<>0   and A.code_row=B.code_row)
		and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)
   ELSE
		insert #err (code,code_form1,code_form2)		
		select distinct code_row,@code_form2,@code_form1 from #report_dinamics A where link_sf=@lsf2 and float_val<>0 and link_col in (select link_col from #report_coloumns where link_table=@link_table2) 
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 and link_col in (select link_col from #report_coloumns where link_table=@link_table1) and float_val<>0   and A.code_row=B.code_row)
		and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)
   
		--select @nomErr=MAX(ORDERS) FROM #res 
		--insert #Res(orders, res, cdoc, ctable)	
		--select @nomErr,'-',@code_form1+' '+@code_form2,''

		IF exists(select * from #err)
			begin
				select @nomErr=MAX(ORDERS) FROM #res 
				insert #Res(orders, res, cdoc, ctable)	
				select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
				from #err
   		   WHERE NOT EXISTS(SELECT * FROM #Res WHERE res = '-' AND cdoc = 'Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2) AND ctable = '№'+ltrim(str(@i)))

				delete #err
			end

		delete #err

   IF @link_col1 IS NOT NULL 
		insert #err (code,code_form1,code_form2)		
		select distinct code_row,@code_form1,@code_form2 from #report_dinamics A where link_sf=@lsf1 and link_col=@link_col1 and float_val<>0
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 and link_col in (select link_col from #report_coloumns where link_table=@link_table2) and float_val<>0   and A.code_row=B.code_row)
		and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)
   ELSE
		insert #err (code,code_form1,code_form2)		
		select distinct code_row,@code_form1,@code_form2 from #report_dinamics A where link_sf=@lsf1 and float_val<>0 AND link_col in (select link_col from #report_coloumns where link_table=@link_table1)
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 and link_col in (select link_col from #report_coloumns where link_table=@link_table2) and float_val<>0   and A.code_row=B.code_row)
		and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)

   
		IF exists(select * from #err)
			begin
				select @nomErr=MAX(ORDERS) FROM #res 
				insert #Res(orders, res, cdoc, ctable)	
				select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
				from #err
   		   WHERE NOT EXISTS(SELECT * FROM #Res WHERE res = '-' AND cdoc = 'Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2) AND ctable = '№'+ltrim(str(@i)))

				delete #err
			end

select 0 
GO
GRANT ALL ON dbo.[RN_CHECK_CODE_ROW] 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].[RO_SPR_EXPORT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_SPR_EXPORT]
GO




/*
c Кейсистемс (Keysystems), 2005

	справка к балансу
*/
CREATE            proc 	dbo.RO_SPR_EXPORT
	 @varKSiLink int, -- линк сохранного справочника в REPORT_SPR
	@varKSiDelSpr tinyint  = 1 -- 1 - для нового справочника: удалять ли старый справочник или нет
as

	create table #Result_SPR ([TEXT] varchar(8000), orders int IDENTITY (1,1))
	declare @codeSpr varchar(50), @LinkTree int, @nameSpr varchar(254), @IsSystem tinyint
	select @codeSpr = rtrim(code), @nameSpr = rtrim(Name), @IsSystem = IsSystem from report_spr where link = @varKSiLink

	insert #Result_SPR ([TEXT])
	values ('------------------- ВЫГРУЗКА СПРАВОЧНИКА: ' +  @nameSpr + ' С КОДОМ ' + @codeSpr + '------------------------')

	insert #Result_SPR ([TEXT])
	values ('
------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------')

	--------------------------------------------------------------------------------
	-- данные о справочнике
	insert #Result_SPR ([TEXT])
	values ('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 #Result_SPR ([TEXT])
	select 'insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values (''' + rtrim(Code) + ''', ' + ltrim(str(orders)) + ', ''' + REPLACE(rtrim(Source),'''', '''''') + ''', ''' + rtrim(Name) + ''', ''' + rtrim(Const) + ''', ' + LTRIM(STR(First)) + ',' + LTRIM(STR(Cnt)) + ')
'
	from report_spr_col
	where link_spr = @varKSiLink

	insert #Result_SPR ([TEXT])
	select 'insert #Data_tmp (Table_From, Filter)
values (''' + rtrim(REPLACE(Table_From,'''', '''''')) + ''', ''' + rtrim(REPLACE(Filter,'''', '''''')) + ''')
'
	from report_spr_data
	where link_spr = @varKSiLink

	insert #Result_SPR ([TEXT])
	values ('declare @link int
select @link = link from report_spr where code = ''' + @codeSpr + '''
exec dbo.RO_SPR_SAVE @link, ''' + @codeSpr + ''', ''' + @nameSpr + ''', ''#Cols_tmp'', ''#Data_tmp'', ' +  LTRIM(STR(@IsSystem))  + '
')
	insert #Result_SPR ([TEXT])
	select  CHAR(13) + CHAR(10)
			+ 'GO'
			+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)

	-------------------------------------------------------------------------------
	-- создание вьюхи
	insert #Result_SPR ([TEXT])
	values ('
------------------- ВЬЮХА ------------------------')

	insert #Result_SPR ([TEXT])
	values( '
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''dbo.[' + @codeSpr + ']'') AND OBJECTPROPERTY(id, N''IsView'') = 1)
DROP VIEW dbo.[' + @codeSpr + ']
')

	insert #Result_SPR ([TEXT])
	select  CHAR(13) + CHAR(10)
			+ 'GO'
			+ CHAR(13) + CHAR(10)

	insert #Result_SPR ([TEXT])
	exec ssp_helptext @codeSpr

	insert #Result_SPR ([TEXT])
	select  CHAR(13) + CHAR(10)
			+ 'GO'
			+ CHAR(13) + CHAR(10) 
	insert #Result_SPR ([TEXT])
values('
GRANT SELECT ON dbo.[' + @codeSpr + '] TO PUBLIC
')

	insert #Result_SPR ([TEXT])
	select  CHAR(13) + CHAR(10)
			+ 'GO'
			+ CHAR(13) + CHAR(10) 

-----------------------------------------------------------------------------
	---- s_objects
-----------------------------------------------------------------------------
	insert #Result_SPR ([TEXT])
	values ('
------------------- S_OBJECTS ------------------------')

	----УДАЛИТЬ
	INSERT INTO #Result_SPR ([TEXT])
	SELECT  
	'IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = ''' + @codeSpr + ''')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = ''' + @codeSpr + '''' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)+ CHAR(13) + CHAR(10)
	 
	----СОЗДАТЬ
	INSERT INTO #Result_SPR ([TEXT])
	EXEC DBO.XU_SCRIPT_SOBJ @codeSpr

	----ДАТЬ ДОСТУП
	INSERT INTO #Result_SPR ([TEXT])
	EXEC DBO.SCRIPTSOBJPERM @codeSpr

-----------------------------------------------------------------------------------------
	-- данные справочника
	insert #Result_SPR ([TEXT])
	values ('
------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------')
	if not exists(select top 1 * from report_spr_data where link_spr = @varKSiLink) -- новый справочник с данными, которые нужно выгрузить
	begin
		select @LinkTree = Link from report_kbk where code = @codeSpr and code_form = 'HEADER'
		insert #Result_SPR ([TEXT]) exec RN_EXPORT_REPORT_KBK @LinkTree, @varKSiDelSpr
	end

-----------------------------------------------------------------------------------------
	select [TEXT]
	from #Result_SPR
	order by orders


	drop table #Result_SPR

GO
GRANT ALL ON dbo.[RO_SPR_EXPORT] TO PUBLIC
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
SET ANSI_WARNINGS OFF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_ANALITICS_OBTAIN_KEY_COL_VAL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_ANALITICS_OBTAIN_KEY_COL_VAL]
GO

CREATE PROCEDURE [dbo].[RT_ANALITICS_OBTAIN_KEY_COL_VAL]
	@nPeriod_Type int,
	@nPeriod_Date_Start datetime,
	@nPeriod_Number_Start int,
	@nPeriod_Date_Stop datetime,
	@nPeriod_Number_Stop int,
	@nStatus int,
	@nFormVersion int = null
AS

-- нормализация даты
declare @cDate varchar(8)
set @cDate = cast(year(@nPeriod_Date_Start) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Start) end as varchar),2) + '01'
set @nPeriod_Date_Start =  dateadd(dd,-1,dateadd(mm,1,@cDate))
set @cDate = cast(year(@nPeriod_Date_Stop) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Stop) end as varchar),2) + '01'
set @nPeriod_Date_Stop =  dateadd(dd,-1,dateadd(mm,1,@cDate))

--
--declare @cDate varchar(8)
--set @cDate = cast(year(@nPeriod_Date_Start) as varchar(4)) + right('00'+cast(month(@nPeriod_Date_Start) as varchar),2) + '01'
--set @nPeriod_Date_Start =  dateadd(dd,-1,dateadd(mm,1,@cDate))
--set @cDate = cast(year(@nPeriod_Date_Stop) as varchar(4)) + right('00'+cast(month(@nPeriod_Date_Stop) as varchar),2) + '01'
--set @nPeriod_Date_Stop =  dateadd(dd,-1,dateadd(mm,1,@cDate))

print @nPeriod_Date_Start
print @nPeriod_Date_Stop
---------------------------------------------------------------
-- создаём таблицу с периодами
exec DropTempTable '#analitics_period'
create table #analitics_period (nn int, period_type int, period_number int, period_date datetime)
create table #analitics_period_copy (period_type int, period_number int, period_date datetime)

declare @cSqlStr varchar(8000)

set @cSqlStr = ''
if exists(select * from #analitics_periods)
	set @cSqlStr = 'insert into #analitics_period (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_periods'
else 
	set @cSqlStr = 'exec dbo.RT_ANALITICS_GET_PERIODS '+convert(varchar,@nPeriod_Date_Start,112)+', '+convert(varchar,@nPeriod_Date_Stop,112)+', '+cast(@nPeriod_Type as varchar)+', ''#analitics_period'''

execute(@cSqlStr)

--  select * from #analitics_period
--  необходимо получить таблицу, примерно следующего вида:
--  period_type, period_date, period_number, link_form, link_table, link_col
--  линки формы будут получены по коду формы, по имени или ордеру таблицы, по имени или ордеру колонки

create table #analitics_period_links (period_type int, period_date datetime, period_number int, link_form int, link_table int, link_col int, link_col_base int, col_type tinyint, keyflag tinyint, tab_type int, dictionary varchar(254), field varchar(254))

declare	@this_link_form int,
		@this_link_table int,
		@nthis_table_order int,
		@cthis_table_name varchar(254),
		@this_link_col int,
		@nthis_col_order int,
		@cthis_col_name varchar(254),
		@this_link_col_type tinyint,
		@new_link_form int,
		@new_link_table int,
		@new_link_col int,
		@new_link_col_type tinyint,
		@cCodeForm varchar(50),
		@lpt int,
		@lpn int,
		@lpd datetime

while exists(select * from #analitics_links) begin -- цикл по отмеченным формам (потому что может быть отмечена более чем одна форма)
	select top 1 @this_link_form = link_f, @this_link_table = link_t, @this_link_col = link_c, @this_link_col_type = col_type from #analitics_links
	-- заполняем таблицу #analitics_period_links. каждому периоду будет соответствовать акуальная в том периоде форма
	select @nthis_table_order = orders, @cthis_table_name = [name] from dbo.report_tables where link_table = @this_link_table
	select @nthis_col_order = orders, @cthis_col_name = [name] from dbo.report_coloumns where link_col = @this_link_col

	-- код формы
	select @cCodeForm = rf0.code from dbo.report_forms as rf0 (nolock) where rf0.link_form = @this_link_form -- линк формы ищется по коду формы вне зависимости от даты

	-- цикл по периодам 
	insert into #analitics_period_copy (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_period

	while exists(select * from #analitics_period_copy) begin
		select top 1 @lpt = period_type, @lpn = period_number, @lpd = period_date from #analitics_period_copy
		-- линк формы в новом периоде
		set @new_link_form = null
		select top 1 @new_link_form = rsf.link_form
		--select rsf.period_type, rsf.begin_date, rsf.period_number, rsf.link_form
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = (select top 1 rf.link_form from dbo.report_forms as rf (nolock) where rf.code = (@cCodeForm) and rsf.begin_date between rf.start_date and isnull(rf.end_date,'20501231')) -- линк формы ищется по коду формы
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd

		-- линк таблицы в новом периоде
		set @new_link_table = null
		select top 1 @new_link_table = rt0.link_table
		from
			dbo.report_tables as rt0 (nolock)
		where
			rt0.link_form = @new_link_form
			and rt0.[name] = @cthis_table_name
		-- если не нашли таблицу по имени, ищем её по ордеру
		if @new_link_table is null begin
			select top 1 @new_link_table = rt0.link_table
			from
				dbo.report_tables as rt0 (nolock)
			where
				rt0.link_form = @new_link_form
				and rt0.orders = @nthis_table_order
		end

		-- линк колонки в новом периоде
		-- существует вероятность, что наименования колонок будут дублироваться в пределах одной формы. Поэтому если дублирование имеет место, переходим к поиску колонки по ордеру
		if (select count(*) from dbo.report_coloumns as rc0 (nolock) where rc0.link_table = @new_link_table and rtrim(rc0.[name]) = rtrim(@cthis_col_name)) = 1 begin
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
				rc0.link_table = @new_link_table
				and rc0.[name] = @cthis_col_name
			--print 'теперь линк колонки =' + cast(@new_link_col as varchar)
		end
		else begin
			-- если не нашли колонку, или колонок с этим именем оказалось несколько, ищем её по ордеру проверяя тип
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
			rc0.link_table = @new_link_table
			and rc0.orders = @nthis_col_order
			and rc0.col_type = @this_link_col_type
		end
		insert into #analitics_period_links (period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, col_type, keyflag, tab_type)
		select distinct
			rsf.period_type,
			rsf.begin_date,
			rsf.period_number,
			rsf.link_form,
			[link_table] = @new_link_table,
			[link_col] = @new_link_col,
			link_col_base = @this_link_col,
			col_type = @this_link_col_type,
			null,
			(select val_type from dbo.report_tables where link_table = @new_link_table)
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = @new_link_form
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd
		
		delete from #analitics_period_copy where period_type = @lpt and period_number = @lpn and period_date = @lpd
	end
	delete from #analitics_links where link_c = @this_link_col
end
update #analitics_period_links
set keyflag = (case when apl.link_col = (select a.link_code_col from dbo.report_tables as a where a.link_table = apl.link_table) then 1 else 0 end)
from #analitics_period_links as apl

-- select * from #analitics_period_links
exec DropTempTable '#tree_link'
create table #tree_link (link int)
insert into #tree_link (link)
select t.link
from dbo.report_svod_tree t
where t.link in (
    select cast((left(ltrim(f.[value]),charindex('@@',ltrim(f.[value]))-1)) as int) from #analitics_filters as f where f.code = 'DEP' or f.code = 'NAME_DEP'
)
-- Создание таблицы сохранённых форм
exec DropTempTable '#sf'
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)
-- предполагается, что к этому моменту существует таблица #analitics_filters, содержащая среди прочего код аналитического признака CODE и текстовое значение VALUE
insert into #sf
select distinct
	rsf.link_saved_form,
	rsf.link_form,
	rsf.period_type,
	rsf.period_number,
	rsf.begin_date,
	rsf.link_organization,
	[btype] = (select [name] from dbo.BI_DICTION_BUDG_TYPE (nolock) where link = rsf.link_type_svod),
rsf.link_type_svod
from report_saved_forms as rsf (nolock)
	inner join (select distinct period_type, period_date, period_number, link_form from #analitics_period_links) as apl
	on
		apl.link_form = rsf.link_form
		and apl.period_date = rsf.begin_date
		and apl.period_type = rsf.period_type
		and apl.period_number = rsf.period_number
      AND rsf.del = 0
    left join dbo.report_svod_tree as rst
    on 
        rsf.link_organization = rst.link_report_org
        and rsf.link_type_svod = rst.link_report_budg
where
	rsf.version =
		case
			when @nFormVersion < 0 or @nFormVersion is null
			then(
				select top 1 version
	 			from 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 lrsf.atr_code = rsf.atr_code
				order by  version desc
			)
			else @nFormVersion
		end		
	and rsf.IsSvod in (
case when @nStatus&0x10 = 0x10 then 1 else -1 end,
		case when @nStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (
case when @nStatus&0x01 = 0x01 then 0 else -1 end,
		case when @nStatus&0x02 = 0x02 then 1 else -1 end,
		case when @nStatus&0x04 = 0x04 then 2 else -1 end,
		case when @nStatus&0x08 = 0x08 then 3 else -1 end,
		case when @nStatus&0x40 = 0x40 then 4 else -1 end,
		case when @nStatus&0x80 = 0x80 then 5 else -1 end)
--	and (
--		rsf.link_organization in (select link from #organizationen_link)
--		or not exists(select * from #analitics_filters where code = 'DEP' or code = 'NAME_DEP' or code = 'BUDG')
--	)
    and (
        rst.link in (select link from #tree_link)
        or not exists(select * from #tree_link)
    )
    and (
		rsf.link_type_svod in (
			select b.link from dbo.kl_budg_type as b (nolock) where b.code in (select rtrim(f.[value]) from #analitics_filters as f where f.code = 'BUD_TYPE')
		)
		or not exists(select * from #analitics_filters where code = 'BUD_TYPE')
	)
	and (
		rsf.link_saved_form in (
			select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = f.code and (rav.str_val = f.[value] /*or rav.int_val = cast(f.[value] as int)*/) where f.type = 2
--			case
--				when exists(select * from #analitics_filters where [type] = 2 and code in (select rav.code_atr from dbo.report_atribut_values as rav where rav.link_saved_form = rsf.link_saved_form))
--				then (select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = f.code and (rav.str_val = f.[value] /*or rav.int_val = cast(f.[value] as int)*/) where f.type = 2)
--				else 0
--			end
		)
		or not exists(select * from #analitics_filters where [type] = 2 and code in (select rav.code_atr from dbo.report_atribut_values as rav where rav.link_saved_form = rsf.link_saved_form))
	)
-- 
--select distinct link_sf from #sf
--return
--

exec DropTempTable '#return_table'
create table #return_table (nn int identity(1,1), code varchar(254), [name] varchar(254))

declare @period_type int,
		@period_date datetime,
		@period_number int,
		@link_form int,
		@link_table int,
		@lnLink_Col int,
		@lnLink_Col_another int,
		@lcDictionary varchar(8000),
		@lcField varchar(8000),
		@lcCol varchar(254),
		@lcFieldStr varchar (254),
		@lcColStr varchar (254),
		@lnPos int,
		@lnPosField int,
		@nFound int,
		@cStrExec varchar(8000)

declare the_cursor cursor local static for
select period_type, period_date, period_number, link_form, link_table, link_col from #analitics_period_links where col_type = 0

open the_cursor
fetch next from the_cursor INTO @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col
while @@fetch_status = 0 begin

       	insert into #return_table (code,[name])
		select distinct left(ltrim(rf.formula),50) as code, null as [name]
		from dbo.report_formula as rf
        where rf.link_row in (select link_row from dbo.report_rows where link_table = @link_table)
        and rf.link_col = (select link_code_col from dbo.report_tables where link_table = @link_table)
        and left(ltrim(rf.formula),50) not in (select left(ltrim(code),50) from #return_table)
        and not exists (select * from dbo.report_forms where left(code,7) = '0503074' and link_form = (select link_form from dbo.report_tables where link_table = @link_table))

		insert into #return_table (code,[name])
		select distinct left(ltrim(dbo.RT_BOK14(rd.code_row)),50) as code, null as [name]
        from dbo.report_dinamics_all as rd
        where rd.link_sf in (select link_sf from #sf)
        and rd.link_col = @lnLink_Col
        and left(ltrim(rd.code_row),50) not in (select left(ltrim(code),50) from #return_table)

	fetch next from the_cursor into @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col
end
close the_cursor
deallocate the_cursor

insert into #tmpFilter(link,checked,code,[name])
select rt.nn as link, (case when tmp.code is not null then 1 else 0 end) as checked, rt.code, right(ltrim(rt.[name]),254)
from #return_table as rt
left join #analitics_filters as tmp
	on rt.code = tmp.[value]
	and tmp.[type] = 0
order by 3

---------------------------------------------------------------------------------------------------------------------------------------------------------
exec DropTempTable '#organizationen_link'
exec DropTempTable '#report_static_table'
exec DropTempTable '#report_dynamic_table'
exec DropTempTable '#analitics_links'
exec DropTempTable '#analitics_period_links'
exec DropTempTable '#return_table'
exec DropTempTable '#sf'
exec DropTempTable '#analitics_period'
---------------------------------------------------------------------------------------------------------------------------------------------------------
GO
grant execute on [dbo].[RT_ANALITICS_OBTAIN_KEY_COL_VAL] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BV_SAVE_G_PROV2_AP_NA_OS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_SAVE_G_PROV2_AP_NA_OS]
GO



/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE dbo.BV_SAVE_G_PROV2_AP_NA_OS
	@varKSnLINK_GP1  INT,		
	@varKSnTYP_LINK INT,			
	@varKSnLINK_INV  INT,			
	@varKSnSUMMA1	NUMERIC(28,2) = 0.00,		
	@varKSnSUMMA2	NUMERIC(28,2) = 0.00,		
	@varKSnQTY NUMERIC(19,4) = 0.00,		
	@varKSdCALC_DATE DATETIME = NULL,	
	@varKSnMode TINYINT = 0, 	

	@varKSpcSOU_CODE CHAR(1) = '1',
	@strINV_TYPE	VARCHAR (30) = NULL

AS

DECLARE @varKScSOU_CODE CHAR(1),

	@varKSnKBK INT,
	@varKSnEKR INT,
	@varKSnDEP INT,
	@varKSnSUB INT,
	@varKSnEMP INT,
	@varKSnNOMEN INT,
	@varKSnINV INT,
	@varKSnKAU INT,
	@varKSnDEP_ACC INT,
	@varKSnTMC INT,
	@varKSnINDATE DATETIME,
	@varKSnAP1 INT,
	@varKSnAP2 INT,
	@varKSnAP3 INT,

	@varKSnSGU_DT INT,
	@varKSnKBK_DT INT,
	@varKSnEKR_DT INT,
	@varKSnDEP_DT INT,
	@varKSnSUB_DT INT,
	@varKSnEMP_DT INT,
	@varKSnNOMEN_DT INT,
	@varKSnINV_DT INT,
	@varKSnKAU_DT INT,
	@varKSnDEP_ACC_DT INT,
	@varKSnTMC_DT INT,
	@varKSnINDATE_DT DATETIME,
	@varKSnAP1_DT INT,
	@varKSnAP2_DT INT,
	@varKSnAP3_DT INT,

	@varKSnSGU_KT INT,
	@varKSnKBK_KT INT,
	@varKSnEKR_KT INT,
	@varKSnDEP_KT INT,
	@varKSnSUB_KT INT,
	@varKSnEMP_KT INT,
	@varKSnNOMEN_KT INT,
	@varKSnINV_KT INT,
	@varKSnKAU_KT INT,
	@varKSnDEP_ACC_KT INT,
	@varKSnTMC_KT INT,
	@varKSnINDATE_KT DATETIME,
	@varKSnAP1_KT INT,
	@varKSnAP2_KT INT,
	@varKSnAP3_KT INT,

	@varKSnSumma NUMERIC(28,2),
	@varKSnQTY_Prov NUMERIC(19,4),
	@varKSnG2_LINK  INT,
	@varKScG2_NAME  VARCHAR(254),
	@varKSnG2_ECON_OPER INT,
	@varKSnG2_ORDERS INT,
	@varKSnGAP_ACCOUNT_DT INT,
	@varKSnGAP_ACCOUNT_KT INT,
	@varKSnLINK_GP2 INT,
	@varKSnLINK_ACC_DT INT,
	@varKSnLINK_ACC_KT INT,
	@varKSLINK_DOC INT,
	@varKSxRet INT,
	@varKSnDEP_LINK INT,
	@varKSnRowCount INT

IF ISNULL (@strINV_TYPE, '') = ''
	SET @strINV_TYPE = 'INVENTORY_CARD'

DECLARE G2_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT LINK, NAME, ECON_OPER, ORDERS FROM G_PROV2 WHERE LINK_UP = @varKSnTYP_LINK

IF @varKSnLINK_GP1 IS NULL
	RETURN -1	

IF @varKSdCALC_DATE IS NULL
	SELECT @varKSdCALC_DATE = WORKDATE FROM USER_INFO

IF @varKSpcSOU_CODE IS NULL OR @varKSpcSOU_CODE = ''
	SET @varKSpcSOU_CODE = '1'

-- Проверка на наличие проводки списания ост. ст-ти: если есть, то @varKSnSUMMA1 - остаточная стоимость, если нет - балансовая
IF NOT EXISTS(SELECT G2.*, SA_D.CODE, *
		FROM dbo.G_PROV2 G2
		INNER JOIN dbo.G_PROV_AP GAP_D ON (GAP_D.LINK_UP = G2.LINK
			AND GAP_D.DB_KR = 0)
		INNER JOIN dbo.S_ACCOUNTS SA_D ON (SA_D.LINK = GAP_D.ACCOUNT
				AND SA_D.cSINTH = '104'
				AND SA_D.ZABALANS = 0)
		INNER JOIN dbo.G_PROV_AP GAP_K ON (GAP_K.LINK_UP = G2.LINK
			AND GAP_K.DB_KR = 1)
		INNER JOIN dbo.S_ACCOUNTS SA_K ON (SA_K.LINK = GAP_K.ACCOUNT
				AND SA_K.cSINTH = '101'
				AND SA_K.ZABALANS = 0)
		WHERE G2.LINK_UP = @varKSnTYP_LINK
		)

	SET @varKSnSUMMA1 = @varKSnSUMMA1 + @varKSnSUMMA2 -- балансовая стоимость

-- Вычисление организации для ЦБ
SELECT TOP 1 @varKSnDEP_LINK = G.DEP 
FROM G_PROV G,  G_PROV1 G1 
WHERE G1.LINK = @varKSnLINK_GP1 AND G.LINK = G1.LINK_UP

SELECT TOP 1
	[ORDERS] = CASE WHEN EXISTS(SELECT * FROM S_ACCOUNTS SAT WHERE SAT.LINK = SA.LINK
								 AND SAT.cSinth = SA.cSinth)
			THEN 0 ELSE 1 END,			
	SA.cSource,
	SA.cSinth,
	SA.cAnalit,
	SA.cUser,
	SA.CODE,
	ART.* 
INTO #REST_OS_DT
FROM dbo.ARestGroupedTableByDate(@varKSdCALC_DATE, DEFAULT, DEFAULT) ART, S_ACCOUNTS SA
WHERE ART.DEP_LINK = @varKSnDEP_LINK AND ART.INV = @varKSnLINK_INV AND ART.ACCOUNT = SA.LINK 
	AND SA.cSINTH = '104'
ORDER BY 1, 6, D_SUMMA DESC

SELECT TOP 1
	[ORDERS] = CASE WHEN EXISTS(SELECT * FROM S_ACCOUNTS SAT WHERE SAT.LINK = SA.LINK
								 AND SAT.cSinth = SA.cSinth)
			THEN 0 ELSE 1 END,			
	SA.cSource,
	SA.cSinth,
	SA.cAnalit,
	SA.cUser,
	SA.CODE,
	ART.* 
INTO #REST_OS_KT
FROM dbo.ARestGroupedTableByDate(@varKSdCALC_DATE, DEFAULT, DEFAULT) ART, S_ACCOUNTS SA
WHERE ART.DEP_LINK = @varKSnDEP_LINK
	AND (@strINV_TYPE = 'INVENTORY_CARD' AND ART.INV = @varKSnLINK_INV
		OR @strINV_TYPE = 'BV_NOMENCLATURE' AND ART.NOMEN = @varKSnLINK_INV)
	AND ART.ACCOUNT = SA.LINK 
	AND (cSINTH = '101' OR cSINTH = '108'
		OR SA.ZABALANS = 1)
		
ORDER BY 1, 6, D_SUMMA DESC

OPEN G2_CUR
FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK, @varKScG2_NAME, @varKSnG2_ECON_OPER, @varKSnG2_ORDERS

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT GAP.* 
	INTO #GAP_CUR
	FROM G_PROV_AP GAP
	WHERE GAP.LINK_UP = @varKSnG2_LINK

	SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT, @varKSnSGU_DT = SGU,
			@varKSnKBK_DT = KBK,
			@varKSnEKR_DT = EKR,
			@varKSnDEP_DT = DEP,
			@varKSnSUB_DT = SUB,
			@varKSnEMP_DT = EMP,
			@varKSnNOMEN_DT = NOMEN,
			@varKSnINV_DT = INV,
			@varKSnKAU_DT = KAU,
			@varKSnDEP_ACC_DT = DEP_ACC,
			@varKSnTMC_DT = TMC,
			@varKSnINDATE_DT = INDATE,
			@varKSnAP1_DT = AP1,
			@varKSnAP2_DT = AP2,
			@varKSnAP3_DT = AP3
	FROM #GAP_CUR
	WHERE DB_KR = 0

	IF @@ROWCOUNT = 0
		SELECT @varKSnGAP_ACCOUNT_DT = NULL, @varKSnSGU_DT = NULL,
			@varKSnKBK_DT = NULL,
			@varKSnEKR_DT = NULL,
			@varKSnDEP_DT = NULL,
			@varKSnSUB_DT = NULL,
			@varKSnEMP_DT = NULL,
			@varKSnNOMEN_DT = NULL,
			@varKSnINV_DT = NULL,
			@varKSnKAU_DT = NULL,
			@varKSnDEP_ACC_DT = NULL,
			@varKSnTMC_DT = NULL,
			@varKSnINDATE_DT = NULL,
			@varKSnAP1_DT = NULL,
			@varKSnAP2_DT = NULL,
			@varKSnAP3_DT = NULL

	SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT, @varKSnSGU_KT = SGU,
			@varKSnKBK_KT = KBK,
			@varKSnEKR_KT = EKR,
			@varKSnDEP_KT = DEP,
			@varKSnSUB_KT = SUB,
			@varKSnEMP_KT = EMP,
			@varKSnNOMEN_KT = NOMEN,
			@varKSnINV_KT = INV,
			@varKSnKAU_KT = KAU,
			@varKSnDEP_ACC_KT = DEP_ACC,
			@varKSnTMC_KT = TMC,
			@varKSnINDATE_KT = INDATE,
			@varKSnAP1_KT = AP1,
			@varKSnAP2_KT = AP2,
			@varKSnAP3_KT = AP3
	FROM #GAP_CUR
	WHERE DB_KR = 1

	IF @@ROWCOUNT = 0
		SELECT @varKSnGAP_ACCOUNT_KT = NULL, @varKSnSGU_KT = NULL,
			@varKSnKBK_KT = NULL,
			@varKSnEKR_KT = NULL,
			@varKSnDEP_KT = NULL,
			@varKSnSUB_KT = NULL,
			@varKSnEMP_KT = NULL,
			@varKSnNOMEN_KT = NULL,
			@varKSnINV_KT = NULL,
			@varKSnKAU_KT = NULL,
			@varKSnDEP_ACC_KT = NULL,
			@varKSnTMC_KT = NULL,
			@varKSnINDATE_KT = NULL,
			@varKSnAP1_KT = NULL,
			@varKSnAP2_KT = NULL,
			@varKSnAP3_KT = NULL


	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND cSinth = '104') OR
		EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_KT AND cSinth = '104')
		SET @varKSnSumma = @varKSnSUMMA2
	ELSE
		SET @varKSnSumma = @varKSnSUMMA1

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND ZABALANS = 1)
		SET @varKSnSumma = @varKSnSUMMA1 + @varKSnSUMMA2 -- балансовая стоимость

	IF @varKSnSumma = 0
	  BEGIN
		FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK, @varKScG2_NAME, @varKSnG2_ECON_OPER, @varKSnG2_ORDERS
		DROP TABLE #GAP_CUR
		CONTINUE
	  END 
		
/*
	SELECT TOP 1 
		SA.cSource,
		SA.cSinth,
		SA.cAnalit,
		SA.cUser,
		SA.CODE,
		ART.* 
	INTO #REST_OS
	FROM dbo.ARestTableByDate(@varKSdCALC_DATE, default) ART, S_ACCOUNTS SA, S_ACCOUNTS SAT
	WHERE  ART.INV = @varKSnLINK_INV AND ART.ACCOUNT = SA.LINK AND (SA.cSinth = SAT.cSinth AND SAT.cSinth <> '104' OR SA.cSinth = '101'  AND SAT.cSinth = '104') AND (SAT.LINK = @varKSnGAP_ACCOUNT_DT OR SAT.LINK = @varKSnGAP_ACCOUNT_KT)
	ORDER BY SA.cSinth
*/
-- Расчет аналитики по Дт
/*
	SELECT TOP 1
		[ORDERS] = CASE WHEN EXISTS(SELECT * FROM S_ACCOUNTS SAT WHERE SAT.LINK = @varKSnGAP_ACCOUNT_DT
									 AND SAT.cSinth = SA.cSinth)
				THEN 0 ELSE 1 END,			
		SA.cSource,
		SA.cSinth,
		SA.cAnalit,
		SA.cUser,
		SA.CODE,
		ART.* 
	INTO #REST_OS_DT
	FROM dbo.ARestGroupedTableByDate(@varKSdCALC_DATE, DEFAULT, DEFAULT) ART, S_ACCOUNTS SA
	WHERE ART.DEP_LINK = @varKSnDEP_LINK AND ART.INV = @varKSnLINK_INV AND ART.ACCOUNT = SA.LINK 
	ORDER BY 1, 6, D_SUMMA DESC
*/
--	SET @varKSnRowCount = @@ROWCOUNT

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND ZABALANS = 1)
		SELECT 	@varKScSOU_CODE = cSource,
			@varKSnKBK = KBK,
			@varKSnEKR = EKR,
			@varKSnDEP = DEP,
			@varKSnSUB = dbo.SubdivisionLink (@varKSdCALC_DATE, SUB),
			@varKSnEMP = EMP,
			@varKSnNOMEN = NOMEN,
			@varKSnINV = INV,
			@varKSnKAU = KAU,
			@varKSnDEP_ACC = DEP_ACC,
			@varKSnTMC = TMC,
			@varKSnAP1 = AP1,
			@varKSnAP2 = AP2,
			@varKSnAP3 = AP3,
			@varKSnINDATE = INDATE
		FROM #REST_OS_KT ROS
	ELSE
		SELECT 	@varKScSOU_CODE = cSource,
			@varKSnKBK = KBK,
			@varKSnEKR = EKR,
			@varKSnDEP = DEP,
			@varKSnSUB = dbo.SubdivisionLink (@varKSdCALC_DATE, SUB),
			@varKSnEMP = EMP,
			@varKSnNOMEN = NOMEN,
			@varKSnINV = INV,
			@varKSnKAU = KAU,
			@varKSnDEP_ACC = DEP_ACC,
			@varKSnTMC = TMC,
			@varKSnAP1 = AP1,
			@varKSnAP2 = AP2,
			@varKSnAP3 = AP3,
			@varKSnINDATE = INDATE
		FROM #REST_OS_DT ROS

		
SET @varKSnRowCount = @@ROWCOUNT

	IF @varKSnRowCount = 0
		SELECT @varKScSOU_CODE = @varKSpcSOU_CODE,
			@varKSnKBK = NULL,
			@varKSnEKR = NULL,
			@varKSnDEP = NULL,
			@varKSnSUB = NULL,
			@varKSnEMP = NULL,
			@varKSnNOMEN = NULL,
			@varKSnINV = @varKSnLINK_INV,
			@varKSnKAU = NULL,
			@varKSnDEP_ACC = NULL,
			@varKSnTMC = NULL,
			@varKSnAP1 = NULL,
			@varKSnAP2 = NULL,
			@varKSnAP3 = NULL,
			@varKSnINDATE = NULL



	SELECT 		
			@varKSnKBK_DT = ISNULL(@varKSnKBK, @varKSnKBK_DT),
			@varKSnEKR_DT = ISNULL(@varKSnEKR, @varKSnEKR_DT),
			@varKSnDEP_DT = ISNULL(@varKSnDEP, @varKSnDEP_DT),
			@varKSnSUB_DT = ISNULL(@varKSnSUB, @varKSnSUB_DT),
			@varKSnEMP_DT = ISNULL(@varKSnEMP, @varKSnEMP_DT),
			@varKSnNOMEN_DT = ISNULL(@varKSnNOMEN, @varKSnNOMEN_DT),
			@varKSnINV_DT = ISNULL(@varKSnINV, @varKSnINV_DT),
			@varKSnKAU_DT = ISNULL(@varKSnKAU, @varKSnKAU_DT),
			@varKSnDEP_ACC_DT = ISNULL(@varKSnDEP_ACC, @varKSnDEP_ACC_DT),
			@varKSnTMC_DT = ISNULL(@varKSnTMC, @varKSnTMC_DT),
			@varKSnINDATE_DT = ISNULL(@varKSnINDATE, @varKSnINDATE_DT),
			@varKSnAP1_DT = ISNULL(@varKSnAP1, @varKSnAP1_DT),
			@varKSnAP2_DT = ISNULL(@varKSnAP2, @varKSnAP2_DT),
			@varKSnAP3_DT = ISNULL(@varKSnAP3, @varKSnAP3_DT)

-- Расчет аналитики по Кт
/*
	SELECT TOP 1
		[ORDERS] = CASE WHEN EXISTS(SELECT * FROM S_ACCOUNTS SAT WHERE SAT.LINK = @varKSnGAP_ACCOUNT_KT
									 AND SAT.cSinth = SA.cSinth)
				THEN 0 ELSE 1 END,			
		SA.cSource,
		SA.cSinth,
		SA.cAnalit,
		SA.cUser,
		SA.CODE,
		ART.* 
	INTO #REST_OS_KT
	FROM dbo.ARestGroupedTableByDate(@varKSdCALC_DATE, DEFAULT, DEFAULT) ART, S_ACCOUNTS SA
	WHERE ART.DEP_LINK = @varKSnDEP_LINK AND ART.INV = @varKSnLINK_INV AND ART.ACCOUNT = SA.LINK 
	ORDER BY 1, 6, D_SUMMA DESC
*/
/*
select * from #REST_OS_dT
select * from #REST_OS_KT
*/
--	SET @varKSnRowCount = @@ROWCOUNT
	
		SELECT 	@varKScSOU_CODE = cSource,
			@varKSnKBK = KBK,
			@varKSnEKR = EKR,
			@varKSnDEP = DEP,
			@varKSnSUB = dbo.SubdivisionLink (@varKSdCALC_DATE, SUB),
			@varKSnEMP = EMP,
			@varKSnNOMEN = NOMEN,
			@varKSnINV = INV,
			@varKSnKAU = KAU,
			@varKSnDEP_ACC = DEP_ACC,
			@varKSnTMC = TMC,
			@varKSnAP1 = AP1,
			@varKSnAP2 = AP2,
			@varKSnAP3 = AP3,
			@varKSnINDATE = INDATE
		FROM #REST_OS_KT ROS
		SET @varKSnRowCount = @@ROWCOUNT
	
	IF @varKSnRowCount = 0
		SELECT @varKScSOU_CODE = @varKSpcSOU_CODE,
			@varKSnKBK = NULL,
			@varKSnEKR = NULL,
			@varKSnDEP = NULL,
			@varKSnSUB = NULL,
			@varKSnEMP = NULL,
			@varKSnNOMEN = NULL,
			@varKSnINV = @varKSnLINK_INV,
			@varKSnKAU = NULL,
			@varKSnDEP_ACC = NULL,
			@varKSnTMC = NULL,
			@varKSnAP1 = NULL,
			@varKSnAP2 = NULL,
			@varKSnAP3 = NULL,
			@varKSnINDATE = NULL


	SELECT 		
			@varKSnKBK_KT = ISNULL(@varKSnKBK, @varKSnKBK_KT),
			@varKSnEKR_KT = ISNULL(@varKSnEKR, @varKSnEKR_KT),
			@varKSnDEP_KT = ISNULL(@varKSnDEP, @varKSnDEP_KT),
			@varKSnSUB_KT = ISNULL(@varKSnSUB, @varKSnSUB_KT),
			@varKSnEMP_KT = ISNULL(@varKSnEMP, @varKSnEMP_KT),
			@varKSnNOMEN_KT = ISNULL(@varKSnNOMEN, @varKSnNOMEN_KT),
			@varKSnINV_KT = ISNULL(@varKSnINV, @varKSnINV_KT),
			@varKSnKAU_KT = ISNULL(@varKSnKAU, @varKSnKAU_KT),
			@varKSnDEP_ACC_KT = ISNULL(@varKSnDEP_ACC, @varKSnDEP_ACC_KT),
			@varKSnTMC_KT = ISNULL(@varKSnTMC, @varKSnTMC_KT),
			@varKSnINDATE_KT = ISNULL(@varKSnINDATE, @varKSnINDATE_KT),
			@varKSnAP1_KT = ISNULL(@varKSnAP1, @varKSnAP1_KT),
			@varKSnAP2_KT = ISNULL(@varKSnAP2, @varKSnAP2_KT),
			@varKSnAP3_KT = ISNULL(@varKSnAP3, @varKSnAP3_KT)

	SELECT @varKSLINK_DOC = LINK_UP FROM G_PROV1 WHERE LINK = @varKSnLINK_GP1

	IF @varKSnMode = 1 OR @varKSnMode = 3
	  BEGIN
		SELECT TOP 1 @varKSnKBK_DT = ISNULL(VAL_LINK, @varKSnKBK_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'KBK' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnEKR_DT = ISNULL(VAL_LINK, @varKSnEKR_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'EKR' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnDEP_DT = ISNULL(VAL_LINK, @varKSnDEP_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'DEP' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnSUB_DT = ISNULL(VAL_LINK, @varKSnSUB_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'SUB' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnEMP_DT = ISNULL(VAL_LINK, @varKSnEMP_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'EMP' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnNOMEN_DT = ISNULL(VAL_LINK, @varKSnNOMEN_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'NOMEN' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnINV_DT = ISNULL(VAL_LINK, @varKSnINV_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'INV' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnKAU_DT = ISNULL(VAL_LINK, @varKSnKAU_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'KAU' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnDEP_ACC_DT = ISNULL(VAL_LINK, @varKSnDEP_ACC_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'DEP_ACC' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnTMC_DT = ISNULL(VAL_LINK, @varKSnTMC_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'TMC' AND TAB_DTKT = 0


		SELECT TOP 1 @varKSnAP1_DT = ISNULL(VAL_LINK, @varKSnAP1_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP1' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnAP2_DT = ISNULL(VAL_LINK, @varKSnAP2_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP2' AND TAB_DTKT = 0
		SELECT TOP 1 @varKSnAP3_DT = ISNULL(VAL_LINK, @varKSnAP3_DT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP3' AND TAB_DTKT = 0
	  END

	IF @varKSnMode = 2 OR @varKSnMode = 3
	  BEGIN
		SELECT TOP 1 @varKSnKBK_KT = ISNULL(VAL_LINK, @varKSnKBK_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'KBK' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnEKR_KT = ISNULL(VAL_LINK, @varKSnEKR_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'EKR' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnDEP_KT = ISNULL(VAL_LINK, @varKSnDEP_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'DEP' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnSUB_KT = ISNULL(VAL_LINK, @varKSnSUB_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'SUB' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnEMP_KT = ISNULL(VAL_LINK, @varKSnEMP_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'EMP' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnNOMEN_KT = ISNULL(VAL_LINK, @varKSnNOMEN_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'NOMEN' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnINV_KT = ISNULL(VAL_LINK, @varKSnINV_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'INV' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnKAU_KT = ISNULL(VAL_LINK, @varKSnKAU_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'KAU' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnDEP_ACC_KT = ISNULL(VAL_LINK, @varKSnDEP_ACC_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'DEP_ACC' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnTMC_KT = ISNULL(VAL_LINK, @varKSnTMC_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'TMC' AND TAB_DTKT = 1


		SELECT TOP 1 @varKSnAP1_KT = ISNULL(VAL_LINK, @varKSnAP1_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP1' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnAP2_KT = ISNULL(VAL_LINK, @varKSnAP2_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP2' AND TAB_DTKT = 1
		SELECT TOP 1 @varKSnAP3_KT = ISNULL(VAL_LINK, @varKSnAP3_KT) 
			FROM DOC_ANALIT_TABLE_70N WHERE LINK_UP = @varKSLINK_DOC AND CODE_AP = 'AP3' AND TAB_DTKT = 1
	  END



	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND cSinth IN ('101','102','103', '105', '108', '201'))
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_DT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth IN ('101','102','103', '105', '108', '201'))
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = SA.LINK
			FROM INVENTORY I, NOMENCLATURE N,  GROUP_INV GI, S_ACCOUNTS SA
			WHERE I.LINK = @varKSnLINK_INV AND N.LINK = I.NOMENCLATURE AND GI.LINK = N.GROUP_INV AND SA.LINK = GI.ACCOUNT
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_KT AND cSinth IN ('101','102','103', '105', '108', '201'))
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_KT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth IN ('101','102','103', '105', '108', '201'))
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = SA.LINK
			FROM INVENTORY I, NOMENCLATURE N,  GROUP_INV GI, S_ACCOUNTS SA
			WHERE I.LINK = @varKSnLINK_INV AND N.LINK = I.NOMENCLATURE AND GI.LINK = N.GROUP_INV AND SA.LINK = GI.ACCOUNT
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND cSinth = '104')
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_DT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth = '104')
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = SA2.LINK
			FROM INVENTORY I, NOMENCLATURE N,  GROUP_INV GI, S_ACCOUNTS SA1, S_ACCOUNTS SA2
			WHERE I.LINK = @varKSnLINK_INV AND N.LINK = I.NOMENCLATURE AND GI.LINK = N.GROUP_INV AND SA1.LINK = GI.ACCOUNT
			AND SA2.cSinth = '104'
			AND ((SA2.cAnalit = SA1.cAnalit AND SA1.cSinth = '101' AND SA1.cAnalit LIKE ('0[1-7]'))
			 OR (SA2.cAnalit = '08' AND SA1.cSinth = '101' AND SA1.cAnalit = '09')
			 OR (SA2.cAnalit = '09' AND SA1.cSinth = '102'))
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_KT AND cSinth = '104')
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_KT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth = '104')
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = SA2.LINK
			FROM INVENTORY I, NOMENCLATURE N,  GROUP_INV GI, S_ACCOUNTS SA1, S_ACCOUNTS SA2
			WHERE I.LINK = @varKSnLINK_INV AND N.LINK = I.NOMENCLATURE AND GI.LINK = N.GROUP_INV AND SA1.LINK = GI.ACCOUNT
			AND SA2.cSinth = '104'
			AND ((SA2.cAnalit = SA1.cAnalit AND SA1.cSinth = '101' AND SA1.cAnalit LIKE ('0[1-7]'))
			 OR (SA2.cAnalit = '08' AND SA1.cSinth = '101' AND SA1.cAnalit = '09')
			 OR (SA2.cAnalit = '09' AND SA1.cSinth = '102'))
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_KT AND cSinth = 'ОС')
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_KT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth = 'ОС')
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = SA2.LINK
			FROM INVENTORY I, NOMENCLATURE N,  GROUP_INV GI, S_ACCOUNTS SA1, S_ACCOUNTS SA2
			WHERE I.LINK = @varKSnLINK_INV
				AND N.LINK = I.NOMENCLATURE
				AND GI.LINK = N.GROUP_INV
				AND SA1.LINK = GI.ACCOUNT
			AND SA2.cSinth = 'ОС'
			AND SA2.cAnalit = SA1.cAnalit

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND cSinth = 'ОС')
		  IF @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
		    IF EXISTS(SELECT * FROM #REST_OS_DT R, S_ACCOUNTS SA WHERE R.ACCOUNT = SA.LINK AND SA.cSinth = 'ОС')
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = SA2.LINK
			FROM dbo.INVENTORY I, dbo.NOMENCLATURE N,  dbo.GROUP_INV GI, dbo.AMORT_ACCT_GROUP_INV AA, dbo.S_ACCOUNTS SA2
			WHERE I.LINK = @varKSnLINK_INV
				AND N.LINK = I.NOMENCLATURE
				AND GI.LINK = N.GROUP_INV
				AND LEFT (GI.CODE, 5) = AA.ACCT1
				AND SA2.cSinth = 'ОС'
				AND SA2.cAnalit = AA.cANALIT1

/*		  ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
*/

/*
select link, code 
from s_accounts
where link in (@varKSnGAP_ACCOUNT_DT, @varKSnGAP_ACCOUNT_kT)
*/
	SELECT TOP 1 @varKSnLINK_ACC_DT = SA2.LINK
	FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2
	WHERE SA1.LINK = @varKSnGAP_ACCOUNT_DT 
		AND SA2.ZABALANS = SA1.ZABALANS
		AND SA2.cAnalit = SA1.cAnalit
		AND ((LEN(SA1.cSinth) = 3 AND SA1.cSinth = SA2.cSinth) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
		AND SA2.cUser = SA1.cUser
		AND SA2.cSource = @varKScSOU_CODE
	IF @@ROWCOUNT <> 1
		SET @varKSnLINK_ACC_DT = @varKSnGAP_ACCOUNT_DT

	SELECT TOP 1 @varKSnLINK_ACC_KT = SA2.LINK
	FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2 WHERE SA1.LINK = @varKSnGAP_ACCOUNT_KT 
		AND SA2.ZABALANS = SA1.ZABALANS
		AND SA2.cAnalit = SA1.cAnalit
		AND ((LEN(SA1.cSinth) = 3 AND SA1.cSinth = SA2.cSinth) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
		AND SA2.cUser = SA1.cUser
		AND SA2.cSource = @varKScSOU_CODE
	IF @@ROWCOUNT <> 1
		SET @varKSnLINK_ACC_KT = @varKSnGAP_ACCOUNT_KT



-- Проверка на то, что счет не имеет дочерних субсчетов
	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK_SELF = @varKSnLINK_ACC_DT) -- счет имеет дочерние субсчета
	  AND @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
	  BEGIN
		SELECT @varKSnLINK_ACC_DT = dbo.BK_GetDBKTAccount (@varKSnLINK_ACC_DT, DEFAULT, DEFAULT, DEFAULT)
	  END
	
	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK_SELF = @varKSnLINK_ACC_KT) -- счет имеет дочерние субсчета
	  AND @varKSnLINK_INV IS NOT NULL AND @varKSnLINK_INV <> 0
	  BEGIN
		SELECT @varKSnLINK_ACC_KT = (SELECT TOP 1 SA2.LINK
					FROM G_PROV_AP GAP, S_ACCOUNTS SA1, S_ACCOUNTS SA2 
					WHERE GAP.INV = @varKSnLINK_INV AND GAP.ACCOUNT = SA1.LINK
						AND SA2.LINK_SELF = @varKSnLINK_ACC_KT AND SA1.cUser = SA2.cUser
						AND dbo.AccountsHasNoChild (SA2.LINK) = 1
					ORDER BY SA1.ZABALANS, SA1.cSinth)
	  END
	

	IF @varKSnSGU_DT IS NULL 
--	OR NOT EXISTS(SELECT * FROM S_ACCOUNTS_SGU S, KOSGU K WHERE S.ACCOUNT = @varKSnLINK_ACC_DT AND S.LINK_SGU = K.LINK AND K.LINK = @varKSnSGU_DT AND DB_KR = 0)
		SELECT TOP 1 @varKSnSGU_DT = K.LINK FROM S_ACCOUNTS_SGU S, KOSGU K WHERE S.ACCOUNT = @varKSnLINK_ACC_DT AND S.LINK_SGU = K.LINK AND K.DB_KR = 0

	IF @varKSnSGU_KT IS NULL 
--	OR NOT EXISTS(SELECT * FROM S_ACCOUNTS_SGU S, KOSGU K WHERE S.ACCOUNT = @varKSnLINK_ACC_KT AND S.LINK_SGU = K.LINK AND K.LINK = @varKSnSGU_KT AND DB_KR = 1)
		SELECT TOP 1 @varKSnSGU_KT = K.LINK FROM S_ACCOUNTS_SGU S, KOSGU K WHERE S.ACCOUNT = @varKSnLINK_ACC_KT AND S.LINK_SGU = K.LINK AND K.DB_KR = 1


/*
	--- Переделал Климченко М.В. 20080703: Количество надо ставить в первой проводке, в которой на
		счетах есть КСУ. При списании ОС 104-101 не ставилось кол-во, когда амортизация=бал.стоимости

	IF NOT EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK IN (@varKSnGAP_ACCOUNT_DT, @varKSnGAP_ACCOUNT_KT) AND KSU = CONVERT(TINYINT,1)) OR
		EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK IN (@varKSnGAP_ACCOUNT_DT, @varKSnGAP_ACCOUNT_KT) AND cSinth = '104') 
		SET @varKSnQTY_Prov = 0
	ELSE
		SET @varKSnQTY_Prov = @varKSnQTY
*/
	IF (EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK IN (@varKSnLINK_ACC_DT, @varKSnLINK_ACC_KT)
			AND KSU = CONVERT(TINYINT,1)
			AND ZABALANS = 0)
			AND @varKSnQTY <> ISNULL ((SELECT SUM (QUANTITY) FROM dbo.G_PROV2 WHERE LINK_UP = @varKSnLINK_GP1), 0))
		OR (EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK IN (@varKSnLINK_ACC_DT, @varKSnLINK_ACC_KT)
			AND KSU = CONVERT(TINYINT,1)
			AND ZABALANS = 1))
		SET @varKSnQTY_Prov = @varKSnQTY
	ELSE
		SET @varKSnQTY_Prov = 0
--			AND KSU = CONVERT(TINYINT,1)
--			AND ZABALANS = 1
--- Климченко М.В. 20080703: = END

-- Если нет счетов, зачем формировать операцию???
	IF  @varKSnLINK_ACC_DT IS NULL AND @varKSnLINK_ACC_KT IS NULL 	
	BEGIN
		FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK, @varKScG2_NAME, @varKSnG2_ECON_OPER, @varKSnG2_ORDERS
		DROP TABLE #GAP_CUR
		CONTINUE
	END 
	
	SET @varKSnLINK_GP2 = NULL

	SELECT TOP 1 @varKScG2_NAME = ISNULL(RTRIM(@varKScG2_NAME) + ' ', '') + 'Мат.ценность (Инвентарь):' + RTRIM(CODE) + ' ' + RTRIM(NAME) FROM INVENTORY WHERE LINK = @varKSnLINK_INV

	EXEC @varKSxRet = X_UPDATE_G_PROV2 @varKSnLINK_GP2 OUTPUT, @varKSnLINK_GP1, NULL,
		@varKSnSumma, @varKSnQTY_Prov, 0, @varKScG2_NAME, @varKSnG2_ECON_OPER,  @varKSnG2_ORDERS
	IF @varKSxRet <> 0
		RETURN @varKSxRet
	IF @varKSnLINK_GP2 IS NULL
		RETURN -3	

	IF @varKSnLINK_ACC_DT IS NOT NULL AND @varKSnLINK_ACC_DT > 0
	  BEGIN
		IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE p_KASSA = 1  AND LINK = @varKSnLINK_ACC_DT)
		  SET @varKSnEKR_DT = @varKSnSGU_DT

		SELECT @varKSnEKR_DT = ANALIT_EKR FROM S_ACCOUNTS WHERE LINK = @varKSnLINK_ACC_DT AND p_EKR = 1

		EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 0, @varKSnLINK_ACC_DT, @varKSnKBK_DT, @varKSnEKR_DT, @varKSnDEP_DT,
			@varKSnSUB_DT, @varKSnEMP_DT, @varKSnNOMEN_DT, @varKSnINV_DT, @varKSnKAU_DT, @varKSnDEP_ACC_DT, @varKSnTMC_DT, @varKSnINDATE_DT, @varKSnAP1_DT, @varKSnAP2_DT, @varKSnAP3_DT, @varKSnSGU_DT
		IF @varKSxRet <> 0
			RETURN @varKSxRet
	  END
	
	
	IF @varKSnLINK_ACC_KT IS NOT NULL AND @varKSnLINK_ACC_KT > 0
	  BEGIN
		IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE p_KASSA = 1  AND LINK = @varKSnLINK_ACC_KT)
		  SET @varKSnEKR_KT = @varKSnSGU_KT

		SELECT @varKSnEKR_KT = ANALIT_EKR FROM S_ACCOUNTS WHERE LINK = @varKSnLINK_ACC_KT AND p_EKR = 1

		EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 1, @varKSnLINK_ACC_KT, @varKSnKBK_KT, @varKSnEKR_KT, @varKSnDEP_KT,
			@varKSnSUB_KT, @varKSnEMP_KT, @varKSnNOMEN_KT, @varKSnINV_KT, @varKSnKAU_KT, @varKSnDEP_ACC_KT, @varKSnTMC_KT, @varKSnINDATE_KT, @varKSnAP1_KT, @varKSnAP2_KT, @varKSnAP3_KT, @varKSnSGU_KT
		IF @varKSxRet <> 0
			RETURN @varKSxRet
	  END

/*
	DROP TABLE #REST_OS_DT
	DROP TABLE #REST_OS_KT
*/
	DROP TABLE #GAP_CUR
	FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK, @varKScG2_NAME, @varKSnG2_ECON_OPER, @varKSnG2_ORDERS
END

CLOSE G2_CUR
DEALLOCATE G2_CUR


RETURN 0




GO
GRANT ALL ON dbo.[BV_SAVE_G_PROV2_AP_NA_OS] 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.[KO_REP_ASSIGNMENT_CLASS_CHIN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KO_REP_ASSIGNMENT_CLASS_CHIN]

GO

CREATE PROCEDURE dbo.KO_REP_ASSIGNMENT_CLASS_CHIN
	@nSel_Spr1 int
AS


DECLARE @RESULT TABLE (						
						[FIO]			VARCHAR(100),	-- ФИО			
						[POST]			VARCHAR(254),	-- Должность
						[SUBDIV]		VARCHAR(254),	-- Подразделение			
						[PROF_KV]		VARCHAR(2000),	-- Сведения о проф.переподготовке и пов.квалификации
						[UCH_ST]		VARCHAR(50),	-- Ученая степень
						[UCH_ZV]		VARCHAR(50),	-- Ученое звание						
						[DATE_BEGIN]	DATETIME,		-- Дата назначения на должность				
						[CHIN_PR]		VARCHAR(254),	-- Новый классный чин
						[DATE]			DATETIME,		-- Дата присвоения нового чина						
						[KLAS_CHIN]		VARCHAR(254),	-- Текущий классный чин
						[DATE_CHIN]		DATETIME,		-- Дата присвоения текущего классного чина
						[POSTGROUP]		VARCHAR(60),	-- Группа должностей
						[KATEG] VARCHAR(50),			-- Категория
						[EDUC_NAME]		VARCHAR(80),	-- Тип образования
						[SPEC_NAME]		VARCHAR(254),	-- Специальность
						[OBW_EXPIR]		VARCHAR(20),			-- Общий стаж
						[GS_EXPIR]		VARCHAR(20))			-- Стаж госслужбы

DECLARE @DATE_CHIN DATETIME
DECLARE @EMPL_LINK INT
DECLARE @ATT_LINK INT
SELECT	@DATE_CHIN =DATE, @EMPL_LINK = EMPL_LINK, @ATT_LINK = ATT_KOM_LINK 
FROM EMPL_CHIN 
WHERE LINK = @nSel_Spr1

-- Сведения о сотруднике ----------------------------------------------------------
DECLARE @KU_EMPL_PLACING_FN TABLE (	LINK INT, 
									PERS_LINK INT,
									FIO VARCHAR(100),
									POST_NAME VARCHAR(254),
									SUBDIV_NAME VARCHAR(254),
									[POSTGROUP]		VARCHAR(60),
									KATEG VARCHAR(50))
INSERT INTO @KU_EMPL_PLACING_FN(	LINK,	PERS_LINK,	FIO,	POST_NAME,	SUBDIV_NAME,[POSTGROUP],KATEG)
SELECT	LINK,	PERS_LINK,	FIO,	ISNULL(POST_NAME,''),	ISNULL(SUBDIV_NAME,''), RTRIM(POST_GROUP),KATEG
FROM	DBO.KU_EMPL_PLACING_FN(@DATE_CHIN)
WHERE	LINK = @EMPL_LINK
-----------------------------------------------------------------------------------

-- Сведения о новом классном чине -------------------------------------------------------
DECLARE @NEW_EMPL_CHIN TABLE(	LINK INT, 
							EMPL_LINK INT, 
							DATE DATETIME, 
							CHIN_NAME VARCHAR(150), 
							ATT_KOM_LINK INT)
INSERT INTO @NEW_EMPL_CHIN(LINK, EMPL_LINK, DATE, CHIN_NAME, ATT_KOM_LINK)
SELECT LINK, EMPL_LINK, DATE, CHIN_NAME, ATT_KOM_LINK
FROM KU_EMPL_CHIN
WHERE LINK = @nSel_Spr1
-----------------------------------------------------------------------------------

-- Сведения о проф.переподготовке и пов.квалификации ------------------------------
DECLARE @PROF_KV VARCHAR(2000)
SET @PROF_KV = RTRIM(DBO.GetProfKvalToEmpl_More(@EMPL_LINK))
-----------------------------------------------------------------------------------

-- Дата назначения на должность ------------------------------------------------------
DECLARE @DATE_BEGIN DATETIME
SET @DATE_BEGIN = (	SELECT	TOP 1 IM.DATE_BEGIN
					FROM	ITEM_MOVE IM
					WHERE	IM.EMPL_LINK = @EMPL_LINK AND (IM.NEW_FACE = 0 OR IM.NEW_FACE = 1) AND IM.ACTIVE = 1 AND IM.DATE_BEGIN <= @DATE_CHIN
					ORDER BY IM.DATE_BEGIN DESC)
-----------------------------------------------------------------------------------

-- Сведения об ученой степени. ученом звании --------------------------------------
DECLARE @UCH TABLE (LINK INT, [UCH_ST] VARCHAR(50),[UCH_ZV] VARCHAR(50))
INSERT INTO @UCH (LINK,[UCH_ST],[UCH_ZV])
SELECT PERS_LINK,RTRIM(LTRIM(ACAD_DEGREE_NAME)),RTRIM(LTRIM(ACAD_STATUS_NAME))
FROM KU_PERSON KP inner join @KU_EMPL_PLACING_FN KE ON KP.LINK = KE.PERS_LINK
-----------------------------------------------------------------------------------

DECLARE @CUR_EMPL_CHIN TABLE (EMPL_LINK INT, CHIN_NAME VARCHAR(254), DATE DATETIME)
INSERT INTO @CUR_EMPL_CHIN (EMPL_LINK, CHIN_NAME, DATE)
SELECT TOP 1 EMPL_LINK, CHIN_NAME, DATE
FROM KU_EMPL_CHIN WHERE DATE = (SELECT TOP 1 DATE
								FROM KU_EMPL_CHIN
								WHERE DATE < @DATE_CHIN AND EMPL_LINK = @EMPL_LINK
								ORDER BY DATE DESC)	AND EMPL_LINK = @EMPL_LINK 

-- Сведения об образовании ----------------------------------------------------------
--DECLARE @UCH_ZAV VARCHAR(3000)
--SET @UCH_ZAV = RTRIM(DBO.KJ_GET_EDUC_EMPL(@EMPL_LINK))

DECLARE @EDUC_NAME		VARCHAR(80),	-- Тип образования
		@SPEC_NAME		VARCHAR(254)	-- Специальность
SELECT @EDUC_NAME = EDUC_NAME, @SPEC_NAME = SPEC_NAME
FROM KU_PERS_EDUCATION INNER JOIN @UCH U ON  KU_PERS_EDUCATION.PERS_LINK = U.LINK --@nSel_Spr1

-- Сведения об общем стаже, стаже госслужбы ------------------------------------------
DECLARE @OBW_EXPIR VARCHAR(20), @GS_EXPIR VARCHAR(20)
IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN) <=0 ) 
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN) >0) 
		SET @OBW_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN)) + 'мес.'

IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN) > 0 )  
BEGIN
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN) <= 0) 	
		SET @OBW_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN))
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN) > 0) 
		SET @OBW_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN)) + 'г. '+CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN))+'мес.'--CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN)) + 'г. '+CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GEN',@DATE_CHIN))+'мес.'
END


IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN) <=0 ) 
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN) >0) 
		SET @GS_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN)) + 'мес.'

IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN) > 0 )  
BEGIN
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN) <= 0) 	
		SET @GS_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN))
	IF (dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN) > 0) 
		SET @GS_EXPIR = CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN)) + 'г. '+CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN))+'мес.'--CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN)) + 'г. '+CONVERT(VARCHAR(3),dbo.ku_GetEmplExpir(@EMPL_LINK,'MONTH','GOS_NADB',@DATE_CHIN))+'мес.'
END

-----------------------------------------------------------------------------------
INSERT INTO @RESULT ([FIO],[POST],[SUBDIV],[PROF_KV],[UCH_ST],[UCH_ZV],
					 [DATE_BEGIN],[CHIN_PR],[DATE],[KLAS_CHIN],[DATE_CHIN],[POSTGROUP],KATEG,
					 [EDUC_NAME], [SPEC_NAME], [OBW_EXPIR],[GS_EXPIR]	)
SELECT 	
	[FIO]			= KEP.FIO,				-- ФИО
	[POST]			= KEP.POST_NAME,		-- Должность
	[SUBDIV]		= KEP.SUBDIV_NAME,		-- Подразделение
	[PROF_KV]		= @PROF_KV,				-- Сведения о проф.переподготовке и пов.квалификации
	[UCH_ST]		= UCH.UCH_ST,			-- Ученая степень
	[UCH_ZV]		= UCH.UCH_ZV,			-- Ученое звание	
	[DATE_BEGIN]	= @DATE_BEGIN,			-- Дата назначения на должность					
	[CHIN_PR]		= NEC.CHIN_NAME,		-- Новый классный чин	
	[DATE]			= NEC.DATE,				-- Дата присвоения нового чина
	[KLAS_CHIN]		= CEC.CHIN_NAME,		-- Текущий классный чин
	[DATE_CHIN]		= CEC.DATE,				-- Дата присвоения текущего чина		
	[POSTGROUP]		= KEP.POSTGROUP,
	[KATEG]			= KEP.KATEG,
	[EDUC_NAME]		= @EDUC_NAME,
	[SPEC_NAME]		= @SPEC_NAME,
	[OBW_EXPIR]		= @OBW_EXPIR,
	[GS_EXPIR]		= @GS_EXPIR
FROM	@NEW_EMPL_CHIN			NEC		LEFT JOIN 
		@KU_EMPL_PLACING_FN		KEP		ON NEC.EMPL_LINK = KEP.LINK LEFT JOIN 				
        @UCH					UCH		ON UCH.LINK = KEP.PERS_LINK LEFT JOIN
		@CUR_EMPL_CHIN			CEC     ON CEC.EMPL_LINK = KEP.LINK 
SELECT * FROM @RESULT


GO


GRANT EXECUTE ON dbo.[KO_REP_ASSIGNMENT_CLASS_CHIN] 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_KS_RANG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_KS_RANG]
GO




/*
© Кейсистемс (Keysystems), 2012
*/
CREATE  PROCEDURE dbo.RO_KS_RANG
	@varKStOrderTable    TINYINT,
   @varKSiOrderCol      INT,
   @varKSvcCode         VARCHAR(50),   
	@varKSiLSF	int
AS
	declare @val numeric(18, 2)
   

   SELECT @val = float_val
   FROM #report_dinamics rd 
         JOIN dbo.report_coloumns rc ON rd.link_col = rc.link_col
         JOIN dbo.report_tables rt ON rc.link_table = rt.link_table
   WHERE rt.orders = @varKStOrderTable AND   rc.orders = @varKSiOrderCol
         AND rd.Code_Row = @varKSvcCode
         
   SELECT @val = COUNT(*) + 1
   FROM #report_dinamics rd 
         JOIN dbo.report_coloumns rc ON rd.link_col = rc.link_col
         JOIN dbo.report_tables rt ON rc.link_table = rt.link_table
   WHERE rt.orders = @varKStOrderTable AND   rc.orders = @varKSiOrderCol
         AND float_val > @val
   

	select isnull(@val, 0)



GO
GRANT ALL ON [dbo].[RO_KS_RANG] 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].[RO_KBK_TREE_MOVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_KBK_TREE_MOVE]
GO





/*
© Кейсистемс (Keysystems), 2006
*/

CREATE  PROCEDURE dbo.RO_KBK_TREE_MOVE
	@varKSLINK int,
	@varKSlink_target int,
	@varKSmovemode int,
	@varKSListNodes varchar(8000) = ''
AS
	DECLARE @link_self int, @ORDER int, @count INT, @vcCodeForm VARCHAR(50)

	SET @ORDER = 1
	SET @link_self = NULL
   
   if @varKSLINK = @varKSlink_target
      return -1      

	IF @varKSmovemode=0 BEGIN -- поместить после узла
		SELECT @link_self = link_self FROM report_kbk WHERE link=@varKSlink_target
		SELECT @ORDER = isnull(orders, 0)+1 FROM report_kbk WHERE link=@varKSlink_target
	END
	ELSE BEGIN -- поместить под узлом
		SET @link_self = @varKSlink_target
		SET @ORDER = 1
	END

	DECLARE @varKStrancount int, @varKSERROR int

	set @count = case when isnull(@varKSLINK,0) = 0 then dbo.RA_GETWORDCOUNT(@varKSListNodes, ',') - 2 else 1 end

	IF exists(SELECT * FROM report_kbk WHERE orders=@ORDER and Link_Self = @Link_Self)
	begin
			UPDATE report_kbk SET orders=orders+@count WHERE link in 
				(SELECT link FROM report_kbk WHERE orders>=@ORDER and Link_Self = @Link_Self)
	end

	if isnull(@varKSLINK,0) = 0
		UPDATE report_kbk SET link_self=@link_self, orders=@ORDER + orders WHERE CHARINDEX(',' + LTRIM(RTRIM(STR(link))) + ',', @varKSListNodes) > 0
	else
		UPDATE report_kbk SET link_self=@link_self, orders=@ORDER WHERE link=@varKSLINK

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @varKSLINK
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @varKSlink_target


GO
GRANT ALL ON dbo.[RO_KBK_TREE_MOVE] 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].[RO_ADD_NOTE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_ADD_NOTE]
GO

/*
© Кейсистемс (Keysystems), 2012
*/


CREATE                       procedure dbo.RO_ADD_NOTE
	@varKSiLSF	int,
	@varKSNote	varchar(8000) = ''
AS
  
   IF ISNULL(@varKSNote, '') <> ''
   BEGIN 
      INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
      VALUES (@varKSiLSF, SUSER_SID(), @varKSNote)
   END 

RETURN 0

GO
GRANT ALL ON dbo.[RO_ADD_NOTE] 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.[SD_REP_T54]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_T54]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.SD_REP_T54
	@varKScYear VARCHAR(4),
	@varKSnMode SMALLINT,
	@varKSnLinkEmpl INT
AS BEGIN

	DECLARE @varKSnYear 	   INT,
            @varKSnLinkPers INT

	SET @varKSnYear = CAST(@varKScYear AS INT)
	SELECT @varKSnLinkPers = PERS_LINK FROM EMPL WHERE LINK = @varKSnLinkEmpl

	DECLARE @varKSstart_date DATETIME, @varKSEND_DATE DATETIME
	SELECT @varKSstart_date = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	SELECT @varKSEND_DATE  = dbo.DateEndOfYear(@varKSstart_date)

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output
	
	CREATE TABLE #PART1 (SUBDIV VARCHAR(254), 
		DOC_BEGIN DATETIME, DOC_END DATETIME,
		TAB_NUM VARCHAR(15), CATEG VARCHAR(254), 
		INN VARCHAR(20), CODE_SPU VARCHAR(20), 
		KLADR VARCHAR(20), 
		SEMPOL VARCHAR(254), children int, 
		START_DATE DATETIME, DISCH_DATE DATETIME, 
		FIO VARCHAR(254), BIRTH_DATE DATETIME
	)

	INSERT INTO #PART1
	SELECT 
		TOP 1 
		[SUBDIV] 	= EP.SUBDIV_NAME,
		[DOC_BEGIN] = @varKSstart_date,
		[DOC_END] 	= @varKSEND_DATE,
		[tab_num]	= EP.TAB,
		[KATEG] 	= EP.STATUS_NAME,
		[INN] 		= P.INN,
		[CODE_SPU] 	= P.INSUR_NUM,
		[KLADR] 	= '',
		[SEMPOL] 	= (SELECT NAME FROM MARRIAGE WHERE LINK = P.MAR_LINK),
		[CHILDREN] = (SELECT COUNT(*) FROM KU_PERS_FAMILY 
					WHERE PERS_LINK = @varKSnLinkPers
				AND FAMILY_NAME IN ('Сын', 'Дочь', 'Пасынок', 'Падчерица')
				and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@varKSnYear)) <18),
		[START_DATE] = convert(DATETIME, E.DATE_BEGIN, 104),
		[DISCH_DATE] = CONVERT(DATETIME, E.DATE_END, 104),
		[FIO] = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
		[BIRTH_DATE] = P.BIRTHDATE
	FROM dbo.KU_EMPL_PLACING EP  
		INNER JOIN dbo.PERSON P ON (EP.PERS_LINK = P.LINK)
		INNER JOIN dbo.SD_EMPL E ON EP.LINK = E.LINK
	WHERE EP.LINK = @varKSnLinkEmpl 

	CREATE TABLE #TMP2 ( ORDER_DATE datetime, ORDER_NUM VARCHAR(15), 
		SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
		KATEG VARCHAR(254), OKLAD NUMERIC(20,2), ADD_PAY NUMERIC(20,2), REAL_REC BIT
	)
	
	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		REAL_REC)
	SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
	FROM DICTIONARY_PURP_DISP_FACES 
	WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) = @varKSnYear
	ORDER BY DATE_PD DESC

	
	INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		REAL_REC)
	SELECT DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
	FROM DICTIONARY_PURP_DISP_FACES 
	WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) = @varKSnYear	
	ORDER BY DATE_PD DESC


	CREATE TABLE #TMP_3 ( 
		ORD_DATE DATETIME,	ORD_NUM VARCHAR(15),
		VAC_TYPE VARCHAR(254),
		PERIOD_B DATETIME,	PERIOD_E DATETIME,
		VAC_BEG DATETIME,	VAC_END DATETIME,
		DAYS VARCHAR(254),
		REAL_REC BIT
		)

	INSERT INTO #TMP_3
	(
		ORD_DATE, ORD_NUM, 
		VAC_TYPE,
		PERIOD_B, PERIOD_E,
		VAC_BEG, VAC_END,
		DAYS, REAL_REC
	)
	SELECT 
		DATE, NUMBER,
		TYPE_NAME,
		PERIOD_BEGIN, PERIOD_END,
		DATE_BEGIN, DATE_END,
		dbo.W_DAYS(7, DATE_BEGIN, DATE_END),
		1
	FROM VACATION
	WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR([DATE_BEGIN]) = @varKSnYear
	
	CREATE TABLE #TMP_DED (ID INT IDENTITY, link_tax int, NAME_TAX VARCHAR(254), DATE1 DATETIME, DATE2 DATETIME, 
		SUMMA_PROC NUMERIC(20,2), SUMMA NUMERIC(20, 2), REAL_REC BIT )

	INSERT INTO #TMP_DED (link_tax, NAME_TAX, DATE1, DATE2, SUMMA_PROC, SUMMA, REAL_REC)
		SELECT link_tax, NAME_TAX, DATE1, DATE2, SUMMA, 0, 1
		FROM SD_EMPL_TAX ET
		WHERE ET.LINK_EMPL = @varKSnLinkEmpl AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date) AND (DATE1 <= @varKSEND_DATE)


	CREATE TABLE #VICHETS (
		LINK INT, CODE VARCHAR(3), SUMMA NUMERIC(20,2), 
		DATE1 DATETIME, DATE2 DATETIME, REAL_REC BIT )
	INSERT INTO #VICHETS
	SELECT DTD.LINK, DTD.SNAME, DTD.SUMMA, DATE1, DATE2, 1 
	FROM SD_EMPL_DED ED, DICTIONARY_TYP_DEDUCTION DTD
	WHERE ED.LINK = @varKSnLinkEmpl 	AND DTD.LINK = ED.LINK_DED 
		AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date)
		AND (DATE1 <= @varKSEND_DATE)



	DECLARE @varKSCOUNT_1 INT, @varKSTMP_INT INT, 
		@varKSCOUNT_2 INT, @varKSCOUNT_3 INT, @varKSCOUNT_4 INT, @varKSCOUNT_MAX INT, @varKSDELTA INT
	SET @varKSCOUNT_1 = (SELECT COUNT(*) FROM #TMP2)
	SET @varKSCOUNT_MAX = @varKSCOUNT_1
	SET @varKSCOUNT_2 = (SELECT COUNT(*) FROM #TMP_3)
	IF @varKSCOUNT_MAX < @varKSCOUNT_2 SET @varKSCOUNT_MAX = @varKSCOUNT_2
	SET @varKSCOUNT_3 = (SELECT COUNT(*) FROM #TMP_DED)
	IF @varKSCOUNT_MAX < @varKSCOUNT_3 SET @varKSCOUNT_MAX = @varKSCOUNT_3
	SET @varKSCOUNT_4 = (SELECT COUNT(*) FROM #VICHETS)
	IF @varKSCOUNT_MAX =0 SET @varKSCOUNT_MAX = 1
	IF @varKSCOUNT_MAX < @varKSCOUNT_4 SET @varKSCOUNT_MAX = @varKSCOUNT_4
	SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_1
	SET @varKSTMP_INT=1
	WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
		INSERT INTO #TMP2 (REAL_REC) VALUES(0)
		SET @varKSTMP_INT=@varKSTMP_INT+1
	END
	SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_2
	SET @varKSTMP_INT=1
	WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
		INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		SET @varKSTMP_INT=@varKSTMP_INT+1
	END

	IF @varKSnMode=1 BEGIN  
		SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_3
		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
			INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END
	END
	SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_4
	SET @varKSTMP_INT=1
	WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
		INSERT INTO #VICHETS (REAL_REC) VALUES(0)
		SET @varKSTMP_INT=@varKSTMP_INT+1
	END


	IF @varKSnMode=1 BEGIN	
	--- begin #3700 13.12.2011	Шорков И.А.  Изменение алгоритма выборки отработанных дней и часов	
		CREATE TABLE #DAYSHOURS(MONTH0 INT, C VARCHAR(3), D INT, H NUMERIC(8,2) )
		INSERT INTO #DAYSHOURS
		SELECT MONTH(T.PERIOD), 
			   TD.SYMB, 
			   (dbo.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,MONTH(T.PERIOD),year(T.PERIOD)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(T.PERIOD),year(T.PERIOD))), DEFAULT, 0)) as DAYS, 
			   (dbo.SA_GET_EMPL_WH (T.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,MONTH(T.PERIOD),year(T.PERIOD)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(T.PERIOD),year(T.PERIOD))), DEFAULT, 0)) AS HOURS
		FROM DBO.TABELS T , DBO.TYP_DAYS TD ,DBO.TABELS_W W left join (
				Select DISTINCT G.LINK, GT.TYPE_DAY from dbo.GRAPH G inner join dbo.GRAPH_VID_TABLE GT on G.VID_LINK = GT.LINK_UP
			) EG on (SELECT GRAPH_LINK FROM DBO.EMPL E WHERE e.LINK = @varKSnYear) = EG.LINK and EG.TYPE_DAY = W.link_day
		WHERE 
			T.LINK_EMPL =  @varKSnLinkEmpl
			AND T.LINK = W.LINK_UP 
			AND  td.link = W.link_day
			AND TD.WORK_D < 4
			and TD.DOP_TAB = 1
			AND YEAR(T.PERIOD) = @varKSnYear
			AND
			(
				EG.TYPE_DAY is not null
				OR
				W.link_day in (Select LINK from dbo.TYP_DAYS WHERE DOP_TAB = 1)
			)
		GROUP BY T.PERIOD, T.LINK_EMPL , TD.SYMB
	--- end #3700 

		CREATE TABLE #TMP_N1 (MONTH1 INT, CN VARCHAR(10), NN VARCHAR(254), SM NUMERIC(20,2), SM_ALL NUMERIC(20,2))
	
		INSERT INTO #TMP_N1
		SELECT MONTH_BEGIN, CODE_PAYS, NAME_PAYS, SUMMA, 0
		FROM S_J_C_Short SJC 
		WHERE 
			SJC.LINK_EMPL = @varKSnLinkEmpl
			AND YEAR_BEGIN = @varKSnYear
			AND TYP_OPER = 1 AND WAY_CALC NOT IN(13, 14)
			AND SJC.LINK_DEP = @DEP_LINK 

----- begin #3695 Шорков И.А. 13.12.2011  исправление алгоритма для выборки пособий по уходу за ребенком
		/* #3696 исправление отображения количества дней нетрудоспособности*/

		CREATE TABLE #TAB2 (REF_ARHE INT, MAX_LINK INT)

		--Последний расчёт каждого больничного, чтобы выйти на больничный
		INSERT INTO #TAB2(REF_ARHE, MAX_LINK)
		SELECT SD.REF_DOC, MAX(S.LINK)
		FROM
			dbo.SDOC S 
			INNER JOIN dbo.SDOC_ADIS SD ON S.LINK = SD.LINK_UP
		WHERE
			 S.FLAG_JC = 1 AND SD.LINK_EMPL = @varKSnLinkEmpl		
		GROUP BY
			SD.REF_DOC			 

		--Для последнего расчёта каждого больничного количество дней из больничного
		CREATE TABLE #ST2 (LINK_UP INT, [DAYS] NUMERIC(18,2))
		INSERT INTO #ST2 (LINK_UP, [DAYS])
		SELECT T1.LINK_UP, [DAYS] = MAX(T1.[DAYS]) 
		FROM 
			[dbo].[SDOC] D 
			INNER JOIN dbo.SDOC_ADIS A ON D.LINK = A.LINK_UP
			INNER JOIN dbo.SDOC_ADIS_TABLE1 T1 ON D.LINK = T1.LINK_UP 
		WHERE 
			A.LINK_EMPL = @varKSnLinkEmpl
		GROUP BY 
			T1.LINK_UP
			
		--
		CREATE TABLE #TAB3 (LINK INT, [DAYS] NUMERIC(18,2))
		INSERT INTO #TAB3 (LINK, [DAYS])
		SELECT S.LINK, SUM(ST2.[DAYS])
		FROM
			dbo.SDOC S 
			INNER JOIN dbo.SDOC_ADIS SD ON S.LINK = SD.LINK_UP
			INNER JOIN #TAB2 DA3 ON DA3.REF_ARHE = SD.REF_DOC
			INNER JOIN #ST2 ST2 ON S.LINK = ST2.LINK_UP
		WHERE
			S.FLAG_JC = 1 AND SD.LINK_EMPL = @varKSnLinkEmpl		 
		GROUP BY 
			S.LINK


		CREATE TABLE #TMP_N2 (MONTH2 INT, CN2 VARCHAR(10), NN2 VARCHAR(254), SM2 NUMERIC(20,2), DAY2 INT, SM_ALL2 NUMERIC(20,2) )
		INSERT INTO #TMP_N2
		SELECT SJC.MONTH_BEGIN, SJC.CODE_PAYS, SJC.NAME_PAYS, SUM(SJC.SUMMA) ,
			[days] = SUM(T3.[DAYS]),
			0
		FROM 
			dbo.S_J_C_Short SJC
			LEFT JOIN #TAB3 T3 ON SJC.LINK_DOC = T3.LINK --Дни больничного определяем по последнему расчёту
		WHERE 
			 SJC.LINK_EMPL = @varKSnLinkEmpl
			AND SJC.YEAR_BEGIN = @varKSnYear
			AND SJC.TYP_OPER = 1
			AND SJC.WAY_CALC IN(13, 14)
			AND SJC.LINK_DEP = @DEP_LINK 
		GROUP BY 
			SJC.MONTH_BEGIN, SJC.LINK_DOC, SJC.CODE_PAYS, SJC.NAME_PAYS , SJC.WAY_CALC
----- end #3695


		CREATE TABLE #TMP_U (MONTH3 INT, CU VARCHAR(10), NU VARCHAR(254), SU NUMERIC(20,2),  SM_ALL3 NUMERIC(20,2) )
		INSERT INTO #TMP_U
		SELECT MONTH_BEGIN, CODE_PAYS, NAME_PAYS, SUMMA, 0
		FROM S_J_C_Short SJC 
		WHERE 
			SJC.LINK_EMPL = @varKSnLinkEmpl
			AND YEAR_BEGIN = @varKSnYear
			AND TYP_OPER = 2
			AND SJC.LINK_DEP = @DEP_LINK 
	
		DECLARE @varKSTMP_TABLE VARCHAR(100)
		EXEC X_GET_TABLE_NAME @varKSTMP_TABLE OUTPUT
		DECLARE @varKSTABLE_NAME_N1 VARCHAR(120), @varKSTABLE_NAME_N2 VARCHAR(120), @varKSTABLE_NAME_U1 VARCHAR(120),
			@varKSDAYSHOURS VARCHAR(120)
		SET @varKSTABLE_NAME_N1 = @varKSTMP_TABLE + '_N1'
		SET @varKSTABLE_NAME_N2 = @varKSTMP_TABLE + '_N2'
		SET @varKSTABLE_NAME_U1 = @varKSTMP_TABLE + '_U1'
		SET @varKSDAYSHOURS = @varKSTMP_TABLE + '_D'
		
		EXEC M_CROSS_TABLE 'MONTH1, SM_ALL', 'NN,CN', 'VARCHAR(254)#VARCHAR(10)', 'SM', 'NUMERIC(20,2)', 'SUM(SM)  AS SM', '#TMP_N1', @varKSTABLE_NAME_N1 
		EXEC M_CROSS_TABLE 'MONTH2, SM_ALL2', 'CN2', 'VARCHAR(10)', 'SM2,DAY2', 'NUMERIC(20,2)#INT', 'SUM(SM2)  AS SM2,SUM(DAY2) AS DAY2', '#TMP_N2', @varKSTABLE_NAME_N2 
		EXEC M_CROSS_TABLE 'MONTH3, SM_ALL3', 'NU,CU', 'VARCHAR(254)#VARCHAR(10)', 'SU', 'NUMERIC(20,2)', 'SUM(SU)  AS SU', '#TMP_U', @varKSTABLE_NAME_U1 
		EXEC M_CROSS_TABLE 'MONTH0', 'C', 'VARCHAR(3)', 'D,H', 'INT#NUMERIC(8,2)', 'SUM(D) AS D,SUM(H) AS H', '#DAYSHOURS', @varKSDAYSHOURS
		
			
		EXEC  ( 'UPDATE ' + @varKSTABLE_NAME_N1 + '  SET SM_ALL = (SELECT SUM(SM) FROM #TMP_N1 WHERE MONTH1 = T1.MONTH1) FROM ' + @varKSTABLE_NAME_N1 + '  T1 ' )
		EXEC  ( 'UPDATE ' + @varKSTABLE_NAME_N2 + '  SET SM_ALL2 = (SELECT SUM(SM2) FROM #TMP_N2 WHERE MONTH2 = T1.MONTH2) FROM ' + @varKSTABLE_NAME_N2 + '  T1 ' )
		EXEC  ( 'UPDATE ' + @varKSTABLE_NAME_U1 + '  SET SM_ALL3 = (SELECT SUM(SU) FROM #TMP_U WHERE MONTH3 = T1.MONTH3) FROM ' + @varKSTABLE_NAME_U1 + '  T1 ' )




		DECLARE @varKSTABLE_NAME_R1 VARCHAR(120)
		SET @varKSTABLE_NAME_R1 = @varKSTMP_TABLE + '_R1'
		EXEC ( '
			SELECT M1.*, T1.*, T2.*, T3.*, T4.* 
			INTO ' + @varKSTABLE_NAME_R1 + '
			FROM MONTHS M1 FULL OUTER JOIN ' + @varKSDAYSHOURS + ' T1 ON M1.NUM = MONTH0
			FULL OUTER JOIN ' + @varKSTABLE_NAME_N1 + '  T2 ON M1.NUM = MONTH1
			FULL OUTER JOIN ' + @varKSTABLE_NAME_N2 + '  T3 ON M1.NUM = MONTH2
			FULL OUTER JOIN ' + @varKSTABLE_NAME_U1 + '  T4 ON M1.NUM = MONTH3 ' )


			
		DECLARE @varKSCOUNT_N1 INT, @varKSCOUNT_N2 INT, @varKSCOUNT_U INT, @varKSCOUNT_D INT, @varKSSQL_STR VARCHAR(8000)
		DECLARE @varKSFIELD_NAME VARCHAR(100)
		SELECT @varKSCOUNT_N1=COUNT(DISTINCT(CN)) FROM #TMP_N1
		SELECT @varKSCOUNT_N2=COUNT(DISTINCT(CN2)) FROM #TMP_N2
		SELECT @varKSCOUNT_U=COUNT(DISTINCT(NU)) FROM #TMP_U
		SELECT @varKSCOUNT_D=COUNT(DISTINCT(C)) FROM #DAYSHOURS

		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT <= @varKSCOUNT_N1 BEGIN
			SET @varKSFIELD_NAME= 'NN_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTABLE_NAME_N1 + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSFIELD_NAME= 'CN_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) +'_'+RTRIM(LTRIM(STR(@varKSTMP_INT)))
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTABLE_NAME_N1 + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END
		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT<=@varKSCOUNT_N2 BEGIN
			SET @varKSFIELD_NAME= 'CN2_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTABLE_NAME_N2 + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END
		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT<=@varKSCOUNT_U BEGIN
			SET @varKSFIELD_NAME= 'NU_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTABLE_NAME_U1 + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSFIELD_NAME= 'CU_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) +'_'+RTRIM(LTRIM(STR(@varKSTMP_INT)))
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSTABLE_NAME_U1 + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END
		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT <= @varKSCOUNT_D BEGIN
			SET @varKSFIELD_NAME= 'C_' + RTRIM(LTRIM(STR(@varKSTMP_INT))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTABLE_NAME_R1+'  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME+' FROM ' +@varKSDAYSHOURS + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END


		
		IF @varKSCOUNT_N1=0 BEGIN
			EXEC (' ALTER TABLE '+@varKSTABLE_NAME_R1+' ADD CN_0_0 VARCHAR(10), NN_0 VARCHAR(254), SM_0_0 MONEY ')
		END
		IF @varKSCOUNT_N2=0 BEGIN
			EXEC (' ALTER TABLE '+@varKSTABLE_NAME_R1+' ADD CN2_0 VARCHAR(10),  SM2_0 MONEY, DAY2_0 INT ')
		END	
		IF @varKSCOUNT_U=0 BEGIN
			EXEC (' ALTER TABLE '+@varKSTABLE_NAME_R1+' ADD NU_0 VARCHAR(10), CU_0_0 VARCHAR(254), SU_0_0 MONEY ')
		END
		IF @varKSCOUNT_D=0 BEGIN
			EXEC (' ALTER TABLE '+@varKSTABLE_NAME_R1+' ADD C_0 VARCHAR(3), D_0 INT, H_0 NUMERIC(8,2) ')
		END
		IF @varKSCOUNT_N1 = 0 AND @varKSCOUNT_N2 = 0 AND @varKSCOUNT_U = 0 BEGIN
			EXEC('INSERT INTO ' + @varKSTABLE_NAME_R1 + ' (SM_0_0 ) VALUES (0) ' )
		END

		EXEC ('DROP TABLE ' +	@varKSTABLE_NAME_N1)
		EXEC ('DROP TABLE ' +	@varKSTABLE_NAME_N2)
		EXEC ('DROP TABLE ' +	@varKSTABLE_NAME_U1)
		EXEC ('DROP TABLE ' +	@varKSDAYSHOURS)
	END



	SELECT * FROM #PART1
	SELECT * FROM #TMP2 ORDER BY REAL_REC DESC, ORDER_DATE ASC
	SELECT * FROM #TMP_3 ORDER BY REAL_REC DESC, ORD_DATE
	IF @varKSnMode=1
		SELECT * FROM #TMP_DED ORDER BY REAL_REC DESC

	ELSE BEGIN
		IF @varKSCOUNT_3 <=3 BEGIN
			SELECT * FROM #TMP_DED ORDER BY REAL_REC DESC
			SELECT * FROM #TMP_DED WHERE 1<0
		END
		ELSE BEGIN
			SELECT * FROM #TMP_DED WHERE ID <=@varKSCOUNT_3/2 ORDER BY REAL_REC DESC
			SELECT * FROM #TMP_DED WHERE ID >@varKSCOUNT_3/2   ORDER BY REAL_REC DESC
		END
	END

	SELECT MONTH(DATE1), *, 
		'Вычет: ' + rtrim(code) + char(10) 
		+ convert(varchar(10), date1, 104) + ' - ' + convert(varchar(10), date2, 104)
		+ char(10) + cast(summa as varchar(15) ) as sum_ded
	FROM #VICHETS ORDER BY REAL_REC DESC, 1, date2

	IF @varKSnMode=1 BEGIN
		EXEC ( 'SELECT * FROM '  + @varKSTABLE_NAME_R1 + ' ORDER BY NUM ')

		EXEC ('DROP TABLE ' +	@varKSTABLE_NAME_R1)
	END
	
	if object_id('tempdb..#TAB2') is NOT NULL
		EXECUTE ('DROP TABLE #TAB2')

	if object_id('tempdb..#TAB3') is NOT NULL
		EXECUTE ('DROP TABLE #TAB3')

END







GO


GRANT EXECUTE ON dbo.[SD_REP_T54] TO PUBLIC

GO

GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_ZAYAVKA_KR_CREATE_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_ZAYAVKA_KR_CREATE_TABLE]
GO

CREATE PROCEDURE [dbo].[BB_ZAYAVKA_KR_CREATE_TABLE] @iLinkDoc		int

AS
Declare	@iERROR		int,
		@iRowCount	int,
		@iTrancount	int
	
SET @iTrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
IF @iLinkDoc is null OR @iLinkDoc = 0
	return -1


delete from dbo.ZAYAVKA_KR_TABLE where LINK_UP = @iLinkDoc

INSERT INTO dbo.ZAYAVKA_KR_TABLE(LINK_UP, [SOURCE], LINK_KBK, LINK_SGU, LINK_DT_ACC, LINK_KBK_D, LINK_SGU_D, SUMMA, TARGET, TITLE)
select @iLinkDoc, S.Link, KGAP.KBK, KGAP.EKR, DGAP.ACCOUNT, case when DSA.LINK is null then null else DGAP.KBK end, case when DSA.LINK is null then null else DGAP.EKR end, G2.SUMMA,'',''
from dbo.G_PROV1 G1
inner join dbo.G_PROV2 G2 on G1.LINK = G2.LINK_UP
inner join dbo.G_PROV_AP KGAP on G2.LINK = KGAP.LINK_UP and KGAP.DB_KR = 1
inner join dbo.S_ACCOUNTS KSA on KSA.LINK = KGAP.ACCOUNT and (KSA.cSINTH = '304' and KSA.cAnalit = '05' or KSA.cSINTH = '201' and KSA.cAnalit = '01')
inner join dbo.G_PROV_AP DGAP on G2.LINK = DGAP.LINK_UP and DGAP.DB_KR = 0
inner join dbo.BB_FIN_SOURCE S on S.CODE = KSA.cSource
left join dbo.S_ACCOUNTS DSA on DSA.LINK = DGAP.ACCOUNT and (KSA.cSINTH = '304' and KSA.cAnalit = '04' or KSA.cSINTH = '302' and KSA.cAnalit in ('10','11','12','13'))
where G1.LINK_UP = @iLinkDoc

SELECT @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
	ROLLBACK
	RETURN 7
END

IF @@TRANCOUNT > @iTrancount
	COMMIT TRAN
RETURN 0
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_VP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_VP]
GO


CREATE                    PROCEDURE dbo.BB_EXPORT_VP
	@cBuffId	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS

DECLARE @iDepLink	int
set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())

-- Таблица 2 (FROM)
SELECT 0 as link,
		0 as link_up,
		KOD_TOFK  = '0000',
		NAME_TOFK = space(2000)

-- Таблица 3 (TO)
SELECT 	0 as link,
		0 as link_up,
		-- Поля для приема выписки
		BUDG_LEVEL  = '0',
		KOD_UBP 	= '00000',
		NAME_UBP	= space(2000)



-- Таблица 4 (PP)
SELECT  LINK 	= 0,
		LINK_UP	= 0,
		LS = space(11),
		[DATE]	= convert(datetime,'20000101',104),
		GUID_FK = space(36)

SELECT  LINK 		= 0,
		LINK_UP		= 0,
		NUM_DOC		= space(15),
		DATE_DOC	= convert(datetime,'20000101',104),
		GUID		= space(36),
		NUM_DOC_UBP = space(15),
		DATE_DOC_UBP= convert(datetime,'20000101',104),
		SUM_OUT	= convert(numeric(18,2),0)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on BB_EXPORT_VP to public
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_86N_002]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_86N_002]
END
GO
 
/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_86N_002]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @iReturn INT 

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

-- создание временных табличек
CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                        ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета

CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении

CREATE TABLE #tab002
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT         -- Текущий финансовый год
   ,[nextFinancialYear] INT      -- Очередной финансовый год
   ,[planFirstYear] INT          --Первый год планового периода
   ,[planLastYear] INT        --Второй год планового периода
)
-- Услуги
CREATE TABLE #tab002_SERVICE
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код услуги
   ,[NUM_UTV] VARCHAR(200) -- Номер (код) по утвержденному перечню услуг 
   ,[NUM]   VARCHAR(50)    -- Порядковый номер раздела, соответствующий услуге
   ,[NAME]  VARCHAR(1000)  -- Наименование услуги, указанной в данном разделе
   ,[KAT]   VARCHAR(1000)  -- Категория потребителей (наименование)   
)
-- Показатели качества услуг 
CREATE TABLE #tab002_QUALITY
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[NAME]     VARCHAR(8000)  -- Наименование показателя качества услуги  
   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                                  
   ,[EI_SYMBOL] VARCHAR(1000)  -- Единица измерения (symbol ОКЕИ)                               
   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя качества услуги за отчетный финансовый год
   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя качества услуги на текущий финансовый год 
   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя качества услуги на очередной финансовый год  
   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя качества услуги на первый год планового периода  
   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя качества услуги на второй год планового периода
   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя качества услуги за текущий финансовый
   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя качества 
)
-- Показатели объема услуги
CREATE TABLE #tab002_VOLUME
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[NAME]     VARCHAR(8000)  -- Наименование показателя объема услуги   
   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
   ,[EI_SYMBOL] VARCHAR(1000)  -- Единица измерения (symbol ОКЕИ)                               
   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя объема услуги за отчетный финансовый год
   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя объема услуги на текущий финансовый год 
   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя объема услуги на очередной финансовый год  
   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя объема услуги на первый год планового периода  
   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя объема услуги на второй год планового периода
   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя объема услуги за текущий финансовый
   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя объема 
)
-- Возможность взимания платы за услугу
CREATE TABLE #tab002_PRICE
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код услуги
   ,[SUMMA]   NUMERIC(20,2)   --Средневзвешенная цена за единицу услуги (руб.) 
   ,[NPA_VID]   VARCHAR(8000) --Вид нормативного правового акта 
   ,[NPA_NAME_ORGAN]   VARCHAR(8000) -- Наименование органа, утвердившего нормативный правовой акт 
   ,[NPA_DATE]   VARCHAR(8000)--Дата нормативного правового акта
   ,[NPA_NUM]   VARCHAR(8000) --Номер нормативного правового акта
   ,[NPA_NAME]   VARCHAR(8000)--Наименование нормативного правового акта 
)
-- Сведения о работах   
CREATE TABLE #tab002_WORK
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)       -- Код работы
   ,[NUM_UTV] VARCHAR(200) -- Номер (код) по утвержденному перечню услуг 
   ,[NUM]   VARCHAR(50)       --Порядковый номер раздела соответствующий работе
   ,[NAME]   VARCHAR(8000)    --Наименование работы, указанной в данном разделе
)
Create index #IX_tab002 on #tab002 (ID)
Create index #IX_tab002_SERVICE on #tab002_SERVICE (ID)
Create index #IX_tab002_QUALITY on #tab002_QUALITY (ID)
Create index #IX_tab002_VOLUME on #tab002_VOLUME (ID)
Create index #IX_tab002_PRICE on #tab002_PRICE (ID)
Create index #IX_tab002_WORK on #tab002_WORK (ID)

CREATE TABLE #tabXML ([TXT] VARCHAR(8000), [ORDERS] INT IDENTITY(1,1), ID UNIQUEIDENTIFIER) 

INSERT #tabHead (DATE, ID)
SELECT GETDATE(), NEWID()

-- получение данных
EXEC dbo.[RO_EXPORT_86N_GET_DATA] @iLINK_SAVED_FORM, 2

-- формирование xml 
EXEC dbo.[RO_EXPORT_86N_GET_XML] 2

IF EXISTS(SELECT * FROM #tabXML)
BEGIN 
   SELECT @vcFILE_NAME = RTRIM(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(100), [ID]),'-',''), '}', ''), '{', ''))
   FROM #tabHead

   INSERT #FileExportReport([TXT],
                            [NameFile],
                            [ORDERS],
                            [NameFileArh])
   SELECT [TXT],
	       @vcFILE_NAME + '.xml',
	       [ORDERS],
          @vcFILE_NAME  + '.zip'
   FROM #tabXML
   ORDER BY [ORDERS]

   SET @vcFILE_NAME = @vcFILE_NAME + '.xml'
END 

DROP TABLE #tabHead
DROP TABLE #tab001
DROP TABLE #tab002
DROP TABLE #tab002_PRICE
DROP TABLE #tab002_QUALITY
DROP TABLE #tab002_VOLUME
DROP TABLE #tab002_WORK
DROP TABLE #tabXML

GO
GRANT ALL ON dbo.[RO_EXPORT_86N_002] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



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 '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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[HTMLReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[HTMLReport]
GO

/* Назначение: Формирование протокола в виде html-файла
    Параметры :          
                    @nMode int = 0,                     -- режим работы:
                                                        --   0 - первый вызов процедуры(запись в таблицу шапки html-файла и(если указана) данных из таблицы)
                                                        --   1 - повторные вызовы процедуры для добавления таблиц с выводимой информацией
                                                        --   2 - вывод полученного файла в text поле
                                                        --   3 - вывод полученного файла (без системных тэгов) в text поле
                    @cWorkTableName varchar(50),        -- имя рабочей таблицы. должна создаваться из вызывающей процедуры
                                                        --   структура: table ([order] int, [type] int, [html] varchar(8000))
                    @cRepHeader varchar(8000) = '',     -- заголовок протокола. может состоять из нескольких строк(разделенных переводом строки или символом "|")
                    @cDataDesc varchar(8000) = '',      -- описание таблицы
                    @cDataTableName varchar(50) = '',   -- название таблицы с данными
                    @cShowFields varchar(500) = '',     -- имена полей, который необходимо вывести в протоколе(разделенные символом "|")
                    @cFieldsDesc varchar(2000) = '',    -- описания полей, который необходимо вывести в протоколе(разделенные символом "|")
                    @cGroupFields varchar(100) = '',    -- список полей для группировки 
                    @cGroupDesc varchar(1000) = '',     -- описание формата вывода для полей группировки (пример: 'Документ @number от @date', где @number и @date - поля группировки)
                    @nRepResult int = 0,                -- результат протокола 
                    @cOrderFields varchar(100) = '',    -- список полей для сортировки
                    @nWriteToLog int = 0,               -- флаг вывода полученного протокола в системный журнал:
																0 - не выводить в журнал, 
																1 - в папку Пользователи, 
																2 - в папку Документы, 
																3 - в папку ЭОД, 
																4 - в папку Справочники, 
																5 - в папку Сводные отчеты, 
																6 - в папку Аналитические признаки
                    @nSysEventsLink int = 0,            -- линк записи в sys_events (для записи отчета в sys_events_doc)
                    @cRepFooter varchar(8000) = '',     -- "подвал" протокола. может состоять из нескольких строк (разделенных переводом строки или символом "|")
                    @cInto varchar(50) = ''             -- имя временной таблицы для размещения сформированного протокола

    Код возврата: Таблица с text-полем, в котором находится сформированный html-код
    Пример работы:

			if object_id('tempdb..#work') is not null drop table #work
			create table #work([order] int, [type] int, [html] varchar(8000))
			
			if object_id('tempdb..#data1') is not null drop table #data1
			create table #data1(f1 varchar(100), f2 varchar(100))
			insert into #data1(f1, f2) values ('aaaa', 'bbbbbb')
			insert into #data1(f1, f2) values ('cccc', 'ddddddddddd')
			
			if object_id('tempdb..#data2') is not null drop table #data2
			create table #data2(f1 varchar(100), f2 varchar(100))
			insert into #data2(f1, f2) values ('aaaa1111', 'bbbbbb22222')
			insert into #data2(f1, f2) values ('cccc33333', 'ddddddddddd444444')
			insert into #data2(f1, f2) values ('eeee555555', 'fffffffffffff666666666666666')
			
			-- создание протокола(можно совместить с выводом первой таблицы)
			exec HTMLReport @nMode 				= 0, 
							@cWorkTableName 	= '#work', 
							@cRepHeader 		= 'Удаление документов|Список документов и статусов их удаления'
			
			-- добавление первой таблицы
			exec HTMLReport @nMode 				= 1, 
							@cWorkTableName 	= '#work', 
							@cDataDesc 			= 'Таблица удаленных документов',
							@cDataTableName		= '#data1',
							@cShowFields		= 'f1|f2',
							@cFieldsDesc		= 'Поле №1|Поле №2'
			
			-- добавление второй таблицы
			exec HTMLReport @nMode 				= 1, 
							@cWorkTableName 	= '#work', 
							@cDataDesc 			= 'Таблица неудаленных документов',
							@cDataTableName		= '#data2',
							@cShowFields		= 'f1|f2',
							@cFieldsDesc		= 'Поле №3|Поле №4'
			
			-- вывод полученного html-кода
			exec HTMLReport @nMode 				= 2, 
							@cWorkTableName 	= '#work'
			
			
			drop table #work
			drop table #data1
			drop table #data2



    Примечание: Используется для получения html-кода протокола выполнения какой-либо операции.
	        Изменена GARY 30.01.2007 для перехода на SQL2005 ввод sys.columns 
    Автор: Рудаков Андрей.
           (Evil - 2007-10-24): добавил обработку параметра @cRepFooter
*/
 
  
-- rev 1.36  
create procedure dbo.HTMLReport(  
  @nMode int = 0,                         
                                 
                                          
                                          
                                          
  @cWorkTableName varchar(50),            
                                          
  @cRepHeader varchar(8000) = '',         
  @cDataDesc varchar(8000) = '',          
  @cDataTableName varchar(50) = '',       
  @cShowFields varchar(8000) = '',        
  @cFieldsDesc varchar(8000) = '',        
  @cGroupFields varchar(8000) = '',       
  @cGroupDesc varchar(8000) = '',         
  @nRepResult int = 0,                    
  @cOrderFields varchar(8000) = '',       
  @nWriteToLog int = 0,                   
  @nSysEventsLink int = 0,                
  @cRepFooter varchar(8000) = '',         
  @cInto varchar(50) = ''                 
)  
as  
begin  
  
set nocount on  
set transaction isolation level read uncommitted  
create table #html_tbl([order] int, [type] int, [html] varchar(8000))  
create index tmp_ind_htmlOrder on #html_tbl([order])  
  
create table #TableDesc(id int identity(1,1), fld_name varchar(50), fld_type varchar(10), fld_size int, fld_format varchar(6000), st_tag varchar(500), end_tag varchar(500))  
create table #TableStyle(id int identity(1,1), fld_name varchar(50), fld_align varchar(10), fld_wrap int, fld_bgcolor varchar(20), fld_color varchar(20), fld_style varchar(200),fld_width varchar(200))  
create index tmp_ind_tStyle on #TableStyle(id)  
create table #tmp_text(textfld text)  
create table #tmp_text_data(id int identity(1,1), text_data varchar(8000))  
create table #tmp_rep_data(id int identity(1,1), rep_data varchar(8000))  
create table #tmp_rep_group(id int identity(1,1), group_val varchar(4000), group_data varchar(4000))  
create table #tmp_rep_data_gr(id int identity(1,1), rep_data varchar(8000))  
create table #text_tbl(text_fld text)  
  
  
declare @sql varchar(8000), @order int, @st_order int, @end_order int, @cur_id int, @list_len int, @list_ind int  
  
set @st_order = 1  
set @end_order = 999999999  
  
  
  
if @nMode = 0  
 begin  
    
  
  insert  #html_tbl([order], [type], [html])   
         select @st_order, 0, '<HTML>'  
     union all  
         select @end_order, 0, '</HTML>'  
     union all  
         select @st_order + 1, 0, '<HEAD><META HTTP-EQUIV=CONTENT-TYPE CONTENT="TEXT/HTML; CHARSET=WINDOWS-1251">'  
  
  
    
  set @sql = dbo.get_val('NASTR_HTML_STYLE', 'char_value', 0)  
  if @sql is null  
   begin  
    insert into #html_tbl([order], [type], [html]) values(@st_order + 2, 0, '<STYLE>BODY {FONT-FAMILY: COURIER NEW, COURIER; FONT-SIZE: X-SMALL; COLOR: BLACK;}  
H1 {FONT-SIZE: SMALL; MARGIN:0; PADDING: 2 2 4 2;}  
HR {HEIGHT: 1; COLOR: GRAY;}  
#WARN {COLOR: RED; FONT-WEIGHT: BOLD;}  
#GOOD {COLOR: GREEN; FONT-WEIGHT: BOLD;}  
#INFO {COLOR: BLUE; FONT-WEIGHT: BOLD;}  
#LOCK {COLOR: GRAY; FONT-WEIGHT: BOLD;}  
#NONE {COLOR: BLACK}  
TABLE.GRID {FONT-FAMILY: COURIER NEW, COURIER; FONT-SIZE: X-SMALL; BORDER: 1 GRAY SOLID;}  
TH {COLOR: BLACK;}  
TR.SUBTITLE {BACKGROUND: #EFEFEF;}  
TR.ODD {BACKGROUND: WHITE;}  
TR.EVEN {BACKGROUND: #EFEFFF;}  
TD.CELL {BORDER: 0;}  
TABLE.GRID_IN {FONT-FAMILY: ARIAL, COURIER NEW, COURIER; FONT-SIZE: X-SMALL; BORDER: 1 GRAY SOLID; WIDTH: 100%;}  
TR.TITLE TH {BACKGROUND: SILVER; COLOR: BLACK; BORDER-BOTTOM:1 GRAY SOLID; PADDING: 0 4 0 4;}  
.hrefstyle {cursor:pointer; text-decoration:underline; color:blue}  
.error {color: #cc0000;}  
.warn {color: #999900;}  
</STYLE>')  
   end  
  else  
   begin   
    insert into #html_tbl([order], [type], [html]) values(@st_order + 2, 0, '<STYLE>  
' + @sql + '  
</STYLE>')  
   end  
  
  declare @nObjProj int  
  select @nObjProj = dbo.obj_id('PROJECT')  
  
declare @vers varchar(1000)
exec Версия @vers output,0

  insert into #html_tbl([order], [type], [html])   
        select @st_order + 3, 0, '</HEAD>'  
        union all  
        select @st_order + 4, 0, '<BODY>'  
        union all  
        select @st_order + 5, 0, '<HR><TABLE STYLE="WIDTH: 100%;FONT-SIZE: 10;"><TR><TD ALIGN=RIGHT>Свод-кс "'+@vers +  '</TD></TR></TABLE>'
        union all  
    select @end_order - 2, 0, '</BODY>'  
  
  set @order = @end_order - 3  
    
  if IsNull(@cRepFooter, '') <> ''  
   begin  
      
    set @cRepFooter = replace(@cRepFooter, char(13) + char(10), '|')  
    set @cRepFooter = replace(@cRepFooter, char(13), '|')  
    set @cRepFooter = replace(@cRepFooter, char(10), '|')  
  
    select @list_len = dbo.ListLenX(@cRepFooter, '|'), @list_ind = 0  
    insert into #html_tbl([order], [type], [html]) values(@order, 0, '<DIV><BR>')  
    while @list_ind < @list_len  
     begin  
      insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_ind + 1, 0, dbo.GetElementX(@cRepFooter, '|', @list_ind) + '<BR>')  
      set @list_ind = @list_ind + 1  
     end  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 1, 0, '</DIV>')  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 2, 0, '<BR>')  
    
    set @order = @st_order + @order + @list_len + 3  
   end  
  else  
   begin  
      
    insert into #html_tbl([order], [type], [html])   
    select @order, 0, '<BR><BR><TABLE STYLE="WIDTH: 100%;FONT-SIZE: 10;"><TR>  
<TD>Дата формирования: ' + convert(varchar(20), getdate(), 104) + '<BR>Время формирования: ' + convert(varchar(20), getdate(), 108) + '</TD><TD>&nbsp;</TD>  
<TD ALIGN=RIGHT>' +  '</TD>  
</TR></TABLE>'  
   end  
  
  
  set @order = 6  
  
    
  if @cRepHeader <> ''  
   begin  
      
    set @cRepHeader = replace(@cRepHeader, char(13) + char(10), '|')  
    set @cRepHeader = replace(@cRepHeader, char(13), '|')  
    set @cRepHeader = replace(@cRepHeader, char(10), '|')  
  
    select @list_len = dbo.ListLenX(@cRepHeader, '|'), @list_ind = 0  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order, 1, '<DIV>')  
    while @list_ind < @list_len  
     begin  
      if @list_ind = 0  
       insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_ind + 1, 1, '<H1>' + dbo.GetElementX(@cRepHeader, '|', @list_ind) + '</H1><HR>')  
      else  
       insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_ind + 1, 1, dbo.GetElementX(@cRepHeader, '|', @list_ind) + '<BR>')  
      set @list_ind = @list_ind + 1  
     end  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 1, 1, '</DIV>')  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 2, 1, '<BR>')  
    
    set @order = @st_order + @order + @list_len + 3  
   end  
 end  
  
if @nMode >= 1  
 begin  
  set @sql = 'insert into #html_tbl select [order], [type], [html] from ' + @cWorkTableName  
  exec (@sql)  
  
  exec sp_executesql N'select @order = isnull(max([order]), 0) + 1 from #html_tbl where type > 0', N'@order int output', @order = @order output  
  if @order < 6 set @order = 6  
  
    
    
  if @cRepHeader <> ''  
   begin  
      
    set @cRepHeader = replace(@cRepHeader, char(13) + char(10), '|')  
    set @cRepHeader = replace(@cRepHeader, char(13), '|')  
    set @cRepHeader = replace(@cRepHeader, char(10), '|')  
  
    select @list_len = dbo.ListLenX(@cRepHeader, '|'), @list_ind = 0  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order, 1, '<DIV>')  
    while @list_ind < @list_len  
     begin  
      if @list_ind = 0  
       insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_ind + 1, 1, '<H1>' + dbo.GetElementX(@cRepHeader, '|', @list_ind) + '</H1><HR>')  
      else  
       insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_ind + 1, 1, dbo.GetElementX(@cRepHeader, '|', @list_ind) + '<BR>')  
      set @list_ind = @list_ind + 1  
     end  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 1, 1, '</DIV>')  
    insert into #html_tbl([order], [type], [html]) values(@st_order + @order + @list_len + 2, 1, '<BR>')  
    
    set @order = @st_order + @order + @list_len + 3  
   end  
  
  
  exec sp_executesql N'select @order = isnull(max([order]), 0) + 1 from #html_tbl where type > 0', N'@order int output', @order = @order output  
  if @order < 6 set @order = 6  
 end  
  
  
  
  
  
if @cDataDesc <> ''  
 begin  
    
  set @cDataDesc = replace(@cDataDesc, char(13) + char(10), '|')  
  set @cDataDesc = replace(@cDataDesc, char(13), '|')  
  set @cDataDesc = replace(@cDataDesc, char(10), '|')  
  
  select @list_len = dbo.ListLenX(@cDataDesc, '|'), @list_ind = 0  
  exec sp_executesql N'insert into #html_tbl([order], [type], [html]) values(@order, 2, ''<DIV>'')', N'@order int', @order = @order  
  while @list_ind < @list_len  
   begin  
      
    exec sp_executesql N'insert into #html_tbl([order], [type], [html]) values(@order + @list_ind + 1, 2, dbo.GetElementX(@cDataDesc, ''|'', @list_ind) + ''<BR>'')', N'@order int, @list_ind int, @cDataDesc varchar(8000)', @order = @order, @list_ind = @list_ind, @cDataDesc = @cDataDesc  
    set @list_ind = @list_ind + 1  
   end  
  exec sp_executesql N'insert into #html_tbl([order], [type], [html]) values(@order + @list_len + 1, 2, ''</DIV>'')', N'@order int, @list_len int', @order = @order, @list_len = @list_len  
   
  set @order = @order + @list_len + 3  
 end  
  
if @cDataTableName <> ''  
 begin  
  declare @head varchar(8000), @flds varchar(8000), @tmp_name varchar(50), @tmp_type varchar(10), @tmp_size int, @tmp_id int, @max_id int, @tmp_format varchar(8000)  
  declare @tmpElem varchar(128)  
  
    
    
  declare @cDBName varchar(128)  
  if left(@cDataTableName, 1) = '#'  
   set @cDBName = 'tempdb..'  
  else  
   set @cDBName = ''  
  
  set @sql = 'insert into #TableDesc(fld_name, fld_type, fld_size) '  
  if dbo.SqlProductVersion(0) = '8'  
   begin  
    select @sql = @sql + 'select name, case when xtype in (167, 175) then ''c'' when xtype in (127, 56, 52, 48, 104) then ''n'' when xtype in (58, 61) then ''d'' when xtype in (59, 60, 62, 106, 108, 122) then ''f'' when xtype in (35, 99) then ''t'' else ''u'' end as fld_type, length from ' + @cDBName + 'syscolumns c where c.id = object_id(''' + @cDBName + @cDataTableName + ''')'  
   end  
  else  
   begin  
    select @sql = @sql + 'select name, case   
       when [system_type_id] in (167, 175) then ''c''   
       when [system_type_id] in (127, 56, 52, 48, 104) then ''n''   
       when [system_type_id] in (58, 61) then ''d''   
       when [system_type_id] in (59, 60, 62, 106, 108, 122) then ''f''   
       when [system_type_id] in (35, 99) then ''t''   
       else ''u'' end as [fld_type],   
       [length] = [max_length]     
       from '+case when len(@cDBName) > 0 then left(@cDBName,len(@cDBName) - 1) else '' end + 'sys.columns c where [object_id] = object_id(''' + @cDBName + @cDataTableName + ''')'  
   end    
  exec (@sql)  
  select @tmp_id = 1  
  exec sp_executesql N'select @max_id = max(id) from #TableDesc', N'@max_id int output', @max_id = @max_id output  
  while @tmp_id <= @max_id  
   begin  
    select @tmp_name = fld_name, @tmp_type = fld_type from #TableDesc where id = @tmp_id  
    if @tmp_type = 'c'  
     begin  
      set @sql = 'update #TableDesc set fld_size = (select dbo.HTMLStrLen(max([' + @tmp_name + '])) from ' + @cDataTableName + ') where id = ' + cast(@tmp_id as varchar(10))  
      exec(@sql)  
     end  
  
    select @tmp_id = @tmp_id + 1  
   end  
  if left(ltrim(@cShowFields), 1) = '<'   
   begin  
      
    declare @st_tag varchar(500), @end_tag varchar(500), @fld_name varchar(50), @fld_align varchar(10), @fld_wrap int, @fld_bgcolor varchar(20), @fld_color varchar(20), @fld_style varchar(200)  , @fld_width varchar(200)
      
    declare @idoc int  
    set @flds = '<style>' + lower(@cShowFields) + '</style>'   
    exec sp_xml_preparedocument @idoc output, @flds  
  
    insert into #TableStyle  
     select *  
     from openxml (@idoc, '/style/field', 3)  
        with ( fld_name varchar(50) '@name',  
          fld_align varchar(10) '@align',  
          fld_wrap int '@wrap',  
          fld_bgcolor varchar(20) '@bgcolor',  
          fld_color varchar(20) '@color',  
          fld_style varchar(200) '@style' ,
		  fld_width varchar(200) '@width'  
         )  
    
      
    set @cShowFields = ''  
    select @tmp_id = min(id) from #TableStyle where fld_name is not null  
    while @tmp_id is not null  
     begin  
      select @st_tag = '<TD', @end_tag = '</TD>', @fld_name = fld_name, @fld_align = isnull(fld_align, ''), @fld_wrap = isnull(fld_wrap, 0), @fld_bgcolor = isnull(fld_bgcolor, ''), @fld_color = isnull(fld_color, ''), @fld_style = isnull(fld_style, ''), @fld_width = isnull(fld_width, '')  from #TableStyle where id = @tmp_id  
        
      if @fld_align <> '' set @st_tag = @st_tag + ' ALIGN=' + @fld_align  
      if @fld_wrap = 0 set @st_tag = @st_tag + ' NOWRAP'  
      if @fld_width <>'' set @st_tag = @st_tag + ' WIDTH = '+@fld_width  

      if @fld_bgcolor <> '' set @st_tag = @st_tag + ' BGCOLOR=' + @fld_bgcolor  
      if @fld_style <> '' set @st_tag = @st_tag + ' STYLE="' + @fld_style + '"'  
      set @st_tag = @st_tag + '>'  
      if @fld_color <> '' select @st_tag = @st_tag + '<FONT COLOR=' + @fld_color + '>', @end_tag = '</FONT>' + @end_tag  
  
      update #TableDesc set st_tag = @st_tag, end_tag = @end_tag where fld_name = @fld_name  
        
      set @cShowFields = @cShowFields + @fld_name + '|'  
  
      select @tmp_id = min(id) from #TableStyle where id > @tmp_id and fld_name is not null  
     end  
    if @cShowFields <> ''  
     set @cShowFields = left(@cShowFields, len(@cShowFields) - 1)  
   end  
  else  
   begin  
      
    select @list_len = dbo.ListLenX(@cShowFields, '|'), @list_ind = 0  
    while @list_ind < @list_len  
     begin  
      set @tmpElem = dbo.GetElementX(@cShowFields, '|', @list_ind)  
      select @tmp_name = fld_name, @tmp_id = id from #TableDesc where fld_name = @tmpElem  
  
      if @tmp_id is not null  
       update #TableDesc  
       set st_tag =   
         case  
          when fld_type = 'd' then '<TD NOWRAP ALIGN=CENTER>'  
          when fld_type in ('n', 'f') then '<TD NOWRAP ALIGN=RIGHT>'  
          when fld_type = 'c' and fld_size > 50 then '<TD>'  
          else '<TD NOWRAP>'  
         end,  
        end_tag = '</TD>'  
       where id = @tmp_id  
  
      set @list_ind = @list_ind + 1  
     end  
   end  
     
  
  update #TableDesc  
  set fld_format =   
    case  
     when fld_type = 'n' then '''' + st_tag + '&nbsp;'' + isnull(cast([' + fld_name + '] as varchar(20)), '''') + ''&nbsp;' + end_tag + ''' + '  
     when fld_type = 'f' then '''' + st_tag + ''' + isnull(dbo.rn_convert_number([' + fld_name + '], 2, '' ''), '''') + ''' + end_tag + ''' + '  
     when fld_type = 'd' then '''' + st_tag + '&nbsp;'' + isnull(convert(varchar(10), [' + fld_name + '], 104), '''') + ''&nbsp;' + end_tag + ''' + '  
     when fld_type = 'c' then '''' + st_tag + '&nbsp;'' + isnull([' + fld_name + '], '''') + ''&nbsp;' + end_tag + ''' + '  
     else '''<TD NOWRAP>&nbsp;'' + isnull(cast([' + fld_name + '] as varchar(8000)), '''') + ''&nbsp;</TD>'' + '  
    end  
    
  
  
    
    
    
  declare @nTextOut tinyint, @cTextFldName varchar(128)  
    
  if exists(select id from #TableDesc where fld_type = 't')  
   begin  
    set @nTextOut = 1  
      
  
      
      
      
  
      
    select @cTextFldName = fld_name from #TableDesc where fld_type = 't'  
    set @sql = 'insert into #tmp_text(textfld) select top 1 ' + @cTextFldName + ' from ' + @cDataTableName  
    exec(@sql)  
  
      
  
    declare @textlen int, @block_len int, @cur_offset int, @tmpstr varchar(8000), @tmpind int, @real_size int, @tmp_id1 int  
    select @textlen = datalength(textfld), @block_len = 8000, @cur_offset = 0 from #tmp_text  
      
    while @cur_offset < @textlen  
     begin  
      insert into #tmp_text_data(text_data)  
       exec ReadFromText '#tmp_text', 'textfld', @cur_offset, @block_len  
  
        
      select @tmp_id1 = max(id) from #tmp_text_data  
      select @tmpstr = reverse(text_data) from #tmp_text_data where id = @tmp_id1  
  
      if dbo.StrLen(@tmpstr) = @block_len  
       begin  
        select @tmpind = charindex(char(10), @tmpstr)  
        if @tmpind <> 0  
         select @tmpind = charindex('>', @tmpstr)  
        if @tmpind <> 0  
         select @tmpind = charindex(' ', @tmpstr)  
        if @tmpind = 0  
         select @tmpind = 1  
    
        select @tmpstr = reverse(@tmpstr)  
        select @tmpstr = left(@tmpstr, dbo.StrLen(@tmpstr) - @tmpind + 1)  
        update #tmp_text_data set text_data = @tmpstr where id = @tmp_id1  
      
        set @real_size = @block_len - @tmpind + 1  
        set @cur_offset = @cur_offset + @real_size  
       end  
      else  
       set @cur_offset = @cur_offset + @block_len  
     end  
  
   end  
  else   
   set @nTextOut = 0  
    
  
  if @cGroupFields = ''  
   begin  
      
  
    set @flds = ''  
    select @list_len = dbo.ListLenX(@cShowFields, '|'), @list_ind = 0  
    while @list_ind < @list_len  
     begin  
      set @tmpElem = dbo.GetElementX(@cShowFields, '|', @list_ind)  
      select @tmp_name = fld_name, @tmp_format = fld_format from #TableDesc where fld_name = @tmpElem  
  
      if @tmp_name is not null  
       set @flds = @flds + @tmp_format  
      else  
       set @flds = @flds + '''<TD NOWRAP>&nbsp;'' + isnull(cast([' + dbo.GetElementX(@cShowFields, '|', @list_ind) + '] as varchar(8000)), '''') + ''&nbsp;</TD>'' + '  
  
      set @list_ind = @list_ind + 1  
     end  
    set @flds = @flds + ''''''  
  
      
    set @sql = 'insert into #tmp_rep_data(rep_data)  
        select ' + @flds + '  
        from ' + @cDataTableName  
    if @cOrderFields <> ''  
     set @sql = @sql + ' order by ' + replace(@cOrderFields, '|', ', ')  
    exec(@sql)  
  
    if exists(select id from #tmp_rep_data)  
     begin  
      if @nTextOut = 0  
       insert into #html_tbl([order], [type], [html]) values(@order + 1, 2, '<TABLE BORDER=1 ' +  
--rules="rows" 
'CLASS=GRID_IN CELLSPACING=0 CELLPADDING=2>')  
      
        
      if @cFieldsDesc <> ''  
       begin  
        set @head = ''  
        select @list_len = dbo.ListLenX(@cFieldsDesc, '|'), @list_ind = 0  
        while @list_ind < @list_len  
         begin  
          set @head = @head + '<TH>&nbsp;' + dbo.GetElementX(@cFieldsDesc, '|', @list_ind) + '&nbsp;</TH>'  
          set @list_ind = @list_ind + 1  
         end  
  
          
        insert into #html_tbl([order], [type], [html])  
         select @order + 2, 2, '<TR CLASS=TITLE BG=SILVER>' +  @head + '</TR>'  
        set @order = @order + 2  
       end  
    
  
        
      if @nTextOut = 0  
       begin  
        insert into #html_tbl([order], [type], [html])  
         select @order + id, 2, '<TR CLASS=' + case id % 2 when 1 then 'ODD' else 'EVEN' end + '>' +  rep_data + '</TR>'  
         from #tmp_rep_data  
        
        exec sp_executesql N'select @order = max([order]) from #html_tbl where type > 0', N'@order int output', @order = @order output  
        insert into #html_tbl([order], [type], [html]) values(@order + 1, 2, '</TABLE><BR>')  
       end  
      else  
       begin  
          
        insert into #html_tbl([order], [type], [html])  
         select @order + id, 2, text_data  
         from #tmp_text_data  
  
  
        select @order = max([order]) from #html_tbl where type > 0  
       end  
     end  
  
   end  
  else  
   begin  
      
  
    declare @gr_flds_ins varchar(200)  
    set @gr_flds_ins = '|'  
  
    set @flds = ''  
    select @list_len = dbo.ListLenX(@cShowFields, '|'), @list_ind = 0  
    while @list_ind < @list_len  
     begin  
      if charindex(dbo.GetElementX(@cShowFields, '|', @list_ind) + '|', @cGroupFields + '|') = 0  
       begin  
                    select @tmp_name = null, @tmp_format = null  
  
        set @tmpElem = dbo.GetElementX(@cShowFields, '|', @list_ind)  
        select @tmp_name = fld_name, @tmp_format = fld_format from #TableDesc where fld_name = @tmpElem  
  
        if @tmp_format is not null  
         set @flds = @flds + @tmp_format  
        else  
         if @tmp_name is not null   
          set @flds = @flds + '''<TD NOWRAP>&nbsp;'' + isnull(cast([' + dbo.GetElementX(@cShowFields, '|', @list_ind) + '] as varchar(8000)), '''') + ''&nbsp;</TD>'' + '  
         else  
          set @flds = @flds + '''<TD NOWRAP>&nbsp;</TD>'' + '  
       end  
      else  
       set @gr_flds_ins = @gr_flds_ins + cast(@list_ind as varchar(10)) + '|'  
      set @list_ind = @list_ind + 1  
     end  
    set @flds = @flds + ''''''  
  
      
    set @head = ''  
    select @list_len = dbo.ListLenX(@cFieldsDesc, '|'), @list_ind = 0  
    while @list_ind < @list_len  
     begin  
      if charindex('|' + cast(@list_ind as varchar(10)) + '|', @gr_flds_ins) = 0  
       set @head = @head + '<TH NOWRAP>&nbsp;' + dbo.GetElementX(@cFieldsDesc, '|', @list_ind) + '&nbsp;</TH>'  
      set @list_ind = @list_ind + 1  
     end  
    
  
    declare @gr_fld varchar(100), @gr_desc varchar(4000), @gr_val varchar(4000)  
    select @list_len = dbo.ListLenX(@cGroupFields, '|'), @list_ind = 0, @gr_desc = @cGroupDesc, @gr_val = @cGroupFields  
    while @list_ind < @list_len  
     begin  
      set @gr_fld = dbo.GetElementX(@cGroupFields, '|', @list_ind)  
      set @gr_desc = replace(@gr_desc, '@' + @gr_fld, ''' + isnull(cast(' + @gr_fld + ' as varchar(8000)), '''') + ''')  
      set @gr_desc = replace(@gr_desc, '@#DATE#' + @gr_fld, ''' + isnull(convert(varchar(20), ' + @gr_fld + ', 104), '''') + ''')  
      set @list_ind = @list_ind + 1  
     end  
    set @gr_desc =  '''' + @gr_desc + ''''  
    set @gr_val = 'isnull(cast(' + replace(@gr_val, '|', ' as varchar(8000)), '''') + ''|'' + isnull(cast(') + ' as varchar(8000)), '''')'  
      
  
      
    set @sql = '  
       insert into #tmp_rep_group(group_val, group_data)  
        select ' + @gr_val + ', ' + @gr_desc + '  
        from ' + @cDataTableName + '  
        order by ' + replace(@cGroupFields, '|', ', ')  
    if @cOrderFields <> ''  
     set @sql = @sql + ', ' + replace(@cOrderFields, '|', ', ')  
  
    set @sql = @sql + '  
       insert into #tmp_rep_data_gr(rep_data)  
        select ' + @flds + '  
        from ' + @cDataTableName + '  
        order by ' + replace(@cGroupFields, '|', ', ')  
    if @cOrderFields <> ''  
     set @sql = @sql + ', ' + replace(@cOrderFields, '|', ', ')  
  
    exec(@sql)  
   
      
    declare @gr_count int  
    exec sp_executesql N'select @gr_count = count(id) from #tmp_rep_group', N'@gr_count int output', @gr_count = @gr_count output  
    if @gr_count > 0  
     begin  
  
      insert into #html_tbl([order], [type], [html]) values(@order + 1, 2, '<TABLE CLASS=GRID FRAME=BORDER>')  
      set @order = @order + 2  
    
      declare @last_gr_id int, @cur_gr_val varchar(4000), @last_gr_val varchar(4000), @cur_gr_desc varchar(4000)  
  
      select @last_gr_val = '', @cur_id = 1, @last_gr_id = 0  
      exec sp_executesql N'select @max_id = max(id) from #tmp_rep_group', N'@max_id int output', @max_id = @max_id output  
      while @cur_id <= @max_id  
       begin  
        exec sp_executesql N'select @cur_gr_val = group_val, @cur_gr_desc = group_data from #tmp_rep_group where id = @cur_id', N'@cur_id int, @cur_gr_val varchar(4000) output, @cur_gr_desc varchar(4000) output', @cur_id = @cur_id, @cur_gr_val = @cur_gr_val output, @cur_gr_desc = @cur_gr_desc output  
  
        if @cur_gr_val <> @last_gr_val  
         begin  
            
    
          if @last_gr_val <> ''   
           begin  
              
            insert into #html_tbl([order], [type], [html]) values(@order, 2, '</TABLE><BR></TD></TR>')  
            set @order = @order + 1  
           end  
    
            
          insert into #html_tbl([order], [type], [html])  
           select @order, 2, '<TR CLASS=ODD><TD CLASS=CELL>' +  @cur_gr_desc + '</TD></TR>'  
          set @order = @order + 1  
    
            
          insert into #html_tbl([order], [type], [html])   
           select @order, 2, '<TR CLASS=ODD><TD CLASS=CELL COLSPAN=3 STYLE=PADDING-LEFT:20>'  
          insert into #html_tbl([order], [type], [html])   
           select @order + 1, 2, '<TABLE BORDER=1  ' + 
--rules="rows" 
'CLASS=GRID_IN CELLSPACING=1 CELLPADDING=2>'  
    
            
          insert into #html_tbl([order], [type], [html])  
           select @order + 2, 2, '<TR CLASS=TITLE BG=SILVER>' +  @head + '</TR>'  
          set @order = @order + 3  
         end  
    
          
        exec sp_executesql N'  
        insert into #html_tbl([order], [type], [html])  
         select @order, 2, ''<TR CLASS='' + case (id - @last_gr_id) % 2 when 1 then ''ODD'' else ''EVEN'' end + ''>'' +  rep_data + ''</TR>''  
         from #tmp_rep_data_gr  
         where id = @cur_id', N'@order int, @last_gr_id int, @cur_id int', @order = @order, @last_gr_id = @last_gr_id, @cur_id = @cur_id  
    
        set @order = @order + 1  
    
        select @last_gr_val = @cur_gr_val, @cur_id = @cur_id + 1  
        if @cur_id > @max_id  
           
         insert into #html_tbl([order], [type], [html]) values(@order, 2, '</TABLE></TD></TR>')  
    
       end  
    
        
      insert into #html_tbl([order], [type], [html]) values(@order + 1, 2, '</TABLE>')  
     end  
  
  
    insert into #html_tbl([order], [type], [html]) values(@order + 2, 2, '<BR>')  
   end  
 end  
  
  
  
set @sql = 'truncate table ' + @cWorkTableName + ' insert into ' + @cWorkTableName + ' select [order], [type], [html] from #html_tbl'  
exec (@sql)  
  
  
if @nMode = 2 or @nMode = 3  
 begin  
  
    
  if @nWriteToLog > 0 and @nSysEventsLink  = 0  
   exec admin_write_events @nMode = 2, @nCondition = @nWriteToLog, @cNote = @cRepHeader, @nAction = 21, @cTable_ins = '#html_tbl|[order]|[html]'  
    
  if @nSysEventsLink <> 0  
   begin  
    exec admin_write_events @nMode = 2, @cNote = @cRepHeader, @cTable_ins = '#html_tbl|[order]|[html]', @nLink = @nSysEventsLink  
   
      
    return  
   end  
  
  
  
  declare @str varchar(8000)  
  insert into #text_tbl(text_fld) values('')  
  
  declare @ptrval binary(16), @text_len int  
  select @ptrval = textptr(text_fld) from #text_tbl  
  
  select @cur_id = min([order]) from #html_tbl where [type] >= @nMode - 2  
  while @cur_id is not null  
   begin  
    select @str = [html] from #html_tbl where [order] = @cur_id  
  
    select @text_len = DATALENGTH(text_fld) from #text_tbl  
    updatetext #text_tbl.text_fld @ptrval @text_len 0 @str   
  
    select @cur_id = min([order]) from #html_tbl where [order] > @cur_id  and [type] >= @nMode - 2  
   end  
  
  if IsNull(@cInto, '') = ''  
   select text_fld as htmlcode, @nRepResult as result from #text_tbl  
  else  
   execute('insert into ' + @cInto + ' (htmlcode, result) select text_fld, ' + @nRepResult + ' from #text_tbl')  
  
 end  
  
  
end  
  

GO
GRANT ALL ON dbo.[HTMLReport] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_WEB_EDIT_FORMRRO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_EDIT_FORMRRO]
GO




/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB для формы RRO
*/


CREATE       PROCEDURE dbo.RO_WEB_EDIT_FORMRRO
	@varKSnLink	bigint,
	@varKSnTree	int = 0, -- если форма новая, то линк дерева сводов, иначе - линк дерева кбк
	@varKSisHeader int =0
AS
declare @iLF int
DECLARE @DATE	datetime,
	@PType	tinyint,
	@PNom	varchar(10),
	@DATE1 datetime,
	@DATE2 datetime, 
	@Periodic tinyint,
	@LSF	int,
	@Mode	int,
	@LinkOrg int,
	@LinkBudg int,
	@varKSnLinkOld bigint,
	@orderTable	tinyint,
	@atributs varchar(254),
	@LinkTable int,
	@DocCode varchar(20),
	@CountRow int,
	@utochn bit
set @varKSnLinkOld = @varKSnLink
set @LinkOrg = dbo.RO_SVOD_ORG(@varKSnTree)
set @LinkBudg = dbo.RO_SVOD_BUDG(@varKSnTree)
set @Mode = convert(int, @varKSnLink/4294967296)
set @varKSnLink = @varKSnLink - @Mode * 4294967296
set @Mode = abs(@Mode)

set @PNom = ''
set @orderTable = case isnull((select Code_Form from dbo.REPORT_KBK where link = @varKSnTree), '') when 'РРО' then 1 when 'РРО2' then 2 else 3 END

set @DocCode = case @orderTable when 1 then (select top 1 Code from RT_FORM_RRO_PNUM where link = @varKSnTree) else (select top 1 Code from RT_FORM_RRO_PNUM2 where link = @varKSnTree) END

set @PNom = case @orderTable when 1 then (select top 1 pnum from RT_FORM_RRO_PNUM where link = @varKSnTree) else (select top 1 pnum from RT_FORM_RRO_PNUM2 where link = @varKSnTree) end
 

set @utochn = case when @PNom <> '' then 1 else 0 end

select @LinkTable = Link_Table from report_tables where orders = @orderTable and Link_Form =(select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink)
select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink)

if @varKSnLink < 0
   select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = abs(@varKSnLink)


/* Список возвращаемых таблиц */
if @varKSnLink > 0
begin

	SELECT	[alias] = 'REP_HEAD', 
		[order] = convert(smallint,1),
		[tab_name] = 'Реквизиты',
		[link_table] = convert(varchar(50), 'REPORT_SVOD'),--convert(int,0),
		[table_type] = convert(smallint,2)
  UNION
	SELECT	[alias] = 'REP_ATR', 
	[order] = convert(smallint,2 ),
	[tab_name] = 'Атрибуты',
	[link_table] = convert(varchar(50), '-98'),
	[table_type] = convert(smallint, 0)
    WHERE @atributs<>'' 
UNION
	SELECT	[alias] = 'REP_TABLE_1',
		[order] = 3,
		[tab_name] = name + case when orders < 3 then case @utochn when 1 then '<BR><B>В ЭТОЙ ТАБЛИЦЕ СЛЕДУЕТ ЗАПОЛНЯТЬ ТОЛЬКО ЯЧЕЙКИ С СУММАМИ, НЕ БОЛЕЕ ЧЕМ В ОДНОЙ СТРОКЕ' else  '<BR><B> ЧИСЛОВЫЕ ДАННЫЕ ДОЛЖНЫ БЫТЬ ТОЛЬКО В ПЕРВОЙ СТРОКЕ!' end else '' end, 
		[link_table] = convert(varchar(50), Link_Table),
		[table_type] = val_type
	FROM REPORT_TABLES
	WHERE Link_Table = @LinkTable
	UNION
	SELECT	[alias] = 'REP_RGB_1',
		[order] = 4,
		[tab_name] = name,
		[link_table] = convert(varchar(50), Link_Table),
		[table_type] = 21
	FROM REPORT_TABLES
	WHERE Link_Table = @LinkTable
	UNION
	SELECT	[alias] = 'REP_NASTR', 
		[order] = convert(smallint, 99), 
		[tab_name] = 'Настройки печати',
		[link_table] = convert(varchar(50), '0'),
		[table_type] = convert(smallint, -1)
	ORDER BY [order]

end
else begin -- новая форма
	SELECT	[alias] = 'REP_HEAD', 
		[order] = convert(smallint,1),
		[tab_name] = 'Реквизиты',
		[link_table] = convert(varchar(50), 'REPORT_SVOD'),
		[table_type] = convert(smallint,2)
	UNION
	SELECT	[alias] = 'REP_ATR', 
	[order] = convert(smallint,2 ),
	[tab_name] = 'Атрибуты',
	[link_table] = convert(varchar(50), '-98'),
	[table_type] = convert(smallint, 0)
    WHERE @atributs<>'' 
   UNION
	SELECT	[alias] = 'REP_NASTR', 
		[order] = convert(smallint, 99),
		[tab_name] = 'Настройки печати',
		[link_table] = convert(varchar(50), '0'),
		[table_type] = convert(smallint, -1)
	ORDER by [order]
end


/* Данные об отчете */
if @varKSnLink > 0
begin
  CREATE TABLE #REP_HEAD_temp ("checked" Int,"UPD" Int,"del" Int,"date" DateTime,"date_prov" DateTime,"link" Int,"period" VarChar(17),"name" VarChar(200),"code" Char(20),"Start_Date" Char(10),"link_saved_form" Int,"Link_form" Int,"Version" SmallInt,"begin_date" DateTime,"period_type" TinyInt,"period_type_web" Int,"period_number" TinyInt,"period_year" Int,"link_organization" Int,"dep_name" VarChar(254),"dep_code" Char(10),"isUpload" TinyInt,"isSvod" TinyInt,"isChangeAnalit" Bit,"IsRO" TinyInt,"Note" VarChar(4000),"Link_Type_Svod" Int,"Type_Svod" VarChar(250),"IsUsedRazdel" Int,"IsUsedCelSt" Int,"IsUsedRashod" Int,"LinkRazdel" Int,"LinkCelSt" Int,"LinkRashod" Int,"CodeRazdel" VarChar(1),"NameRazdel" VarChar(1),"CodeCelSt" VarChar(1),"NameCelSt" VarChar(1),"CodeRashod" VarChar(1),"NameRashod" VarChar(1),"Print_Object_Method" VarChar(200),"Query_Add_Module" VarChar(200),"Query_Before" VarChar(200),"Query_RepMaker" VarChar(200),"Query_Report" VarChar(200),"Query_Report_Path" VarChar(200),"Decript_Proc" VarChar(30),"IsRemoteAccess" TinyInt,"RULES" TinyInt,"isCalcItog" Int,"IsRO_MASK" Int,"CountSave" Int,"Object" VarChar(100),[IS_AUTOFILL] TINYINT,"IsCopy" BIT,"End_Date" Char(10), Query_Report_New varchar(250), Print_Object_Method_New varchar(250))
  CREATE TABLE #note (link INT, note_all TEXT)
  insert #REP_HEAD_temp 
	exec I_REPORT_USER_SAVED_FORM @varKSiLinkSF =@varKSnLink, @bIsWeb = 1 -- редактирование
        --обновим countsave из report_saved_tables
   --     IF @varKSnTree>0
   --             UPDATE #REP_HEAD_temp SET CountSave=coalesce((select top 1 countsave from REPORT_SAVED_TABLES where Link_Saved_Form=@varKSnLink and Link_Table=@varKSnTree),0)

   INSERT #note (link, note_all)
   EXEC dbo.RO_SAVED_FORM_NOTES @varKSnLink

  select @varKSnTree as Doc, @LinkTable as Link_Table, T.*, N.Note_All from #REP_HEAD_temp T, #note N
  drop table #REP_HEAD_temp
  DROP TABLE #note

   --атрибуты
    IF @atributs<>''
    begin
        exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,0
    end

	DECLARE @iLTable	INT,
		@cRuStr		varchar(8000), @TableName varchar(50), @TableName1 varchar(50)

	exec dbo.X_GET_TABLE_NAME  @TableName output

	select @iLTable = Link_Table from report_tables where Link_Form = (select Link_Form from report_saved_forms where Link_Saved_Form = @varKSnLink) and orders = @orderTable
	if @orderTable < 3
	begin
		if @orderTable = 1
			select @DocCode = Code from RT_FORM_RRO_PNUM where link = @varKSnTree
		else
			select @DocCode = Code from RT_FORM_RRO_PNUM2 where link = @varKSnTree
		SET @cRuStr = 'EXEC dbo.RI_PROC_T' + ltrim(convert(varchar(15),@iLTable)) + ' ' + convert(varchar(15), @varKSnLink) + ', @tmp_table = ''' + @TableName +''''

		print @cRuStr
		execute (@cRuStr)
		create table #CountRow (c int)
		insert #CountRow execute('select count(*) from '+ @TableName + ' where CHARINDEX(LEFT(''' + @DocCode +  ''' + ''        '',9), Code) > 0')
		set @CountRow = isnull((select c from #CountRow), 0)			

		exec dbo.X_GET_TABLE_NAME  @TableName1 output

		SET @cRuStr = 'select * from ' + @TableName + ' where CHARINDEX(LEFT(''' + @DocCode +  ''' + ''        '',9), Code) > 0 drop table ' + @TableName + '
EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + convert(varchar(15), @varKSnLink) + ', ''COL'', 2, @tmp_table = ''' + @TableName1 + '''
	select top ' + STR(@CountRow) + ' * from ' + @TableName1 + ' drop table ' + @TableName1
	end
	else begin	
		SET @cRuStr = 'EXEC dbo.RI_PROC_T' + ltrim(convert(varchar(15),@iLTable)) + ' ' + convert(varchar(15), @varKSnLink)
		SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + convert(varchar(15), @varKSnLink) + ', ''COL'', 2'
	end
	print @cRuStr
	execute (@cRuStr)
end
else
begin -- новый отчет
	exec I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg,1

   --атрибуты
    IF @atributs<>''
    begin
         set @varKSnLink = abs(@varKSnLink)
        exec RN_GET_ATRIBUT_VALUES  null, @varKSnLink,0
    end


end

/* Настройки печати */
DECLARE	@iLOrg	int,
	@DocDate	datetime
EXEC @iLOrg = getowndeplink 
IF @varKSnLink>0
	select @iLOrg = link_organization, @DocDate = begin_date from report_saved_forms where link_saved_form = @varKSnLink
ELSE
	select @DocDate = getdate()

select *, convert(char(10), @DocDate + 1, 104) as Doc_Date from dbo.PrintDoc_GetDepData2 (@iLOrg)


GO
GRANT ALL ON dbo.[RO_WEB_EDIT_FORMRRO] 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.[KU_MOVES_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_MOVES_SAVE]

GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE [dbo].KU_MOVES_SAVE
	@parLINK	int	OUTPUT,
	@parNumber  varchar(30),
	@parDate   datetime,
	@parSTAFF_LINK	INT,
	@parNUM_STAKE	numeric(3,2),
	@parSTATUS	int = null,
	@parDATE_BEGIN     DATETIME = null,
	@parDATE_END       DATETIME = null,
	@parTYPE         INT = null,
	@parREASON            VARCHAR(254) = null,
	@parETS_RAZR	INT = null,
	@parKONTR_DATE	DATETIME = null,
	@parKONTR_NUM	VARCHAR(15) = null,
	@parEMPL_LINK      INT = null,
	@parORDER_LINK INT = null,
	@parDEP_LINK int = null,
	@parORDER_STATUS int = 0,
	@parIO int = null
AS
DECLARE @ERROR tinyint, @trancount int, @SQLError int, @RowCount int, @comment varchar(254)

SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	
	IF @parDATE_BEGIN IS NULL or @parSTAFF_LINK is null or @parNUM_STAKE is null 
		or @parTYPE is null or @parTYPE=0 or @parNUM_STAKE<=0 or @parSTATUS is null
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @parDATE_BEGIN > @parDATE_END
		BEGIN
			ROLLBACK
			RETURN 107
		END
	-- ПРОВЕРКА НА ТО, ЧТО ДАТА НАЧАЛА НОВОЙ РАБОТЫ БОЛЬШЕ ДАТА ПРИЕМА НА НОВУЮ РАБОТУ -----------------------
	DECLARE @varDATE_BEGIN_WORK DATETIME
	SET @varDATE_BEGIN_WORK = (
				SELECT	TOP 1 DATE_BEGIN 
				FROM	ITEM_MOVE
				WHERE	EMPL_LINK = @parEMPL_LINK AND
					ACTIVE = 1
				ORDER BY DATE_BEGIN
				  )
	IF @parDATE_BEGIN <= @varDATE_BEGIN_WORK
	BEGIN
		ROLLBACK
		RETURN 114
	END
	----------------------------------------------------------------------------------------------------------
	IF isnull(rtrim(@parKONTR_NUM), '')='' SET @parKONTR_NUM = null

	IF @parDEP_LINK is null
		SELECT @parDEP_LINK = dep_link FROM user_dep
	
	SELECT @parORDER_LINK = link FROM ORDERS WITH (UPDLOCK) WHERE LINK = @parORDER_LINK
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	
	IF @RowCount = 0
	BEGIN
		SET @comment='О переводе '+dbo.ku_GetEmplFIO(@parEMPL_LINK)
		EXECUTE @ERROR = KU_ORDER_SAVE @parORDER_LINK OUTPUT, 2, @parNumber, @parDate, @comment, 0, @parDEP_LINK
		IF @ERROR <> 0
			RETURN @ERROR
	END

	IF @parLINK is null OR @parLINK = 0
	BEGIN
		INSERT INTO item_move WITH (ROWLOCK) (new_face, staff_link, num_stake, status, date_begin, date_end2, type, reason,
								ets_razr, kontr_date, kontr_num, empl_link, order_link,[io])
			VALUES (0, @parSTAFF_LINK, @parNUM_STAKE, @parSTATUS, 
				@parDATE_BEGIN, @parDATE_END, @parTYPE, @parREASON, @parETS_RAZR, @parKONTR_DATE, @parKONTR_NUM, @parEMPL_LINK, @parORDER_LINK,@parIO)
		SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	ELSE
	BEGIN
		UPDATE item_move SET new_face=0, staff_link=@parSTAFF_LINK, num_stake=@parNUM_STAKE, status=@parSTATUS, date_begin=@parDATE_BEGIN, date_end2=@parDATE_END, type=@parTYPE, 
				reason=@parREASON, ets_razr=@parETS_RAZR, kontr_date=@parKONTR_DATE, kontr_num=@parKONTR_NUM, empl_link=@parEMPL_LINK, order_link=@parORDER_LINK, [io]=@parIO
		WHERE link=@parLINK
		SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @RowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END

		UPDATE money_period SET date_begin = @parDATE_BEGIN WHERE item_link = @parLINK
		SELECT @SQLError = @@ERROR
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF not exists(SELECT * FROM oklad_pays WHERE dep_link=@parDEP_LINK) BEGIN
		ROLLBACK
		RETURN 113
	END

	IF @parORDER_STATUS=1
		UPDATE orders SET status = 1 WHERE link=@parORDER_LINK

IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[KU_MOVES_SAVE] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_VAC_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_VAC_FILL]

GO

CREATE   PROCEDURE dbo.SA_N_VAC_FILL 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @OBJ_CODE VARCHAR(50), --Код объекта
 @SR_VID TINYINT = 1, -- Прочие расчеты по среднему 1 - Компенсация за отпуск, 2 - прочее
 @LINK_VAC INT, --Ссылка на приказ
 @SR_LINK_EMPL INT  = NULL, --Прочие расчеты по среднему  Ссылка на сотрудника
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT  = NULL, --Тип расчетного периода: 1- 3 месяца, 2 - 12 месяцев
 @PAYMENT TINYINT  = NULL,-- Способ расчета 1 - в рабочих днях, 2 - в календарных днях
 @SR_DATE1 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала
 @SR_DATE2 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата окончания
 @SR_DATE DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала расчетного периода
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

---инит
DECLARE 
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME --Начало отпуска, командировки

IF ( --для госслужащих начисление отпускных или расчет компенсации отпускных
		( 	RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH' 
		OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1
		)
		AND dbo.sa_get_option_by_code('FURLOUGH_OPT10') = 1 --Специальный расчет для муниципальных и государственных гражданских служащих
	)
	OR
	( --для госслужащих начисление командировочных
		RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL ' 
		AND dbo.sa_get_option_by_code('CALC_TRAVEL_OPT6') = 1 --Специальный расчет для муниципальных и государственных гражданских служащих
	)
BEGIN

	IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH'
	BEGIN
		SELECT @LINK_EMPL = EMPL_LINK, @DATE_BEGIN = DATE_BEGIN
		FROM dbo.ORDERS O INNER JOIN dbo.ITEM_VACATION IV ON IV.ORDER_LINK = O.LINK
		WHERE IV.LINK = @LINK_VAC
	END

	IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL'
	BEGIN
		SELECT @LINK_EMPL = EMPL_LINK, @DATE_BEGIN = DATE_BEGIN
		FROM dbo.ORDERS O INNER JOIN dbo.ITEM_TRAVEL IV ON IV.ORDER_LINK = O.LINK
		WHERE IV.LINK = @LINK_VAC
	END

	IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
	BEGIN
		SELECT @LINK_EMPL = @SR_LINK_EMPL, @DATE_BEGIN = @SR_DATE1
	END

	IF EXISTS (
		Select s.GOSSL 
		FROM 
			dbo.EMPL E
			LEFT JOIN dbo.EMPL_STAFF1(@DATE_BEGIN) d on e.link = d.empl_link
			LEFT JOIN staff S ON s.link = D.STAFF_LINK
		WHERE 
			E.LINK = @LINK_EMPL AND ISNULL(s.GOSSL,0) IN (0,7,8,2,4) )
	--Расчет по 922 приказу
		EXEC dbo.SA_N_VAC_FILL1 @LINK_DOC OUT, @OBJ_CODE, @SR_VID, @LINK_VAC, @SR_LINK_EMPL, @LINK_PAYS, @TYP_PERIOD, @PAYMENT, @SR_DATE1, @SR_DATE2, @SR_DATE, @RECALC, @OPER, @LINK_DEP
	ELSE 	--Расчет по 562 постановлению
		EXEC dbo.SA_N_VAC_FILL2 @LINK_DOC OUT, @OBJ_CODE, @SR_VID, @LINK_VAC, @SR_LINK_EMPL, @LINK_PAYS, @TYP_PERIOD, @PAYMENT, @SR_DATE1, @SR_DATE2, @SR_DATE, @RECALC, @OPER, @LINK_DEP

END
ELSE
	--Расчет по 922 приказу
	EXEC dbo.SA_N_VAC_FILL1 @LINK_DOC OUT, @OBJ_CODE, @SR_VID, @LINK_VAC, @SR_LINK_EMPL, @LINK_PAYS, @TYP_PERIOD, @PAYMENT, @SR_DATE1, @SR_DATE2, @SR_DATE, @RECALC, @OPER, @LINK_DEP



GO


GRANT EXECUTE ON dbo.[SA_N_VAC_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_EXPORT_86N_003]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_86N_003]
END
GO
 
/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_86N_003]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @iReturn INT 

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

-- создание временных табличек
CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                        ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета

CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении

CREATE TABLE #tab003
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT         -- Значение на финансовый год, на который утверждается план ФХД
   ,[planFirstYear] INT          --Первый год планового периода
   ,[planLastYear] INT        --Второй год планового периода
)

CREATE TABLE #tab003_FHD
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код показателя
   ,[SUMMA1] NUMERIC(20,2) -- Значение на финансовый год, на который утверждается план ФХД          
   ,[SUMMA2] NUMERIC(20,2) -- Значение показателя на первый год планового периода
   ,[SUMMA3] NUMERIC(20,2) -- Значение показателя на второй год планового периода
)

Create index #IX_tab003 on #tab003 (ID)
Create index #IX_tab003_FHD on #tab003_FHD (ID)

CREATE TABLE #tabXML ([TXT] VARCHAR(8000), [ORDERS] INT IDENTITY(1,1), ID UNIQUEIDENTIFIER) 

INSERT #tabHead (DATE, ID)
SELECT GETDATE(), NEWID()

-- получение данных
EXEC dbo.[RO_EXPORT_86N_GET_DATA] @iLINK_SAVED_FORM, 3

-- формирование xml 
EXEC dbo.[RO_EXPORT_86N_GET_XML] 3

IF EXISTS(SELECT * FROM #tabXML)
BEGIN 
   SELECT @vcFILE_NAME = RTRIM(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(100), [ID]),'-',''), '}', ''), '{', ''))
   FROM #tabHead

   INSERT #FileExportReport([TXT],
                            [NameFile],
                            [ORDERS],
                            [NameFileArh])
   SELECT [TXT],
	       @vcFILE_NAME + '.xml',
	       [ORDERS],
          @vcFILE_NAME  + '.zip'
   FROM #tabXML
   ORDER BY [ORDERS]

   SET @vcFILE_NAME = @vcFILE_NAME + '.xml'
END 

DROP TABLE #tabHead
DROP TABLE #tab001
DROP TABLE #tab003
DROP TABLE #tab003_FHD
DROP TABLE #tabXML

GO
GRANT ALL ON dbo.[RO_EXPORT_86N_003] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RK_CALC_TN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RK_CALC_TN]

GO

-- Расчет транспотного налога
CREATE PROCEDURE dbo.RK_CALC_TN
	@intDEP_LINK	INT,		-- !!!ПАРАМЕТР!!! ---
	@PERIOD_BEGIN	DATETIME,	-- НАЧАЛО НАЛОГОВОГО ПЕРИОДА
	@PERIOD_END	DATETIME	-- КОНЕЦ НАЛОГОВОГО ПЕРИОДА,
AS 
BEGIN

	DECLARE 
		@intPERIOD_MONTH	INT, 
		@REC_NO INT,
		@DATE_REG DATETIME,
		@DATE_UNREG DATETIME,
		@COL6 NUMERIC (10,2),	-- МОЩНОСТЬ
		@COL9 NUMERIC (10,2),
		@COL10 NUMERIC (10,2), 	-- СТАВКА ТРАНС. НАЛОГА
		@COL11 NUMERIC (20,2), 	-- СУММА НАЛОГА ТС
		@COL114 NUMERIC (20,2), 	-- СУММА К УПЛАТЕ
		@MONTH_USED INT,
		@DATECALC_BEGIN DATETIME,
		@DATECALC_END DATETIME,
		@intORDERS	INT
	
-- exec RK_CALC_TN 74578, '20090401', '20090630'
/*
SELECT dbo.GetOwnDepLink ()

	SET @intDEP_LINK = dbo.GetOwnDepLink ()
	SET @PERIOD_BEGIN = '20060101'
	SET @PERIOD_END = '20091231'
*/	
	SET @intPERIOD_MONTH = DATEDIFF (MONTH, @PERIOD_BEGIN, @PERIOD_END) + 1
--	SELECT @intPERIOD_MONTH
	
	DECLARE @TAB_RET TABLE (REC_NO INT IDENTITY,
				COL2 VARCHAR (10), 	-- вид ТС
				COL3 VARCHAR (30), 	-- VIN ТС
				COL4 VARCHAR (100), 	-- МАРКА ТС
				COL5 VARCHAR (20), 	-- НОМЕР ТС
				COL6 NUMERIC (10,2),	-- МОЩНОСТЬ
				COL7 VARCHAR (20), 	-- ЕИ(КОД) МОЩНОСТИ ТС
				COL8 INT, 		-- СРОК ИСПОЛЬЗОВАНИЯ ТС
				COL9 NUMERIC (10,2), 	-- КОЭФФИЦИЕНТ ТС
				COL10 NUMERIC (10,2), 	-- СТАВКА ТРАНС. НАЛОГА
				COL11 NUMERIC (20,2), 	-- СУММА НАЛОГА ТС
				COL12 VARCHAR (10), 	-- КОД НАЛОГОВОЙ ЛЬГОТЫ ТС
				COL13 NUMERIC (20,2), 	-- СУММА ЛЬГОТЫ
				COL14 NUMERIC (20,2), 	-- СУММА К УПЛАТЕ
				DATE_REG DATETIME,	-- ДАТА РЕГИСТРАЦИИ ТС
				DATE_UNREG DATETIME,	-- ДАТА СНЯТИЯ ТС,
				MONTH_USED	NUMERIC (10,2),
				ORDERS INT DEFAULT (0)
		)
	
	INSERT INTO @TAB_RET (COL2, COL3, COL4, COL5, COL6, COL7,
			COL8, COL9, COL10, COL11, COL12,
			COL13, COL14,
			DATE_REG, DATE_UNREG
	)
	
	SELECT ISNULL (dbo.BV_GetInvChar3 (LINK, DEFAULT, 'GROUP_CODE'), ''),	-- вид ТС
		ISNULL (dbo.BV_GetInvChar3 (LINK, DEFAULT, 'VIN_CODE'), ''),	-- VIN ТС
		ISNULL (dbo.BV_GetInvChar3 (LINK, DEFAULT, 'AUTO_MARK'), ''),	-- МАРКА ТС
		ISNULL (dbo.BV_GetInvChar3 (LINK, DEFAULT, 'AUTO_NUM'), ''),	-- ГОС. НОМЕР ТС
		ISNULL (dbo.BV_GetInvChar4 (LINK, DEFAULT, 'HORSEPOWER'), 0),	-- МОЩНОСТЬ
	        '251',	-- ЕИ ТС,
		0, 0, 
		ISNULL (dbo.BV_GetInvChar4 (LINK, DEFAULT, 'STAVKA_TNALOG'), 0),	-- СТАВКА ТРАНС. НАЛОГА
		0,
	'', --	ISNULL (dbo.BV_GetInvChar3 (LINK, DEFAULT, 'AUTO_NUM'), ''),	-- КОД НАЛОГОВОЙ ЛЬГОТЫ ТС
		0,
		0,
		dbo.BV_GetInvChar1 (LINK, DEFAULT, 'DATE_REG_TC'), 	-- ДАТА РЕГИСТРАЦИИ ТС
		dbo.BV_GetInvChar1 (LINK, DEFAULT, 'DATE_UNREG_TC')	-- ДАТА СНЯТИЯ ТС,
	FROM dbo.INVENTORY_CARD
	WHERE DEP_LINK = @intDEP_LINK
		AND CODE_GRP LIKE '101_5%'

--select * from @TAB_RET
	
	/* -- РАСЧЕТ -- */
	SET @intORDERS = 0
	DECLARE #CALC_CURSOR CURSOR FOR
		SELECT REC_NO, DATE_REG, DATE_UNREG 
			FROM @TAB_RET
			WHERE (DATE_REG IS NULL
					OR DATE_REG <= @PERIOD_END)
				AND (DATE_UNREG IS NULL
					OR DATE_UNREG >= @PERIOD_BEGIN)
				AND COL6 > 0
	OPEN #CALC_CURSOR
	FETCH #CALC_CURSOR
		INTO @REC_NO, @DATE_REG, @DATE_UNREG
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @DATECALC_BEGIN = CASE
						WHEN @DATE_REG BETWEEN @PERIOD_BEGIN AND @PERIOD_END THEN @DATE_REG
						WHEN @DATE_REG < @PERIOD_BEGIN THEN @PERIOD_BEGIN
					END
	
		SET @DATECALC_END = CASE
						WHEN @DATE_UNREG IS NULL OR @DATE_UNREG > @PERIOD_END THEN @PERIOD_END
						WHEN @DATE_UNREG BETWEEN @PERIOD_BEGIN AND @PERIOD_END THEN @DATE_UNREG
					END
	
		SET @COL9 = CONVERT (NUMERIC (10,2), (DATEDIFF (MONTH, @DATECALC_BEGIN, @DATECALC_END) + 1))/@intPERIOD_MONTH
		SET @COL9 = ISNULL (@COL9, 0)
	
		SET @intORDERS = @intORDERS + 1

		UPDATE @TAB_RET SET COL9 = @COL9, COL11 = @COL9 * COL6 * COL10,
					ORDERS = @intORDERS 
		WHERE REC_NO = @REC_NO
	
		UPDATE @TAB_RET SET COL14 = COL11 - COL13
		WHERE REC_NO = @REC_NO
	
		FETCH #CALC_CURSOR
			INTO @REC_NO, @DATE_REG, @DATE_UNREG
	END
	CLOSE #CALC_CURSOR
	DEALLOCATE #CALC_CURSOR
	
	SELECT RIGHT ('000' + RTRIM (CONVERT (VARCHAR (20), ORDERS)), 3) AS CODE, 
		RIGHT ('000' + RTRIM (CONVERT (VARCHAR (20), ORDERS)), 3) AS COL1,
		COL2, COL3, COL4, COL5, COL6, COL7, 
		COL8, COL9, COL10, COL11, COL12, COL13, COL14
	FROM @TAB_RET
	WHERE ORDERS > 0
	ORDER BY ORDERS
END


GO


GRANT EXECUTE ON dbo.[RK_CALC_TN] TO PUBLIC

GO


--Расширенные свойства--


GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_EXPORT_FORM_CALC]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].BB_EXPORT_FORM_CALC
GO


/*
© Кейсистемс (Keysystems), 2006
*/

CREATE PROCEDURE dbo.BB_EXPORT_FORM_CALC @cCalcFormID varchar(100)	

as

-- ВЫГРУЗКА расчетов
DECLARE @iCalcLink INT,
		@cFormCode varchar(50),
		@cFormDate varchar(8),
		@iCalcFormLink int
		
	
declare @tTemp table ([TEXT] varchar(8000), ord int identity)
declare @curCalc cursor  

--SELECT * FROM dbo.RB_CALC_NASTR

SET @curCalc = CURSOR FORWARD_ONLY FOR 
SELECT LINK from dbo.BufferGetTableByID(@cCalcFormID)


OPEN @curCalc	
FETCH NEXT FROM @curCalc INTO @iCalcFormLink
while @@fetch_status = 0
begin

	select @cFormDate = rtrim(convert(char(8),FORM_DATE,112)), @cFormCode = rtrim(FORM_CODE) from RB_CALC_NASTR where LINK = @iCalcFormLink
	insert into @tTemp([TEXT])
	SELECT 'DECLARE @iCalcFormLink INT,
			@iCalcLink INT
			
	delete RCF
	FROM dbo.REPORT_CALC_FORMS RCF
	inner join dbo.REPORT_CALC RC on RC.LINK_UP = RCF.LINK and RC.[isUSER] = 0
	inner join dbo.REPORT_FORMS RF on RCF.LINK_FORM = RF.Link_Form 
	WHERE RF.CODE = ''' + @cFormCode + ''' AND RF.START_DATE = ''' + @cFormDate + ''' and RCF.[ORDER] = ' + LTRIM(str([ORDER])) + ' and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ''' + rtrim(dbo.BB_CALC_GET_ATR_VAL(LINK,FORM_LINK ,1)) + '''


	UPDATE RCF 
	set [ORDER] = 1
	FROM dbo.REPORT_CALC_FORMS RCF
	inner join dbo.REPORT_CALC RC on RC.LINK_UP = RCF.LINK and RC.[isUSER] = 1
	inner join dbo.REPORT_FORMS RF on RCF.LINK_FORM = RF.Link_Form 
	WHERE RF.CODE = ''' + @cFormCode + ''' AND RF.START_DATE = ''' + @cFormDate + ''' and RCF.[ORDER] = ' + LTRIM(str([ORDER])) + ' and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ''' + rtrim(dbo.BB_CALC_GET_ATR_VAL(LINK,FORM_LINK ,1)) + '''

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, ' + LTRIM(str(USED)) + ',' + LTRIM(str([ORDER])) + ',''' + RTRIM(COMMENT) + '''
	from dbo.REPORT_FORMS where CODE = ''' + @cFormCode +  ''' AND [START_DATE] = ''' + @cFormDate + ''' 
	SET @iCalcFormLink = @@IDENTITY
	'
	--select * 
	FROM dbo.RB_CALC_NASTR 
	WHERE LINK = @iCalcFormLink




	insert into @tTemp([TEXT])
	SELECT 'INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, ''' + RTRIM(CODE_ATR) + ''', ''' + isnull(RTRIM(STR_VAL),'NULL') + ''', ' + isnull(LTRIM(str(INT_VAL)),'NULL') + ')'
	FROM dbo.REPORT_CALC_ATRIBUTE 
	WHERE LINK_CALC_FORM = @iCalcFormLink


	DECLARE CALC_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT DISTINCT LINK 
	FROM dbo.REPORT_CALC
	WHERE LINK_UP = @iCalcFormLink

	OPEN CALC_CUR
	FETCH NEXT FROM CALC_CUR INTO @iCalcLink

	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into @tTemp([TEXT])
		SELECT 'set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, ''' + RTRIM(Code_Row) + ''','  + LTRIM(STR(IsUser)) + ','  + LTRIM(STR(Calc_Order)) + ',''' + RTRIM(Comment) + '''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = ' + RTRIM(ORDER_COL) + '
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = ''' + LTRIM(STR(ORDERS)) + '''
			
			SET @iCalcLink = @@IDENTITY
		'
		FROM dbo.RO_CALC
		WHERE LINK = @iCalcLink
		--select @varKSBlockLink

		insert into @tTemp([TEXT])
		select '	INSERT INTO REPORT_CALC_ROWS (Link_Calc, Orders, [Sign], DT_Mask, KT_Mask, DT_EKR, KT_EKR, Type_KBK, [Type], Mask_KBK, DT_KT)
		SELECT @iCalcLink, ' + LTRIM(STR(ORDERS)) + ',' + LTRIM(STR([Sign])) + ',''' + RTRIM(DT_Mask) + ''',''' + RTRIM(KT_Mask) + ''',''' + 
		RTRIM(DT_EKR) + ''',''' + RTRIM(KT_EKR) + ''',' + LTRIM(STR(Type_KBK)) + ',' + LTRIM(STR(Type)) + ',''' + RTRIM(Mask_KBK) + ''',' + LTRIM(STR(DT_KT))
		FROM dbo.REPORT_CALC_ROWS 
		WHERE LINK_CALC = @iCalcLink
		order by ORDERS

		FETCH NEXT FROM CALC_CUR INTO @iCalcLink
	END
	CLOSE CALC_CUR
	DEALLOCATE CALC_CUR

	insert into @tTemp ([TEXT])
	select 'GO'
	FETCH NEXT FROM @curCalc INTO @iCalcFormLink

end
CLOSE @curCalc
DEALLOCATE @curCalc

SELECT [TEXT] from @tTemp order by ord

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_BASE_SUM_PAY_DIF_PERIODS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_BASE_SUM_PAY_DIF_PERIODS]

GO


CREATE   PROCEDURE dbo.SD_BASE_SUM_PAY_DIF_PERIODS
---Расчет базовых сумм для расчета отпускных по общей инструкции
 @varKSRefPay 	int,
 @varKSlinkEmpl	 int,
 @varKSdDate1	datetime,
 @varKSdDate2	datetime,		 
 @ObjCode	varchar(254) = NULL,
 @varKSdDate3	datetime = NULL, --Начало отпуска 
 @varKSdDate4	datetime = NULL  --Конец расчетного периода
AS  

declare @nFURLOUGH_OPT1  Int	-- Мат. помощь учитывать как премию
Set @nFURLOUGH_OPT1 = [dbo].[sa_get_option_by_code]('FURLOUGH_OPT1')

Set @ObjCode = COALESCE(@ObjCode,'')
Set @varKSdDate3 = COALESCE(@varKSdDate3,'30000101')
Set @varKSdDate4 = COALESCE(@varKSdDate4,'30000101')

declare @FURLOUGH_OPT5  Int
Set @FURLOUGH_OPT5 = [dbo].[sa_get_option_by_code]('FURLOUGH_OPT5')
Set @FURLOUGH_OPT5 = case when @FURLOUGH_OPT5 = 0 then 12 else @FURLOUGH_OPT5 end

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

Select LINK_EMPL, SJ.LINK_PAYS, SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.WAY_CALC, SJ.SUMMA, LINK_VKR, 
--	PERIOD_BEGIN = CASE WHEN COALESCE(AP.LINK_UP,0) = 0 AND (SJ.WAY_CALC in (6,7,12) OR COALESCE(R.LINK_UP,0) <> 0) THEN SJ.DATE1 ELSE PERIOD_BEGIN END, 
--	PERIOD_END = CASE WHEN COALESCE(AP.LINK_UP,0) = 0 AND (SJ.WAY_CALC in (6,7,12) OR COALESCE(R.LINK_UP,0) <> 0) THEN SJ.DATE2 ELSE PERIOD_END END, 
	PERIOD_BEGIN = CASE WHEN COALESCE(R.LINK_UP,0) <> 0 AND @DOCUMENTS_RECALC_OPT1 = 1 THEN SJ.DATE1 ELSE PERIOD_BEGIN END, 
	PERIOD_END = CASE WHEN COALESCE(R.LINK_UP,0) <> 0 AND @DOCUMENTS_RECALC_OPT1 = 1 THEN SJ.DATE2 ELSE PERIOD_END END, 
	SJ.DATE1, SJ.DATE2, Option_CV
into #tmpCJ 
from dbo.S_J_C_Short SJ INNER JOIN dbo.PAYS P ON SJ.LINK_PAYS = P.LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
	--Сыммы по начислению процентом учитывать в месяце, в котором рассчитвали
	LEFT JOIN dbo.SDOC_APER AP ON SJ.LINK_DOC = AP.LINK_UP 
where LINK_EMPL = @varKSlinkEmpl

---
declare @mat_period table (period datetime)

IF @FURLOUGH_OPT5 <> 12 
--Определим, за какие месяцы надо брать мат помощь.
Begin
	Set rowcount @FURLOUGH_OPT5
	
		insert into @mat_period (period)
		SELECT SJ.PERIOD_BEGIN
		FROM #tmpCJ SJ INNER JOIN dbo.group_pays(@varKSRefPay) T ON SJ.link_PAYS=T.PAY_LINK
		WHERE 
			SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.PERIOD_BEGIN>=dbo.DateBeginOfMonth(DATEADD(Month,-12,@varKSdDate4))
			and SJ.PERIOD_END <= dbo.DateEndOfMonth(@varKSdDate3) AND SJ.WAY_CALC = 12
		order by SJ.PERIOD_BEGIN desc
	
	Set rowcount 0
END

DECLARE @E_FIN TABLE (LINK_EMPL INT, LINK_KBK INT)
INSERT INTO @E_FIN (LINK_EMPL,LINK_KBK)
SELECT TOP 1 empl_link, LINK_KBK FROM DBO.SA_EMPLS_INFO(@varKSdDate3, @varKSlinkEmpl)

/*промежуточный результат*/
declare @tbl table (PERIOD_BEGIN DATETIME, CODE_PAY varchar(10), NAME_PAY varchar(60), WAY_CALC tinyint, LINK_PAY int, summa numeric(18,2), LINK_VKR INT, DATE1 DATETIME, DATE2 DATETIME)
insert into @tbl(PERIOD_BEGIN, CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,summa, LINK_VKR, DATE1, DATE2)
SELECT 			CONVERT(VARCHAR(8),((YEAR(PERIOD_BEGIN) * 100 + MONTH(PERIOD_BEGIN)) * 100 + 1)),
			[CODE_PAY]		= CODE_PAYS, 
			[NAME_PAY]		= NAME_PAYS, 
			[WAY_CALC]		= (Case when @nFURLOUGH_OPT1 = 1 and RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' and WAY_CALC = 12 then 7 else WAY_CALC end), 
			[LINK_PAY]		= SJ.link_PAYS ,
			[SUMMA]			= SUM(SJ.summa), 
			LINK_VKR 		= COALESCE(LINK_VKR,DEF.LINK_KBK), 
			DATE1, 
			DATE2	

FROM #tmpCJ SJ INNER JOIN dbo.group_pays(@varKSRefPay) T ON SJ.link_PAYS=T.PAY_LINK
	LEFT JOIN @E_FIN DEF ON DEF.LINK_EMPL = SJ.LINK_EMPL
WHERE 
	SJ.LINK_EMPL = @varKSlinkEmpl 
	AND SJ.PERIOD_BEGIN>=@varKSdDate1
	AND
	(	SJ.PERIOD_END<=@varKSdDate2 
		OR /*В начислении отпускных при определении заработка за последний расчетный месяц 
			брать метериальную помощь с признаком также из месяца начала отпуска*/
		RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 
				and Year(@varKSdDate4) = Year(@varKSdDate2) and Month(@varKSdDate4) = Month(@varKSdDate2)
				and Year(SJ.PERIOD_END) = Year(@varKSdDate3) and Month(SJ.PERIOD_END) = Month(@varKSdDate3)
	)
	AND
	(
		@FURLOUGH_OPT5 <> 12 and RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 
			and SJ.PERIOD_BEGIN in (Select period from @mat_period)
		OR
		NOT (@FURLOUGH_OPT5 <> 12 AND RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 )
	)

GROUP BY  CONVERT(VARCHAR(8),((YEAR(PERIOD_BEGIN) * 100 + MONTH(PERIOD_BEGIN)) * 100 + 1)), SJ.link_PAYS, CODE_PAYS, NAME_PAYS, WAY_CALC, COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2	 

/*Перечень сотрудников, которым НЕ нужно индексировать*/
DECLARE @NO_INDEX_EMPL table (link int)
INSERT INTO @NO_INDEX_EMPL (link)
SELECT LINK_EMPL FROM dbo.GROUPS_EMPL G inner join dbo.GROUPS_EMPL_REF E on E.LINK_GROUP = G.LINK
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT4')

/*Перечень надбавок, которые НЕ нужно индексировать*/
DECLARE @NO_INDEX_PAY table (link int)
INSERT INTO @NO_INDEX_PAY (link)
SELECT P.link
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT3')

/*Перечень надбавок, которые нужно индексировать*/
DECLARE @nadbavki table (link int)
INSERT INTO @nadbavki (link)
SELECT P.link 
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT1')
	AND P.link NOT IN (SELECT LINK FROM @NO_INDEX_PAY)

DECLARE @TI numeric(18,4)
DECLARE @INDEX_OPT2 int
Set @INDEX_OPT2 = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT2')

/*Заготовки для вычисления коэффициентов*/
declare @pn3 table (link_pay int, way_calc int, summa numeric(18,2))
declare @pn2 table (link_pay int, period datetime, summa numeric(18,2))
declare @koef table (link_pay int, period datetime, koef numeric(18,4))
/*Здесь коэффициенты тарифных ставок*/
declare @koef_ts table (link_pay int, period datetime, koef numeric(18,4))

IF (@INDEX_OPT2 = 2 OR @INDEX_OPT2 = 3 OR EXISTS (Select * from @nadbavki)) 
	AND @varKSlinkEmpl NOT IN (SELECT LINK FROM @NO_INDEX_EMPL)
BEGIN
	IF @INDEX_OPT2 = 3
		insert into @nadbavki (link) 
		Select distinct PE.link_pays from dbo.PAYS_EMPL PE 
		where PE.LINK_EMPL = @varKSlinkEmpl and PE.link_pays not in (select link from @nadbavki)

	--Размер постоянных начислений на момент начала отпуска
	insert into @pn3 (link_pay, way_calc, summa)
	Select link_pays, way_calc, sum(summa *ndays/wdays) from dbo.sa_all_pays_all(@varKSlinkEmpl,@varKSdDate3,null,DEFAULT,DEFAULT) 
	where  @varKSdDate3 between date_begin and coalesce(date_end,@varKSdDate3) and wdays <> 0
	group by link_pays, way_calc

	-- Для месяцев расчетного периода рассчитаем коеффициенты индексации
	DECLARE @Cur1 CURSOR, @PER DATETIME
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR Select DATE_BEGIN FROM dbo.months_ex(@varKSdDate1, @varKSdDate3)
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @PER
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			insert into @pn2 (link_pay, period, summa)
			Select link_pays, @PER, sum(summa) 
			from dbo.sa_all_pays_all(@varKSlinkEmpl, @PER,null, DEFAULT,DEFAULT)
			group by link_pays
		END
		FETCH NEXT FROM @Cur1 INTO @PER
	END
	
	CLOSE @Cur1 
	DEALLOCATE @Cur1

	--Здесь коэффициенты индексации оклада
	insert into @koef_ts (link_pay, period, koef)
	select D1.LINK_PAY, D2.period, Koef = Sum(coalesce(D1.summa,0) / coalesce(D2.summa,coalesce(D1.summa,0.0000001)))
	from  @pn3 D1 inner join @pn2 D2 on D1.LINK_PAY = D2.LINK_PAY and D1.WAY_CALC in (1,2,20)
	where	@INDEX_OPT2 = 2 and coalesce(D2.summa,0) <> 0 and (coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))) > 1 
	group by D1.LINK_PAY, D2.period 

	--Здесь коэффициенты индексации надбавок
	insert into @koef (link_pay, period, koef)
	select D1.LINK_PAY, d2.period, Koef = coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))
	from  @pn3 D1 inner join @pn2 D2 on D1.LINK_PAY = D2.LINK_PAY inner join @nadbavki N on D1.LINK_PAY = N.link
	where	coalesce(D2.summa,0) <> 0 and (coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))) > 1 

	--Здесь коэффициенты индексации прочих видов оплат, не являющихся постоянными начислениями
	IF @INDEX_OPT2 = 3
	BEGIN
		DECLARE @Cur2 CURSOR, @LINK_PAY INT
		SET @Cur2 = CURSOR FORWARD_ONLY
	
		FOR select distinct link from dbo.Pays P inner join @tbl J on P.LINK = J.LINK_PAY INNER JOIN dbo.WAY_CALC WC ON P.WAY_CALC = WC.CODE where object = 1 AND WC.TYPE = 1 AND isPercent = 1 AND P.LINK not in (select link from @nadbavki)
		
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @LINK_PAY
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				insert into @koef (link_pay, period, koef)
				select @LINK_PAY, PERIOD_BEGIN,
					CASE WHEN SUM(coalesce(summa,0)) <> 0 THEN 
						SUM(convert(numeric(18,6),coalesce(summa,0)) * (case when coalesce(K.Koef,1) > 1 then coalesce(K.Koef,1) else 1 end)) / SUM(coalesce(summa,0.0000001))
					ELSE 1 END
				FROM @tbl T inner join (Select distinct PAY_LINK from dbo.group_pays(@LINK_PAY) ) BASE ON BASE.PAY_LINK = T.link_pay
					LEFT join @koef K on T.link_pay = K.link_pay AND Year(K.Period) = Year(T.DATE1) AND Month(K.Period) = Month(T.DATE1)
				WHERE	NOT EXISTS (Select * from @koef where link_pay = @LINK_PAY AND period = PERIOD_BEGIN)
				GROUP BY PERIOD_BEGIN
				ORDER BY PERIOD_BEGIN
			END
		
			FETCH NEXT FROM @Cur2 INTO @LINK_PAY
		END
		
		CLOSE @Cur2
		DEALLOCATE @Cur2
	END
END 

IF @INDEX_OPT2 = 1 AND @varKSlinkEmpl NOT IN (SELECT LINK FROM @NO_INDEX_EMPL)
	insert into @koef_ts (link_pay, period, koef)
	Select distinct link, M.DATE_BEGIN, dbo.SA_TARIF_INDEX(dbo.DateEndOfMonth(M.DATE_BEGIN), @varKSdDate3)  
	from dbo.pays, dbo.months_ex(@varKSdDate1, @varKSdDate2) M 
	where object = 1 
		AND @INDEX_OPT2 = 1
		AND link NOT IN (SELECT LINK_PAY FROM @koef)

/*вывод базовых начислений с учетом индексации тарифных ставок*/
select PERIOD_BEGIN, 0 as Nadb, T.CODE_PAY, T.NAME_PAY, T.WAY_CALC, T.LINK_PAY, 
summa= Convert(numeric(18,4),coalesce(summa,0)) * case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end, 
sum0= coalesce(summa,0), 
Koef= case when coalesce(K.Koef,1) > 1  and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end, 
COALESCE(Option_CV,0) CV, LINK_VKR, DATE1, DATE2
into #tmp
from @tbl T inner join dbo.PAYS P on T.link_pay = P.link
	left join (SELECT PERIOD, MAX(KOEF) AS KOEF FROM @koef_ts GROUP BY PERIOD) K on YEAR(T.PERIOD_BEGIN) = YEAR(K.PERIOD) and MONTH(T.PERIOD_BEGIN) = MONTH(K.PERIOD)
	left join @NO_INDEX_PAY NI ON NI.LINK = P.LINK
where	
	not exists (Select K1.link_pay from @koef K1 where K1.link_pay = T.link_pay and coalesce(K1.Koef,1) > (coalesce(K.Koef,1)))

--Результат
CREATE TABLE #OUT_TABLE (
	PERIOD DATETIME,
	NADB NUMERIC(18,2),
	CODE_PAY VARCHAR(254),
	NAME_PAY VARCHAR(254), 
	WAY_CALC INT,
	LINK_PAY INT,
	SUMMA NUMERIC(18,2),
	SUM0 NUMERIC(18,2),
	KOEF  NUMERIC(18,4),
	CV	NUMERIC(18,2),
	LINK_VKR INT,
	DATE1 DATETIME,
	DATE2 DATETIME
)

--вывод базовых начислений с учетом индексации спец. надбавок (премии и т.д.)
INSERT INTO #OUT_TABLE (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
Select PERIOD_BEGIN, Nadb,CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,summa,sum0,Koef,CV, LINK_VKR, DATE1, DATE2
from #tmp

--union all 
--Оклад и др. постоянные начисления
INSERT INTO #OUT_TABLE (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
select PERIOD_BEGIN, 1 as Nadb, T.CODE_PAY,T.NAME_PAY,T.WAY_CALC, T.LINK_PAY, 
	summa= convert(numeric(18,4),coalesce(summa,0)) * (case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end), 
	sum0= coalesce(summa,0),
	Koef= (case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end), 
	0 CV, LINK_VKR, DATE1, DATE2
from 
	@tbl T LEFT join @koef K on T.link_pay = K.link_pay AND Year(K.Period) = Year(T.PERIOD_BEGIN) AND Month(K.Period) = Month(T.PERIOD_BEGIN)
	left join @NO_INDEX_PAY NI ON NI.LINK = T.link_pay
where	
	T.link_pay not in (Select link_pay from #tmp where #tmp.PERIOD_BEGIN = T.PERIOD_BEGIN)
order by PERIOD_BEGIN, CODE_PAY, LINK_VKR

--Расчёт коэффициента индексации для районного и северного
DECLARE 
	@LINK_RAYON INT, 
	@LINK_SEVER INT, 
	@REGION_VAL NUMERIC(18,4), 
	@REGION_SUM NUMERIC(18,2), 
	@Y INT, 
	@M INT, 
	@LINK_SFIN INT,  
	@TMP_DATE DATETIME

SET @LINK_RAYON = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPTIONS3_1')
SET @LINK_SEVER = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPTIONS3_2')

SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT DISTINCT Y = YEAR(DATE1), M = MONTH(DATE1) FROM #OUT_TABLE ORDER BY YEAR(DATE1), MONTH(DATE1)

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @Y, @M
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
	
		SET @TMP_DATE = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@M,@Y))
		
		----Пересчёт для коэф индексации для районного			
		SET @REGION_VAL = DBO.SA_GET_REGION(@varKSlinkEmpl,@TMP_DATE,1)
		
		IF @REGION_VAL > 0 
		BEGIN
		
			SET @Cur2 = CURSOR FORWARD_ONLY

			FOR SELECT DISTINCT LINK_VKR FROM #OUT_TABLE WHERE YEAR(PERIOD) =  @Y AND MONTH(PERIOD) = @M ORDER BY LINK_VKR
			
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					IF EXISTS (SELECT * FROM #OUT_TABLE WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_RAYON AND KOEF > 1)
					BEGIN

	--					SET @REGION_SUM = ISNULL((SELECT SUM(SUM0) FROM #BASE1 S WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND S.LINK_PAY = @LINK_RAYON),0)
	--					ROUND(SUM(S.SUM0) * @REGION_VAL / (@REGION_SUM * 100),4) --Коэффициент соответствия рассчётного районного коэффицента фактическому
						SET @REGION_VAL = ISNULL(
							(
								SELECT 
									CASE WHEN SUM(S.SUM0) <> 0 THEN
										ROUND(SUM(S.SUMMA) / SUM(S.SUM0),4) --расчётный коэф индексации
									ELSE 0 END	
								FROM #OUT_TABLE S INNER JOIN dbo.group_pays(@LINK_RAYON) B ON S.LINK_PAY = B.PAY_LINK
								WHERE YEAR(S.PERIOD) = @Y AND MONTH(S.PERIOD) = @M AND LINK_VKR = @LINK_SFIN
							),1)
						
						UPDATE #OUT_TABLE
						SET KOEF = @REGION_VAL, SUMMA = SUM0 * @REGION_VAL
						WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_RAYON
					END	
					
				END
			
				FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END	--IF @REGION_VAL > 0

		----Пересчёт для коэф индексации для северного			
		SET @REGION_VAL = DBO.SA_GET_REGION(@varKSlinkEmpl,@TMP_DATE,2)
	
		IF @REGION_VAL > 0 
		BEGIN
		
			SET @Cur2 = CURSOR FORWARD_ONLY

			FOR SELECT DISTINCT LINK_VKR FROM #OUT_TABLE WHERE YEAR(PERIOD) =  @Y AND MONTH(PERIOD) = @M ORDER BY LINK_VKR
			
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					IF EXISTS (SELECT * FROM #OUT_TABLE WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_SEVER AND KOEF > 1)
					BEGIN

						SET @REGION_VAL = ISNULL(
							(
								SELECT 
									CASE WHEN SUM(S.SUM0) <> 0 THEN
										ROUND(SUM(S.SUMMA) / SUM(S.SUM0),4) --расчётный коэф индексации
									ELSE 0 END	
								FROM #OUT_TABLE S INNER JOIN dbo.group_pays(@LINK_SEVER) B ON S.LINK_PAY = B.PAY_LINK
								WHERE YEAR(S.PERIOD) = @Y AND MONTH(S.PERIOD) = @M AND LINK_VKR = @LINK_SFIN
							),1)
						
						UPDATE #OUT_TABLE
						SET KOEF = @REGION_VAL, SUMMA = SUM0 * @REGION_VAL
						WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_SEVER
					END
					
				END
			
				FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END	--IF @REGION_VAL > 0			
		
	END  

	FETCH NEXT FROM @Cur1 INTO @Y, @M
END

CLOSE @Cur1
DEALLOCATE @Cur1

------------------
SELECT PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2 FROM #OUT_TABLE

Return 0




GO


GRANT EXECUTE ON dbo.[SD_BASE_SUM_PAY_DIF_PERIODS] TO PUBLIC

GO

GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_REPORT_NEVIYASN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_REPORT_NEVIYASN]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
c Кейсистемс (Keysystems), 2005
*/

create  procedure dbo.BB_REPORT_NEVIYASN
	@dDateB 	datetime,
	@dDateE 	datetime	

as
declare @iOwnDep	int
	
set @iOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

select ACC_CODE = DA.ACC_CODE,
		DA.TOFK_CODE,
		DA.TOFK_NAME,
		DA.BUDG_NAME,
		
		[DATE] = G.DATE_PROV,
		DOC_NAME = dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT),
		DOC_NUM = G.NUMBER,
		DOC_DATE = G.[DATE],
		PLAT_NAME = D.NAME,
		PLAT_INN = D.INN,
		PLAT_KPP = D.KPP,
		ADM_INN = DA.DEP_INN,
		ADM_KPP = DA.DEP_KPP,
		OKATO = DA.DEP_OKATO,
		KBK_CODE = KBK.CODE,
		SUMMA = G2.SUMMA, 
		Z_NUM = isnull(Z.NUMBER,''),
		Z_DATE = Z.[DATE],
		G.COMMENT
from dbo.G_PROV G 
INNER JOIN dbo.G_PROV1 G1 on G.LINK = G1.LINK_UP
INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP DT ON DT.LINK_UP = G2.LINK AND DT.DB_KR = 0
INNER JOIN dbo.G_PROV_AP KT ON KT.LINK_UP = G2.LINK AND KT.DB_KR = 1
INNER JOIN dbo.S_ACCOUNTS SA1 ON DT.ACCOUNT = SA1.LINK and SA1.cSinth = '210' and SA1.cAnalit = '02'
INNER JOIN dbo.S_ACCOUNTS SA2 ON KT.ACCOUNT = SA2.LINK and SA2.cSinth = '205' and SA2.cAnalit = '81'
inner join dbo.BB_DEP_ACC_DOP(null) DA on DA.ACC_LINK = G.ACC
left join dbo.DEPARTMENTS D on D.LINK = isnull(KT.DEP,DT.DEP)
left join dbo.KL_KBK KBK on KBK.LINK = isnull(KT.KBK,DT.KBK)
left join (select distinct U.LINK_G, GU.NUMBER, GU.[DATE] from dbo.G_PROV GU
			left join dbo.UVED_U_DOC U on U.LINK_UP = GU.LINK) Z on Z.LINK_G = G.LINK  
WHERE G.DATE_PROV BETWEEN @dDateB AND @dDateE and
		G.DEP = @iOwnDep	

return 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant all on dbo.BB_REPORT_NEVIYASN to public
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_PRINTDOC_INVOICE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_PRINTDOC_INVOICE]

GO
CREATE PROCEDURE dbo.BK_PRINTDOC_INVOICE
	@intLINK_DOC	INT
AS
BEGIN
	-- Шапочная часть доумента --
	DECLARE @TAB_HDR TABLE
		(DOC_LINK	INT,

		DOC_NUM		VARCHAR (30),
		DOC_DATE	VARCHAR (10),
		COR_NUM		VARCHAR (30),
		COR_DATE	VARCHAR (10),

		-- Продавец --
		SEL_NAME	VARCHAR (254),
		SEL_ADDR	VARCHAR (254),
		SEL_INN		VARCHAR (20),
		SEL_KPP		VARCHAR (20),

		-- Грузоотправитель --
		SHIPPER		VARCHAR (254),

		-- Грузополучатель --
		RECEIVER	VARCHAR (254),

		-- Платежно - расчетный документ --
		NUM_BASE	VARCHAR (30),
		DATE_BASE	VARCHAR (10),

		-- Покупатель --
		BUY_NAME	VARCHAR (254),
		BUY_ADDR	VARCHAR (254),
		BUY_INN		VARCHAR (20),
		BUY_KPP		VARCHAR (20)
		)

	-- Реквизиты счет-фактуры --
	INSERT INTO @TAB_HDR
	SELECT DOC.LINK,
		DOC.NUMBER,
		CONVERT (VARCHAR (10), DOC.[DATE], 104),
		CASE 
			WHEN ISNULL (GPI.COR_NUM, '') = '' THEN '-'
			ELSE GPI.COR_NUM
		END, 
		CASE
			WHEN GPI.COR_DATE IS NULL THEN  '-'
			ELSE CONVERT (VARCHAR (10), GPI.COR_DATE, 104)
		END,

		-- Продавец --
		dbo.BK_GET_PRINT_DEP_NAME (SEL.LINK),
		CONVERT (VARCHAR (254), dbo.GetAddressByKladr (SEL.KLADR_LINK) +
			ISNULL (', ' + SEL.HOUSE, '')),
		SEL.INN,
		SEL.KPP,

		-- Грузоотправитель --
		CASE
			WHEN ISNULL (SEL_SHIP, 0) = 1 THEN 'он же'
			ELSE CONVERT (VARCHAR (254), dbo.BK_GET_PRINT_DEP_NAME (SH1.LINK)
				+ ' ' + ISNULL (CONVERT (VARCHAR (254), dbo.GetAddressByKladr (SH1.KLADR_LINK)
				+ ISNULL (', ' + SH1.HOUSE, '')), ''))
		END,

		-- Грузополучатель --
		CONVERT (VARCHAR (254), dbo.BK_GET_PRINT_DEP_NAME (R1.LINK)
			+ ' ' + ISNULL (CONVERT (VARCHAR (254), dbo.GetAddressByKladr (R1.KLADR_LINK)
			+ ISNULL (', ' + R1.HOUSE, '')), '')),

		-- Платежно - расчетный документ --
		GPI.PAY_NUM AS NUM_BASE, 
		CONVERT (VARCHAR (10), GPI.PAY_DATE, 104),

		-- Покупатель --
		dbo.BK_GET_PRINT_DEP_NAME (BUY.LINK),
		CONVERT (VARCHAR (254), dbo.GetAddressByKladr (BUY.KLADR_LINK) +
			ISNULL (', ' + BUY.HOUSE, '')),
		BUY.INN,
		BUY.KPP
	FROM dbo.G_PROV DOC
	LEFT JOIN dbo.G_PROV_INVOICE GPI ON (GPI.DOC_LINK = DOC.LINK)
	LEFT JOIN dbo.DEPARTMENTS SEL ON (SEL.LINK = GPI.SELLER)
	LEFT JOIN dbo.DEPARTMENTS BUY ON (BUY.LINK = GPI.BUYER)
	LEFT JOIN dbo.DEPARTMENTS SH1 ON (SH1.LINK = GPI.SHIPPER)
	LEFT JOIN dbo.DEPARTMENTS R1 ON (R1.LINK = GPI.RECEIVER)
	WHERE DOC.LINK = @intLINK_DOC

	SELECT T1.*,
		T2.INV_NAME,
		ISNULL (T2.UM_CODE, '-') AS UM_CODE,
		ISNULL (T2.UM_NAME, '-') AS UM_NAME,
		ISNULL (T2.QTY, 0.00) AS QTY,
		ISNULL (T2.PRICE, 0.00) AS PRICE,
		T2.SUMMA,
		ISNULL (T2.AKCIZ, 0.00) AS AKCIZ,
		ISNULL (T2.STAVKA_NDS, 0.00) AS STAVKA_NDS,
		ISNULL (T2.SUMMA_NDS, 0.00) AS SUMMA_NDS,
		ISNULL (T2.NO_NDS, 0) AS NO_NDS,
		ISNULL (T2.SUMMA_ALL, 0.00) AS SUMMA_ALL,
		STATE_CODE,
		STATE_NAME,
		NUM_TD
	FROM @TAB_HDR T1
	LEFT JOIN dbo.BK_DOC_TABLE_MZ_NDS_FN (@intLINK_DOC) T2 ON (T2.LINK_UP = T1.DOC_LINK)
END


GO


GRANT EXECUTE ON dbo.[BK_PRINTDOC_INVOICE] TO PUBLIC

GO


--Расширенные свойства--


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_173]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_173]
END
GO



/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_173]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @vcOKATO VARCHAR(100), @vcPPP VARCHAR(100) 



EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
   SELECT @vcOKATO = d.[OKATO], @vcPPP = d.[VED]
   FROM dbo.[REPORT_SAVED_FORMS] rsf
         JOIN dbo.[DICTIONARY_DEPARTMENT] d ON [LINK] = rsf.[Link_Organization]
   WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM
         
   UPDATE #FileExportReport
   SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
   WHERE TXT = 'ТБ=02'      

   UPDATE #FileExportReport
   SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
   WHERE orders = (SELECT MIN(orders)
                   FROM #FileExportReport
                  WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                        AND orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                        AND [TXT] >= '470|')

   UPDATE #FileExportReport
   SET [TXT] = dbo.[RA_GETWORDNUM]([TXT],1,'|' ) + '|' + RTRIM(@vcPPP) + '|' + RTRIM(@vcOKATO) + SUBSTRING([TXT], CHARINDEX('|', [TXT]),8000) 
   WHERE  orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
         AND [TXT] LIKE '%|%'
                                  
END



GO
GRANT ALL ON dbo.RO_EXPORT_FORM_173 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_154]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_154]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_154]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON


DECLARE @iOrder INT,
         @liReturn INT,
         @vcUK VARCHAR(250),
         @lvcKBP VARCHAR(250),
         @lvcVB VARCHAR(250)
         

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN

   SELECT @vcUK = REPLACE([TXT],'УК=','')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) IN ('УК=')
         
   SELECT @lvcKBP = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
         LEFT([TXT],3) IN ('KБ=')

   SELECT @lvcVB = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')
   
   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],'')      
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503155'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503155'
   END

   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_155' AND
            [CODE] = 'IMPORT_KBP_155'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_155' AND
            [CODE] = 'IMPORT_VB_155'
   END
            
   DELETE #IMPORT_TABLE
   WHERE LEFT([TXT],2)='* ' OR
         [ORDER] IN (1,2)

   SET IDENTITY_INSERT #IMPORT_TABLE ON
     
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ=0503154M',-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'KБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)

   SET IDENTITY_INSERT #IMPORT_TABLE OFF
        

      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_154] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_86N_004]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_86N_004]
END
GO
 
/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_86N_004]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @iReturn INT 

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

-- создание временных табличек
CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                        ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета

CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении

CREATE TABLE #tab004
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT       
)
--Целевые средства
CREATE TABLE #tab004_BUDGETARY
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код показателя
   ,[SUMMA] NUMERIC(20,2) -- Значение      
)
--Объекты бюджетных инвестиций 
CREATE TABLE #tab004_CONSTRUCTION
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код
   ,[NAME] NUMERIC(20,2)   -- Наименование объекта  
   ,[KAT]  VARCHAR(50)     -- Код категории объекта 
   ,[SUMMA] NUMERIC(20,2)
)

--Целевые субсидии
CREATE TABLE #tab004_GRANT
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)    -- Код
   ,[NAME] VARCHAR(2000)   -- Наименование субсидии
   ,[SUMMA] NUMERIC(20,2)  -- Сумма планируемых поступлений по целевой субсидии (руб)      
)

Create index #IX_tab004 on #tab004 (ID)
Create index #IX_tab004_BUDGETARY on #tab004_BUDGETARY (ID)
Create index #IX_tab004_CONSTRUCTION on #tab004_CONSTRUCTION (ID)
Create index #IX_tab004_GRANT on #tab004_GRANT (ID)

CREATE TABLE #tabXML ([TXT] VARCHAR(8000), [ORDERS] INT IDENTITY(1,1), ID UNIQUEIDENTIFIER) 


INSERT #tabHead (DATE, ID)
SELECT GETDATE(), NEWID()

-- получение данных
EXEC dbo.[RO_EXPORT_86N_GET_DATA] @iLINK_SAVED_FORM, 4

-- формирование xml 
EXEC dbo.[RO_EXPORT_86N_GET_XML] 4

IF EXISTS(SELECT * FROM #tabXML)
BEGIN 
   SELECT @vcFILE_NAME = RTRIM(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(100), [ID]),'-',''), '}', ''), '{', ''))
   FROM #tabHead

   INSERT #FileExportReport([TXT],
                            [NameFile],
                            [ORDERS],
                            [NameFileArh])
   SELECT [TXT],
	       @vcFILE_NAME + '.xml',
	       [ORDERS],
          @vcFILE_NAME  + '.zip'
   FROM #tabXML
   ORDER BY [ORDERS]

   SET @vcFILE_NAME = @vcFILE_NAME + '.xml'
END 

DROP TABLE #tabHead
DROP TABLE #tab001
DROP TABLE #tab004
DROP TABLE #tab004_BUDGETARY
DROP TABLE #tab004_CONSTRUCTION
DROP TABLE #tab004_GRANT
DROP TABLE #tabXML

GO
GRANT ALL ON dbo.[RO_EXPORT_86N_004] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT * 
          FROM dbo.SYSOBJECTS 
          WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_REPORT_XML]') AND 
                OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_REPORT_XML]
END

GO

/*

 c Кейсистемс (Keysystems), 2010
	Экспорт отчетов в формате xml

	create table #Files ([TXT]             VARCHAR(8000), 
                        [ORDERS]          INT IDENTITY(1,1), 
                        [NAMEFILE]        VARCHAR(100), 
                        [NAMEFILE_ARH]    VARCHAR(100), 
                        [OrderFile]       INT DEFAULT(0),
                        [LINK_SAVED_FORM] INT)
	create table #Reports (LSF int)

*/
CREATE PROCEDURE dbo.[RO_EXPORT_REPORT_XML]
	@varKSiLSF	int
AS
	SET NOCOUNT ON
	-- поиск шаблона экспорта
	declare @CodeForm varchar(30), @StartDate datetime, @LinkE int, @NameDate varchar(30), @CodeBudg varchar(30), @CodeOrg varchar(30), @LF int, @BeginDate datetime, @LinkOrg int, @LinkBudg int, @ExecStr nvarchar(4000), @PeriodType TINYINT, @orderCol VARCHAR(100), @value VARCHAR(8000)
	select  @PeriodType = RSF.Period_Type, @BeginDate = RSF.begin_date, @LinkOrg = RSF.Link_Organization, @LinkBudg = RSF.Link_Type_Svod, @LF = RSF.Link_Form, @CodeForm = RF.Code, @StartDate = RF.Start_date from report_forms RF join report_saved_forms RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
	select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm and Start_Date = @StartDate

	if @LinkE is NULL
		select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm

	if @LinkE is NULL
		return 1

	--declare #t_LSF table (LSF int)
	create table #t_LSF (LSF int, atr varchar(1000))
	create table #t_Exec (txt varchar(8000))

	insert #t_LSF (LSF, atr)
	select distinct LSF, RSF.atr_code
	from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)
	union
	select distinct link, RSF.atr_code from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)

   DELETE R	
	from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)
	
   DELETE B
   from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)

		-- готовим данные
------------------------------------------------------------------------------------------------------
	declare @i int
	declare @t_Header table (Code varchar(100), Value varchar(8000), LSF int default 0)

	if @PeriodType = 1
	begin
		insert @t_Header (Code, Value)
		select '@DATE@', convert(varchar(10), dbo.DateBeginOfYear(@beginDate), 120) 

		set @NameDate = LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' год' 
	end
	else begin
		insert @t_Header (Code, Value)
		select '@DATE@', convert(varchar(10), dbo.DateBeginOfMonth(@beginDate), 120) 

		set @NameDate = RTRIM(dbo.DateMonthName(MONTH(@begindate))) + ' ' + LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' года' 
	end

	insert @t_Header (Code, Value)
	select '@NAME_DATE@', @NameDate

	set @codeBudg = isnull((select RTRIM(isnull(B.OutCode,'')) from  dbo.kl_budg_type B where  B.link = @LinkBudg ),'')

	insert @t_Header (Code, Value)
	select '@CODE_BUDG@',  @CodeBudg

	insert @t_Header (Code, Value)
	select '@NAME_BUDG@',  isnull((select dbo.[RA_XML_MASK] (RTRIM(isnull(B.Name, ''))) from dbo.kl_budg_type B where B.link = @LinkBudg), '') 

	select @CodeOrg = RTRIM(isnull(D.budg,'')) from dbo.departments D where D.link = @LinkOrg

	insert @t_Header (Code, Value)
	select '@CODE_ORG@',  @CodeOrg

	insert @t_Header (Code, Value)
	select '@NAME_ORG@',  dbo.[RA_XML_MASK](RTRIM(isnull(D.Name,'')))  from dbo.departments D where D.link = @LinkOrg

	insert @t_Header (Code, Value, LSF)
	select '@' + LTRIM(RTRIM(code))+ '@',  dbo.RN_GET_ATR_VALUE(Link_Saved_Form , Code), Link_Saved_Form 
	from dbo.N_REPORT_ATRIBUTS_VIEW V
			left join report_saved_forms RSF on charindex(RTRIM(V.Code), RSF.atr_code) > 0
			join #t_LSF L on L.LSF = RSF.Link_Saved_Form


	
	--declare #t_Data table (OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000), LSF int)
	create table #t_Data (LSF int, OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000))
	Create index #IX_DATA on  #t_Data (LSF, OrderTable, CodeRow)
	-- пока только динамика
	insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select RT.orders, RD.Code_Row, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RTRIM(RD.Str_Val)) end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col
	where RT.Val_Type = 1 --and exists(select top 1 * from dbo.report_dinamics_all RD1 where RD1.Link_SF = RD.Link_SF and RD1.Code_Row = RD.Code_Row and RD1.float_val <> 0) 
			and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and (RT.orders = D.OT) and (RC.orders = D.OC or D.OC = 0))

	insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select RT.orders, RR.Code, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''))) else dbo.[RA_XML_MASK] (RTRIM(isnull(RF.Formula,''))) end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where RT.Val_Type = 0 and exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0) 
		and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and RT.orders = D.OT and (RC.orders = D.OC or D.OC = 0))

	insert #t_Exec (txt)
	select 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (' + isnull(C.COND, 'RD.Str_Val') +  ') end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col '
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C
		full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT
	where isnull(C.OT, T.OT) in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)

	
	insert #t_Exec (txt)
	select ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else dbo.[RA_XML_MASK] (' + isnull(C.COND,'RTRIM(isnull(RF.Formula,''''))') + ') end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C
		full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT
	where isnull(C.OT, T.OT)  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)

	insert #t_Exec (txt)
	select top 1 ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else dbo.[RA_XML_MASK] (RTRIM(isnull(RF.Formula,''''))) end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0))) + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table 
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)
		and not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RR.Code and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T 
	where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)


	insert #t_Exec (txt)
	select top 1 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RD.Str_Val) end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0)))  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table 
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col 
	where not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RD.Code_Row and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T 
	where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)


	exec ssp_execresultset 'select txt from #t_Exec'--, @varKSDebug = 1
   
--select * from #t_Data order by OrderTable, CodeRow, OrderCol
--return
	-- формируем текст
------------------------------------------------------------------------------------------------------------
	--declare @t_Txt table (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))
	create table #t_Txt (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))
	create table #t_Txt1 (link int, txt varchar(8000), orders varchar(1000), orderTable tinyint default 0, CodeRow varchar(50), LSF int default (0))
	Create index #IX_TXT on  #t_Txt (link)

	
	insert #t_Txt (link, txt, orders, OrderTable, CodeRow, LSF)
	select link, txt , RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5) + '00000000000000000000000000000000000000000000000000000000000' AS orders , X.OrderTable, '' as CodeRow, 0
	from dbo.report_export_xml X 	 
			where link_up = @LinkE	and Link_Self = 0 and Type = 0 and X.OrderTable= 0
	union
	select -link, txt_end, RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5)  + '00000000000000000000000000000000000000000000000000000000005', X.OrderTable,  '', 0
	from dbo.report_export_xml X 
	where link_up = @LinkE	and Link_Self = 0  and txt_end <> '' and X.OrderTable= 0
	union 
	select link, txt , RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5) + RIGHT('0000000000000000000000000000000000000000000000000000000000' + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) + isnull(CodeRow,''), 57)  + '0' AS orders , X.OrderTable, isnull(CodeRow, ''), D.LSF
	from dbo.report_export_xml X 	 join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.orderTable = D.OrderTable 
			where link_up = @LinkE	and Link_Self = 0 and Type = 0
	union
	select -link, txt_end, RIGHT('0000' + LTRIM(RTRIM(STR(orders))) ,5)  + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(CodeRow,''), 57) + '5', X.OrderTable, isnull(CodeRow, ''), D.LSF
	from dbo.report_export_xml X 
		join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.orderTable = D.OrderTable 
	where link_up = @LinkE	and Link_Self = 0  and txt_end <> ''

	while @@rowcount > 0 
	begin
		-- сначала заполняем атрибуты
		set @i = 1

		update T	
		set txt = T.txt + ' ' + X.txt + '="' + X.Field + '"'  
		from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link
		where X.link_up = @LinkE and Type = 1 and LEN(T.orders) + 5 >= (select max(LEN(orders)) from 	#t_Txt T )
				and X.orders = @i

		while @@rowcount > 0
		begin
			set @i = @i + 1

			update T	
			set txt = T.txt + ' ' + X.txt + '="' + X.Field + '"'  
			from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link
			where X.link_up = @LinkE and Type = 1 and LEN(T.orders) + 5 >= (select max(LEN(orders)) from 	#t_Txt T )
					and X.orders = @i
		end

		truncate table #t_Txt1

		-- теперь потомки, умноженные на строки		
		insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)
		select X.link, X.txt  , T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5)  + '00000000000000000000000000000000000000000000000000000000000'  AS orders, 0, '', 0
		from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link
			where link_up = @LinkE and Type = 0	and X.orderTable = 0
				and not exists(select top 1 * from 	#t_Txt T where X.link = T.link)
		union
		select -X.link, X.txt_end, T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5) + '00000000000000000000000000000000000000000000000000000000005', 0, '', 0  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link
			where link_up = @LinkE and Type = 0	and txt_end <> '' and X.orderTable = 0	
				and not exists(select top 1 * from 	#t_Txt T where X.link = T.link)

		insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)
		select X.link, X.txt  , T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5)  + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(D.CodeRow,''), 57) + '0'  AS orders, X.OrderTable, isnull(D.CodeRow,''), isnull(D.LSF,0)
		from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link 
			join (select distinct LSF, OrderTable, CodeRow from #t_Data) D on X.OrderTable = D.OrderTable and ((D.CodeRow = T.CodeRow and D.LSF = T.LSF) or T.LSF = 0)
			where link_up = @LinkE and Type = 0	
				and not exists(select top 1 * from 	#t_Txt T where X.link = T.link)

		insert #t_Txt1 (link, txt, orders, OrderTable, CodeRow, LSF)
		select -X.link, X.txt_end, T.orders + '.' + RIGHT('0000' + LTRIM(RTRIM(STR(X.orders))),5) + RIGHT('0000000000000000000000000000000000000000000000000000000000'  + RIGHT('0000000' + LTRIM(RTRIM(STR(D.LSF))),7) +  isnull(D.CodeRow,''), 57) + '5',  X.OrderTable, isnull(D.CodeRow, ''), isnull(D.LSF,0)  from dbo.report_export_xml X join #t_Txt T on X.Link_Self = T.Link
			 join (select distinct LSF, OrderTable, CodeRow from #t_Data) D  on X.OrderTable = D.OrderTable and ((D.CodeRow = T.CodeRow and D.LSF = T.LSF) or T.LSF = 0)
			where link_up = @LinkE and Type = 0	and txt_end <> '' 	
				and not exists(select top 1 * from 	#t_Txt T where X.link = T.link)

		insert #t_Txt (link, txt, orders, OrderTable, CodeRow, LSF)
		select link, txt, orders, OrderTable, CodeRow, LSF
		from #t_Txt1

	end
	-- заполняем таблицу:
	declare @txt varchar(8000), @orders varchar(1000), @link int, @OT tinyint, @CodeRow varchar(50), @LSF int
	declare @t_Empty table (Code char(4))

	insert @t_Empty (Code) values ('@1@') insert @t_Empty (Code) values ('@2@') insert @t_Empty (Code) values ('@3@') insert @t_Empty (Code) values ('@4@') insert @t_Empty (Code) values ('@5@') 
	insert @t_Empty (Code) values ('@6@') insert @t_Empty (Code) values ('@7@') insert @t_Empty (Code) values ('@8@') insert @t_Empty (Code) values ('@9@') insert @t_Empty (Code) values ('@10@') 
	insert @t_Empty (Code) values ('@11@') insert @t_Empty (Code) values ('@12@') insert @t_Empty (Code) values ('@13@') insert @t_Empty (Code) values ('@14@') insert @t_Empty (Code) values ('@15@') 
	insert @t_Empty (Code) values ('@16@') insert @t_Empty (Code) values ('@17@') insert @t_Empty (Code) values ('@18@') insert @t_Empty (Code) values ('@19@') insert @t_Empty (Code) values ('@20@') 
	insert @t_Empty (Code) values ('@21@') insert @t_Empty (Code) values ('@22@') insert @t_Empty (Code) values ('@23@') insert @t_Empty (Code) values ('@24@') insert @t_Empty (Code) values ('@25@') 
	insert @t_Empty (Code) values ('@26@') insert @t_Empty (Code) values ('@27@') insert @t_Empty (Code) values ('@28@') insert @t_Empty (Code) values ('@29@') insert @t_Empty (Code) values ('@30@') 

	update #t_Txt
	set txt = REPLACE(txt, 'RIGHT(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt)), CHARINDEX(')', txt, CHARINDEX('RIGHT(', txt)) - CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))) + ')',
   RIGHT(RTRIM(CodeRow),convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))+1, CHARINDEX(')', txt, CHARINDEX('RIGHT(', txt)) - CHARINDEX(',', txt, CHARINDEX('RIGHT(', txt))-1))))
   WHERE txt like '%RIGHT(@CODEROW@%'

	update #t_Txt
	set txt = REPLACE(txt, 'LEFT(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt)), CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))) + ')', LEFT(RTRIM(CodeRow),convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))+1, CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))-1))))
   WHERE txt like '%LEFT(@CODEROW@%' --+ SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('LEFT(', txt)), CHARINDEX(')', txt, CHARINDEX('LEFT(', txt)) - CHARINDEX(',', txt, CHARINDEX('LEFT(', txt))) + ')%'

	update #t_Txt
	set txt =  
    REPLACE(txt, 'SUBSTRING(@CODEROW@' + SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)), CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt)) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))) + ')', 
    SUBSTRING(CodeRow, convert(int, SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1, CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)) + 1) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)) - 1)),
     convert(int,SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1)+1,  CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt))  - CHARINDEX(',', txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))+1) - 1)))
    )
   WHERE txt like '%SUBSTRING(@CODEROW@%' --+ SUBSTRING(txt, CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt)), CHARINDEX(')', txt, CHARINDEX('SUBSTRING(', txt)) - CHARINDEX(',', txt, CHARINDEX('SUBSTRING(', txt))) + ')%'

	update #t_Txt
	set txt = REPLACE(txt, '@CODEROW@', RTRIM(CodeRow))

	update #t_Txt
	set txt = REPLACE(txt, '@КОД_ДОХОДА@', RIGHT(RTRIM(K.Code),17))
	from dbo.report_kbk K
	where code_form = 'ДОХОДЫ_2010' and K.Code like '%' + RTRIm(CodeRow) + '%' and CHARINDEX('@КОД_ДОХОДА@', txt) > 0

	declare @code_skif table (code_str varchar(50), code varchar(50))

	insert @code_skif (code_str, code) values ('520', '0105000000000000А')
	insert @code_skif (code_str, code) values ('520', '0105000000000050А')
	insert @code_skif (code_str, code) values ('520', '0105010000000050А')
	insert @code_skif (code_str, code) values ('520', '0105020000000050А')
	insert @code_skif (code_str, code) values ('520', '0105000000000060А')
	insert @code_skif (code_str, code) values ('520', '0105010000000060А')
	insert @code_skif (code_str, code) values ('520', '0105020000000060А')
	insert @code_skif (code_str, code) values ('520', '0800000000000000А')
	insert @code_skif (code_str, code) values ('520', '0800000000000050А')
	insert @code_skif (code_str, code) values ('520', '0801000000000050А')
	insert @code_skif (code_str, code) values ('520', '0802000000000050A')
	insert @code_skif (code_str, code) values ('520', '0800000000000060A')
	insert @code_skif (code_str, code) values ('520', '0801000000000060A')
	insert @code_skif (code_str, code) values ('520', '0802000000000060А')
	insert @code_skif (code_str, code) values ('800', 'И4000000000000000')
	insert @code_skif (code_str, code) values ('810', 'И5000000000000000')
	insert @code_skif (code_str, code) values ('811', 'И6000000000000000')
	insert @code_skif (code_str, code) values ('812', 'И7000000000000000')
	insert @code_skif (code_str, code) values ('820', 'И8000000000000000')
	insert @code_skif (code_str, code) values ('821', 'И9000000000000000')
	insert @code_skif (code_str, code) values ('822', 'И1000000000000000')

	update #t_Txt
	set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),17))
	from @code_skif K
	where K.Code_str = LEFT(CodeRow,3) and K.Code like  + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0

	update #t_Txt
	set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),17))
	from dbo.report_kbk K
	where code_form = 'ИСТОЧНИКИ_2010' and K.Code like '%' + LEFT(CodeRow,3) + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0 and LEFT(CodeRow, 3) > '700'

	update #t_Txt
	set txt = REPLACE(txt, '@КОД_ИСТОЧНИКОВ@', RIGHT(RTRIM(K.Code),14) + '000')
	from dbo.report_kbk K
	where code_form = 'ИСТОЧНИКИ_2010' and K.Code like '%' + LEFT(CodeRow,3) + '%' + RIGHT(RTRIM(CodeRow),LEN(CodeRow)-3) + '%' and CHARINDEX('@КОД_ИСТОЧНИКОВ@', txt) > 0

	declare cur_Text  cursor local static for select link, orders, txt,  orderTable, CodeRow, LSF from #t_Txt where charindex('@', txt) > 0

	open cur_Text
	fetch next from cur_Text into  @link, @orders, @txt, @OT, @CodeRow, @LSF
	while @@fetch_status = 0
	BEGIN
		select @txt = REPLACE(@txt, RTRIM(code), RTRIM(VALUE))
		from @t_header
		where LSF = @LSF or LSF = 0
      
		if @LSF = 0
		begin
			delete #t_TXT where link = @link

			insert #t_TXT
			select @link, max(REPLACE(@txt, code, value)), @orders, @OT, @CodeRow, LSF
			from @t_header
			where LSF <> 0 and CHARINDEX(code, @txt) > 0			
         GROUP BY LSF
			union
			select -@link, (select top 1 txt from #t_TXT where link = -@link), LEFT(@orders, LEN(@orders)-1) + '5', @OT, @CodeRow, LSF
			from @t_header
			where LSF <> 0 and CHARINDEX(code, @txt) > 0			

			if @@ROWCOUNT = 0
			begin
				insert #t_TXT
				select @link, @txt, @orders, @OT, @CodeRow, 0			
			end
			else
				delete #t_TXT where link = -@link and LSF = 0
            
         SELECT @LSF = MIN(LSF) FROM #t_TXT WHERE [link] = @link
         WHILE EXISTS(SELECT * FROM #t_TXT WHERE [link] = @link AND LSF > @LSF)
         BEGIN
            SELECT @TXT = TXT FROM #t_TXT WHERE [link] = @link AND LSF = @LSF

      		select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')
            SELECT @txt = REPLACE(@txt, code, value)
            FROM @t_Header
            WHERE LSF = @LSF            
            
            UPDATE #t_TXT SET TXT = @TXT WHERE [link] = @link AND LSF = @LSF    
            SELECT @LSF = MIN(LSF) FROM #t_TXT WHERE [link] = @link AND LSF > @LSF
         END            
         SELECT @TXT = TXT FROM #t_TXT WHERE [link] = @link AND LSF = @LSF

         SELECT @txt = REPLACE(@txt, code, value)
         FROM @t_Header
         WHERE LSF = @LSF            

     		select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')
            
         UPDATE #t_TXT SET TXT = @TXT WHERE [link] = @link AND LSF = @LSF
         SET @LSF = 0    
		END
      

		if @TXT like '%RIGHT%'
		BEGIN


   		select  @TXT = REPLACE(@txt, 'RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')', RIGHT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))-1))))
			from #t_Data
			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
				and @txt like '%RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')%'

   		select  @TXT = REPLACE(@txt, 'RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')', RIGHT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))-1))))
			from #t_Data
			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
				and @txt like '%RIGHT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('RIGHT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('RIGHT(', @txt))) + ')%'

   	end

		if @TXT like '%LEFT%'
		BEGIN

			select  @TXT = REPLACE(@txt, 'LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')', LEFT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))-1))))
			from #t_Data
			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
				and @txt like '%LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')%'

			select  @TXT = REPLACE(@txt, 'LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')', LEFT(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))-1))))
			from #t_Data
			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
				and @txt like '%LEFT(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt)), CHARINDEX(')', @txt, CHARINDEX('LEFT(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('LEFT(', @txt))) + ')%'
            
		END

--		if @TXT like '%SUBSTRING%'
--		BEGIN
--
--			select  @TXT = REPLACE(@txt, 'SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')', 
--         SUBSTRING(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1))
--         , convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1
--         ))))
-- 
--			from #t_Data
--			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
--				and @txt like '%SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')%'
--
--
--			select  @TXT = REPLACE(@txt, 'SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')', 
--         SUBSTRING(RTRIM(Value),convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1))
--         , convert(int, SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)))+1, CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))-1
--         ))))
--
--			from #t_Data
--			where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF 
--				and @txt like '%SUBSTRING(' + RTRIM(OrderCol) + SUBSTRING(@txt, CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt)), CHARINDEX(')', @txt, CHARINDEX('SUBSTRING(', @txt)) - CHARINDEX(',', @txt, CHARINDEX('SUBSTRING(', @txt))) + ')%'
--            
--		END
      
      SELECT @OrderCol = RTRIM(min(OrderCol)) 
		from #t_Data
		where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF

      WHILE EXISTS(select * from #t_Data where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol > @orderCol)
      BEGIN
         SELECT @Value = RTRIM(VALUE)  
		   from #t_Data
		   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol = @orderCol

         select @txt = REPLACE(@txt, @OrderCol, @Value)   

         SELECT @OrderCol = RTRIM(min(OrderCol)) 
		   from #t_Data
		   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol > @orderCol
      END          

       
      SELECT @Value = VALUE  
	   from #t_Data
	   where orderTable = @OT and CodeRow = @CodeRow and LSF = @LSF AND orderCol = @orderCol

      IF @OrderCol IS NOT NULL
      select @txt = REPLACE(@txt, @OrderCol, @Value)   

		select @txt = replace(@txt, RTRIM(Code), '')
		from @t_Empty

		select @txt = replace(@txt, RTRIM(Code_str), RTRIM(add_info)) from dbo.report_kbk where code_form = 'SEND_XML' and (CHARINDEX('#' + RTRIM(@CodeForm) + '#', Code) > 0 or REPLACE(Code,'#','') = '')

		update #t_Txt set txt = @txt where link = @link and LSF = @LSF and CodeRow = @CodeRow and OrderTable = @OT
		fetch next from cur_Text into  @link, @orders, @txt, @OT, @CodeRow, @LSF
	end

	close cur_Text
	deallocate cur_Text
	--select  txt + case when link > 0 then '>' else '' end,  orders, LSF from #t_Txt order by orders, CodeRow

	delete #t_Txt where ltrim(txt) = ''

	-------- результат
	declare @OrderFile int
	set @OrderFile = isnull((select max(OrderFile) from #Files), 0)

	insert #Files ([TXT], [NAMEFILE],  [NAMEFILE_ARH], [OrderFile], [LINK_SAVED_FORM])
	select T.txt + isnull(X.txt_close,''), 
		REPLACE(RTRIM(@NameDate), ' ', '_') + '_' + @CodeBudg + '_' + @CodeOrg + '_Форма_' + RTRIM(@CodeForm) + '.xml',
		REPLACE(RTRIM(@NameDate), ' ', '_') + '_' + @CodeBudg + '_' + @CodeOrg + '_Форма_' + RTRIM(@CodeForm) + '.arj' , @OrderFile, @varKSiLSF   
	from #t_Txt T left join dbo.report_export_xml X on T.link =  X.link and X.link_up = @LinkE
	order by T.orders


GO
GRANT ALL ON dbo.[RO_EXPORT_REPORT_XML] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--exec  dbo.[RO_EXPORT_REPORT_XML] 25922
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[STO_W_HOURS_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[STO_W_HOURS_SAVE]

GO

CREATE  PROCEDURE [dbo].[STO_W_HOURS_SAVE]
/* Тарификация в образовани. Табличная часть документа о педнагрузках*/
	@LINK	   	int	OUTPUT,		
	@link_up	int = 0,		
	@link_empl	int = 0,
	@link_tar_empl	int = 0,
	@link_pay	int = 0,		
	@link_les	int = 0,	
	@t		int = 1,	
	@link_paral	int = 0,		
	@link_clas	int = 0,		
	@week_hours	numeric(5,2) = 0.00,
	@percent	numeric(5,2) = 100.00,
	@LINK_KBK	INT,
	@DATE_BEGIN 	DATETIME = NULL,
	@DATE_END 	DATETIME = NULL,
	@NO_CALC	TINYINT = 0,
	@M_STAVKA	NUMERIC(18,2) = 0.00

AS

DECLARE @varKSSQLError	int, 
		@varKSEventText	varchar(7000),
		@varKStrancount	int,  
		@varKSObjLink int, 
		@varKSRowCount INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

SET @link_les = coalesce(@link_les,0)
SET @link_paral = coalesce(@link_paral,0)
SET @link_clas = coalesce(@link_clas,0)
SET @week_hours = coalesce(@week_hours,0.00)
SET @percent = coalesce(@percent,100.00)
SET @link_empl = coalesce(@link_empl,0)
SET @link_tar_empl = coalesce(@link_tar_empl,0)
SET @M_STAVKA = COALESCE(@M_STAVKA,0)

SET @link_paral = (case when @t IN (2,3,4) then 0 ELSE @link_paral end)
SET @link_clas = (case when @t in (1,3,4) then 0 else @link_clas end)

IF coalesce(@link_up,0) = 0 or (coalesce(@link_empl,0) + coalesce(@link_tar_empl,0)) = 0 or coalesce(@link_pay,0) = 0 or COALESCE(@LINK_KBK,0) = 0 
BEGIN
	ROLLBACK
	RETURN 5
END

DECLARE @DOC_BEGIN DATETIME, @DOC_END DATETIME
Select @DOC_BEGIN = date_begin, @DOC_END = date_end from  STO_WEEK_HOURS_DOC where LINK = @link_up

SET @DATE_BEGIN = (CASE WHEN @DATE_BEGIN IS NULL OR @DATE_BEGIN NOT BETWEEN @DOC_BEGIN AND @DOC_END OR @DATE_BEGIN = @DOC_BEGIN THEN NULL ELSE @DATE_BEGIN END)
SET @DATE_END = (CASE WHEN @DATE_END IS NULL OR @DATE_END NOT BETWEEN @DOC_BEGIN AND @DOC_END OR @DATE_END = @DOC_END THEN NULL ELSE @DATE_END END)

IF @LINK is null OR @LINK = 0
BEGIN
	if exists (select * from dbo.STO_WEEK_HOURS where link_up = @link_up and link_empl = @link_empl and link_tar_empl = @link_tar_empl and link_pay= @link_pay and link_les = @link_les 
		and link_paral = @link_paral and link_clas = @link_clas and t = @t and week_hours = @week_hours and [percent] = @percent and LINK_KBK = @LINK_KBK) 
	begin
		ROLLBACK
		RETURN 8 /*'Комбинация ключевых реквизитов не уникальна.'*/		
	end
END

SELECT @varKSObjLink = LINK FROM S_OBJECTS WHERE CODE = 'STO_W_HOURS_TABLE'

IF @LINK is null OR @LINK = 0
BEGIN
	INSERT INTO dbo.STO_WEEK_HOURS WITH (ROWLOCK) (link_up, link_empl, link_tar_empl, link_pay, link_les, link_paral, link_clas, week_hours, [percent], t,LINK_KBK, DATE1, DATE2, NO_CALC, M_STAVKA) 
	VALUES (@link_up, @link_empl, @link_tar_empl, @link_pay, @link_les, @link_paral, @link_clas, @week_hours, @percent, @t, @LINK_KBK, @DATE_BEGIN, @DATE_END, @NO_CALC, @M_STAVKA)
	SELECT @varKSSQLError = @@ERROR, @LINK = @@IDENTITY
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END
ELSE
BEGIN
	UPDATE STO_WEEK_HOURS WITH (ROWLOCK) 
	SET link_up= @link_up, link_empl = @link_empl, link_tar_empl= @link_tar_empl, link_pay= @link_pay, link_les= @link_les, link_paral= @link_paral, link_clas= @link_clas, week_hours= @week_hours, [percent]= @percent, t= @t, LINK_KBK = @LINK_KBK, DATE1 = @DATE_BEGIN, DATE2 = @DATE_END, NO_CALC = @NO_CALC, M_STAVKA = @M_STAVKA
	WHERE LINK =@LINK
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
END	


SELECT @varKSEventText = 'Табличная часть документа о педнагрузках ' + ' ' + RTRIM(CONVERT(VARCHAR(50),LINK)) + ' ' + RTRIM(CONVERT(VARCHAR(50),link_up))+ ' ' + RTRIM(CONVERT(VARCHAR(50),fio))+ ' ' + RTRIM(CONVERT(VARCHAR(50),tab))+ ' ' + RTRIM(CONVERT(VARCHAR(50),POST_NAME))+ ' ' + RTRIM(CONVERT(VARCHAR(50),pays_name))+ ' ' + RTRIM(CONVERT(VARCHAR(50),l_name))+ ' ' + RTRIM(CONVERT(VARCHAR(50),p_name))+ ' ' + RTRIM(CONVERT(VARCHAR(50),c_name))+ ' ' + RTRIM(CONVERT(VARCHAR(50),FACT_WEEK_HOURS))+ ' ' + RTRIM(CONVERT(VARCHAR(50),perc)) from STO_W_HOURS_TABLE   where link = @link
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObjLink, 'STO_WEEK_HOURS', @LINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[STO_W_HOURS_SAVE] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_155]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_155]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_155]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON


DECLARE @iOrder INT,
         @liReturn INT,
         @vcUK VARCHAR(250),
         @lvcKBP VARCHAR(250),
         @lvcVB VARCHAR(250)
         

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN

   SELECT @vcUK = REPLACE([TXT],'УК=','')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) IN ('УК=')
         
   SELECT @lvcKBP = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
         LEFT([TXT],3) IN ('KБ=')

   SELECT @lvcVB = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')
   
   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],'')      
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503155'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503155'
   END

   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_155' AND
            [CODE] = 'IMPORT_KBP_155'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_155' AND
            [CODE] = 'IMPORT_VB_155'
   END
            
   DELETE #IMPORT_TABLE
   WHERE LEFT([TXT],2)='* ' OR
         [ORDER] IN (1,2)

   SET IDENTITY_INSERT #IMPORT_TABLE ON
     
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ=0503155M',-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'KБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)

   SET IDENTITY_INSERT #IMPORT_TABLE OFF

   UPDATE #IMPORT_TABLE
   SET [TXT] = REPLACE([TXT], '710|***|', '710|500|') 
   WHERE [TXT] LIKE '%710|***|%'

   UPDATE #IMPORT_TABLE
   SET [TXT] = REPLACE([TXT], '720|***|', '720|600|') 
   WHERE [TXT] LIKE '%720|***|%'
      
   UPDATE #IMPORT_TABLE
   SET TXT = RTRIM(TXT) + '|' + dbo.[RA_GETWORDNUM]([TXT], 1, '|') + REPLACE(dbo.[RA_GETWORDNUM]([TXT], 2, '|'), '***', '000')  
   WHERE [ORDER] > (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE [TXT] = 'РД=2')
         AND [TXT] LIKE '%|%|%'

   UPDATE #IMPORT_TABLE
   SET [TXT] = REPLACE([TXT], '|***|', '|000|') 
   WHERE [TXT] LIKE '%|%|%'
       

      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_155] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_86N_005]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_86N_005]
END
GO
 
/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_86N_005]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @iReturn INT 

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

-- создание временных табличек
CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                        ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета

CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении

CREATE TABLE #tab005
(
   ID       UNIQUEIDENTIFIER
   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
   ,[versionNumber]   VARCHAR(50)-- Номер версии
   ,[financialYear]  INT       
)
--Бюджетные обязательства
CREATE TABLE #tab005_CIRCUMSTANCE
(
   ID       UNIQUEIDENTIFIER
   ,[CODE]  VARCHAR(50)   
   ,[NAME]  VARCHAR(8000)   -- Наименования бюджетных обязательств 
   ,[RZPR]  VARCHAR(50)     -- Раздел, подраздел  
   ,[CSR]   VARCHAR(50)     -- Целевая статья
   ,[VR]    VARCHAR(50)     -- Вид расходов
   ,[SGU]   VARCHAR(50)     -- КОСГУ    
   ,[BUDGET_CODE] VARCHAR(50) -- код бюджета
   ,[BUDGET_NAME] VARCHAR(2000) -- наименование бюджета
   ,[SUMMA] NUMERIC(20,2)   -- Значение      
)

Create index #IX_tab005 on #tab005 (ID)
Create index #IX_tab005_CIRCUMSTANCE on #tab005_CIRCUMSTANCE (ID)

CREATE TABLE #tabXML ([TXT] VARCHAR(8000), [ORDERS] INT IDENTITY(1,1), ID UNIQUEIDENTIFIER) 


INSERT #tabHead (DATE, ID)
SELECT GETDATE(), NEWID()

-- получение данных
EXEC dbo.[RO_EXPORT_86N_GET_DATA] @iLINK_SAVED_FORM, 5

-- формирование xml 
EXEC dbo.[RO_EXPORT_86N_GET_XML] 5

IF EXISTS(SELECT * FROM #tabXML)
BEGIN 
   SELECT @vcFILE_NAME = RTRIM(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(100), [ID]),'-',''), '}', ''), '{', ''))
   FROM #tabHead

   INSERT #FileExportReport([TXT],
                            [NameFile],
                            [ORDERS],
                            [NameFileArh])
   SELECT [TXT],
	       @vcFILE_NAME + '.xml',
	       [ORDERS],
          @vcFILE_NAME  + '.zip'
   FROM #tabXML
   ORDER BY [ORDERS]

   SET @vcFILE_NAME = @vcFILE_NAME + '.xml'
END 

DROP TABLE #tabHead
DROP TABLE #tab001
DROP TABLE #tab005
DROP TABLE #tab005_CIRCUMSTANCE
DROP TABLE #tabXML

GO
GRANT ALL ON dbo.[RO_EXPORT_86N_005] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHECK_KS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_KS]
GO

/*
c Кейсистемс (Keysystems), 2005
*/
CREATE     PROCEDURE dbo.RO_CHECK_KS 
  @LSF int = NULL, 
  @dBegin datetime = '20050101', 
  @PerType smallint = 1, 
  @PerNom smallint = 1, 
  @isSvod tinyint = 0, 
  @LinksGroupKS varchar(8000) = '', 
  @LinksDepartment varchar(8000) = '',
  @bExcess tinyint = 0 output,  -- FOR WEB only
  @cText  varchar(60) = '' output,  -- FOR WEB only
  @varKStableName varchar(100) = '', -- таблица с линками отчетов для внутридокументной проверки
  @cTables varchar(1000) = '', --для какой таблицы формы будем проводить проверку (если '' - то для всех)
  @cProgressTable     varchar(254)  = '',
  @cGroup varchar(250)='', --группа кс,
  @iDown int=0, --проверка по ветке
  @mdks int=0,  --мдкс
  @tmpTable varchar(100)='',  --временная таблица для протокола
  @typeProtokol tinyint = 0, -- тип протокола (если @tmpTable пустно): 
							-- 0 - автоматический выбор (если меньше 10000 строк, то html, иначе грид),
							-- 1 - грид всегда
							-- 2 - html всегда
	@varKSiTypeRules INT = 0							
AS

SET @cText = 'Формула&Документ&Таблица&Операция и код&Графа&Значение'
SET @bExcess = 1



	if  (@LSF is NOT NULL or RTRIM(ISNULL(@varKStableName,'')) <> '') and isnull(@LinksGroupKS,'')=''
	begin
		exec dbo.RO_CHECK_KS_INSIDE @LSF, @varKStableName, @cTables, @iDown, @cGroup, @cProgressTable, @tmpTable, @typeProtokol, @varKSiTypeRules
		return 1	
	end
	else
	begin	
		exec dbo.RO_CHECK_KS_OUTSIDE @LinksGroupKS, @PerType, @PerNom, @dBegin, @LinksDepartment, @varKStableName, @iDown, @cProgressTable, @tmpTable, @typeProtokol
		return 1
	end
	



declare @strProgressExec varchar(1000),@nprecision float(10),@noKS int,@link_gr int,@name_gr varchar(2000),@count_atr_err int
set @nprecision=0.001
set @noKs=0
declare @outStr varchar(8000),@atr varchar(50),@name_atr varchar(100),@cProgress varchar(1000),@code_atr varchar(100),@name_atr_main varchar(100)
declare @linkRule int, @OrderRow int, @ExecProc varchar(250), @i int, @i1 int, @orders int, @ordersRule varchar(250),@cnt int, @ExecStr varchar(8000)
set @outStr = ''
set @orders = 0

declare @cTmp varchar(1000),@cnt_f_r int,@cnt_f_f int
declare @cTmp1 varchar(1000), @cTmp2 varchar(1000), @cTmp3 varchar(1000), @cTmp4 varchar(1000),@begin_ord int
create table #Rules (link_rule int primary key, order_rule int)
create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)
create table #ListForms_atr (lsf int, linkForm int, codeForm char(20), startDate datetime)
create table #atr (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_cur (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_empty (lsf int, atr varchar(50), str_val varchar(50))
create table #t_mdks(link_group int,code varchar(100))
create table #ListFormsV (lsf int, linkForm int, codeForm char(20), startDate datetime)
create table #Val (val float(53))
create table #Res (orders int,ord int IDENTITY (1, 1) NOT NULL, res varchar(8000),cKod varchar(100),cDoc varchar(2000),cTable varchar(100),cCol varchar(100),cValue varchar(100))
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(50), [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_LeftPart_V table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value numeric(24,8), orders varchar(250))
declare @t_RightPart_V table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value numeric(24,8), orders varchar(250))
--declare @t_All_M table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(250), Exec_Proc_Desc varchar(250), Value numeric(20,4), orders varchar(250))
declare @t_LeftPart_M table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value numeric(20,4), orders varchar(250))
declare @t_RightPart_M table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value numeric(20,4), orders varchar(250))
declare @t_temp_M table(Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), [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)
declare @t_ExData  table (Link_Rule int,LinkCol int,LinkRow int, OrderRow int, Err varchar(8000),Err1 varchar(8000),orders varchar(250))
declare @t_LeftPart_VEx table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float(53), orders varchar(250))
declare @t_RightPart_VEx table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
create table #t_znak (OrderRow int, Link_Rule int, orders varchar(250),[sign] varchar(2))
declare @t_tmp table (lc int, lr int, lrule int, V float(53), o varchar(250), s char(2), cr varchar(50))
create table #t_znak_not_plus (Link_Rule int, orders varchar(250))
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(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
declare @t_LeftPart_MEx table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float(53), orders varchar(250))
declare @t_RightPart_MEx table (Link_Rule int , OrderRule int, OrderRow int, Val_Type tinyint, Sign char(2), LinkTable int, LinkCol int, LinkRow int, CodeRow varchar(50), Factor float(53), Exec_Proc varchar(350), Exec_Proc_Desc varchar(250), Value float (53), orders varchar(250))
declare @t_ExRes  table (Link_Rule int, OrderRow int, orders varchar(250),ord int,cformula varchar(8000),cKod varchar(100),cDoc varchar(2000),cTable varchar(100),cCol varchar(100),cValue varchar(50))
declare @rounds int -- точность
declare @link_form int
declare @minDateUpdCache datetime,@maxDateModifyRule datetime
declare @NRULES table  (Link_Rule int,Orders varchar(50),include bit)
declare @NRULES1 table  (Link_Rule int,Orders varchar(50),orderrule int,[ROWS] varchar (250))
Declare @ResultValue table (link_rule int,orders varchar(50),sign varchar(2),LeftValue numeric(20,4),RightValue numeric(20,4))
declare @t_minus table (Link_Rule int,orderRow int )
declare @Error table (link_rule int,orders varchar(50))
declare @LinksDepartment_tmp varchar(250) 
declare @link_col_cache table(link_rule int,link_col int)
create table #table_ks (orders int)
 declare @lsf_tmp int

if RTRIM(ISNULL(@varKStableName,'')) <> '' and (select object_id('tempdb..' + @varKStableName)) is NOT NULL
begin
  set @cTmp = 'insert #ListFormsV (lsf) select * from ' + @varKStableName + ' drop table ' + @varKStableName
  execute(@cTmp)
  delete #ListFormsV where lsf not in (select Link_Saved_Form from report_Saved_Forms)
  if not exists(select top 1 * from #ListFormsV)
  begin
    insert #Res (res) values ('Не выбран ни один отчет для проверки!')
    select isnull(res,'') res,isnull(cdoc,'') cdoc,isnull(ctable,'') ctable,isnull(ckod,'') ckod,isnull(ccol,'') ccol,isnull(cvalue,'') value from #Res order by orders,ord
    return 0
  end
  IF @iDown=1
    begin
        select -lsf as lsf into #LF_TMP from #ListFormsV
        While exists(select * from #LF_TMP where lsf<0)
            begin
               select top 1 @lsf_tmp=-lsf  from #LF_TMP where lsf<0
               INSERT #LF_TMP exec dbo.RN_GET_SVOD_FORMS @lsf_tmp,default,default,default,default,default,default,default,default,1,1
               delete  #LF_TMP where lsf=-@lsf_tmp
            end
        INSERT #ListFormsV (lsf)
        SELECT lsf from #LF_TMP A where not exists(select * from #ListFormsV where lsf=A.lsf)
    end 
  IF @iDown=2
    begin
        select lsf as lsf into #LF_TMP2 from #ListFormsV
        While exists(select * from #LF_TMP2 where lsf>0)
            begin
               select top 1 @lsf_tmp=lsf  from #LF_TMP2 where lsf>0
               INSERT #LF_TMP2 exec dbo.RN_GET_SVOD_FORMS @lsf_tmp,default,default,default,default,default,default,default,default,1,1
               update #LF_TMP2 set lsf=-lsf   where lsf=@lsf_tmp
            end
        INSERT #ListFormsV (lsf)
        SELECT -lsf from #LF_TMP2 A where not exists(select * from #ListFormsV where lsf=-A.lsf)
    end 

end
if (@LSF is not null) and exists(select top 1 * from report_saved_forms where link_saved_form = @LSF)
begin
  insert #ListFormsV (lsf) values (@LSF)
end

declare @linkOrg int, @subStr varchar(30), @Str1 varchar(8000), @str2 varchar(8000), @linkTree int, @linkBudg int, @Year int

--для междокументных правил
create table #link_uzel (link int)
IF @mdks=1 
    begin
        --найдем узлы для проверок
        select @dbegin=begin_date,@perType=period_type,@perNom=period_number from report_saved_forms where link_saved_form in (select top 1 lsf from #ListFormsV)
        insert #link_uzel
        select link from RO_SVOD_TREE A, REPORT_SAVED_FORMS B 
        WHERE A.LINK_REPORT_ORG = LINK_ORGANIZATION AND
         ISNULL([LINK_REPORT_BUDG],0) = ISNULL(LINK_TYPE_SVOD,0) 
        and B.link_saved_form in (select lsf from #ListFormsV)
        set @LinksDepartment=''
        while exists(select top 1 * from #link_uzel)        
            begin
                select top 1  @linkOrg=link from #link_uzel
                set @LinksDepartment=@LinksDepartment+case when @LinksDepartment='' then '' else ' ' end +ltrim(str(@linkOrg))
                delete #link_uzel where link=@linkOrg
            end
    end
set @LinksDepartment_tmp=@LinksDepartment

if not exists(select top 1 * from #ListFormsV) or @mdks=1
begin
  if LEN(LTRIM(@LinksDepartment_tmp)) = 0
  begin
    exec dbo.X_GET_OWN_DEP_LINK @linkOrg output
    select @LinksDepartment_tmp = LTRIM(STR(Link)) from report_svod_tree where Link_Org = @linkOrg and type = 1
   end
  set @Year = YEAR(@dBegin)
  set @dBegin = case @PerType when 1 then LTRIM(STR(@Year)) + '1231' 
        when 2 then dateadd(quarter, @PerNom, LTRIM(STR(@Year)) + '0101') -1
        else dateadd(month, @PerNom, LTRIM(STR(@Year)) + '0101') - 1 end
  while LEN(LTRIM(@LinksDepartment_tmp)) > 0
  begin
    exec dbo.RO_FORMULA_FUNCTIONS 1, @LinksDepartment_tmp output, @subStr output, ' '
    set @linkTree = CONVERT(int, @subStr)
    set @linkOrg = NULL
    set @linkBudg = NULL
    set @IsSvod = 0
    select @linkOrg = Link_report_org, @linkBudg = Link_report_budg, @IsSvod = 1 - Childrens from dbo.ro_svod_tree where Link = @LinkTree
    insert #ListForms exec dbo.I_REPORT_ORG_FORMS_LIST @linkOrg, @dBegin, @perType, @perNom, @isSvod, @LinkBudg
    insert #ListForms exec dbo.I_REPORT_ORG_FORMS_LIST @linkOrg, @dBegin, @perType, @perNom, @isSvod, null
  end      
end
else
        insert #ListForms
        select lsf, link_form, '', NULL from #ListFormsV LF inner join report_saved_forms RSF on LF.lsf = RSF.[Link_Saved_Form]

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 1'
        execute(@strProgressExec)
    end

select *
INTO #REPORT_FORMS
from REPORT_FORMS (NOLOCK)
where link_form in (select linkform from #ListForms)

select *
into #report_tables
from dbo.report_tables (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

Create index #IX_REPORT_TABLES on #report_tables (link_table)

select *
into #REPORT_COLOUMNS
from dbo.REPORT_COLOUMNS (NOLOCK)
where link_table in (select link_table from #report_tables)

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 2'
        execute(@strProgressExec)
    end


SELECT RR.*,RSV.Formula code 
into #I_REPORT_ROWS
FROM Report_Rows  RR (NOLOCK) LEFT JOIN 
	Report_Formula RSV (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 (NOLOCK)
where link_SF in (select lsf from #ListForms) and code_row<>'' 

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 3'
        execute(@strProgressExec)
    end


select *
into #REPORT_CONTROL_RULES
From REPORT_CONTROL_RULES (NOLOCK)
where link_form in (select link_form from #REPORT_FORMS)

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 4'
        execute(@strProgressExec)
    end


select *
into #REPORT_SUMMA
From REPORT_SUMMA_ALL (NOLOCK)
Where Link_Saved_Form in (select lsf from #ListForms)

select *
into #REPORT_DINAMICS
From REPORT_DINAMICS_ALL (NOLOCK)
Where Link_SF in (select lsf from #ListForms)

Create index #IX_REPORT_SUMMA on #report_summa (link_col,link_row)
Create index #IX_report_dinamics on #report_dinamics (link_sf,code_row,link_col)
Create index #IX_REPORT_CONTROL_RULES on #REPORT_CONTROL_RULES (link_rule)
Create index #IX_T_KS on #T_KS (link_rule,orders)
Create index #T_ZNAK on #T_ZNAK (link_rule,orders)


select link_col 
into #link_col_summa
from #report_dinamics group by link_col
union 
select link_col from #report_summa group by link_col

--считаем настройку - скрывать нулевые слагаемые
declare @cStr varchar(250),@del_null_ks bit
exec X_GET_OPTION 'RA_REP_OPTIONS_COM_DEL_P_KS',0,@cStr output 	
set @del_null_ks=case when RTRIM(@cstr)='1' then 1 else 0 end
set @del_null_ks=0


declare @varKSEventText varchar(1000),@varKSLink_Task int
select @varKSLink_Task = link_task from user_info


--обработка группы
    CREATE TABLE #tmp_group_ks (link_rule int)
    declare @gr_ks int
    IF @cGroup<>''
        begin
            select @gr_ks=link_group_ks from  report_group_ks (NOLOCK) where name=@cGroup and type=4
            insert #tmp_group_ks
            select link_rule from report_control_group (NOLOCK) where link_group_ks=@gr_ks
            Create index #ix_tmp_group_ks on #tmp_group_ks (link_rule)
        end

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 5'
        execute(@strProgressExec)
    end



if exists(select top 1 * from #ListFormsV)  and @mdks=0
begin 
------------------ ВНУТРИДОКУМЕНТНЫЕ КС -----------------------------------------
  while exists(select top 1 * from #ListFormsV)
  begin
    select top 1 @LSF = lsf from #ListFormsV
    truncate table #ListForms
    insert #ListForms
      select lsf, link_form, '', NULL from #ListFormsV LF inner join report_saved_forms RSF on lsf = @LSF and LF.lsf = RSF.[Link_Saved_Form]

    truncate table #Rules
    truncate table #t_KS
    delete @t_LeftPart_V
    delete @t_RightPart_V
    truncate table #t_Col
    delete @t_ExData
    delete @t_LeftPart_VEx
    delete @t_RightPart_VEx
    delete @t_tmp
    delete @link_col_cache
    truncate table #t_znak_not_plus
    truncate table #t_sum 
    delete @t_ExRes
    delete #ListFormsV where lsf = @LSF
    truncate table #Rules
    truncate table #TABLE_KS

    delete @NRULES
    delete @NRULES1
    delete  @ResultValue
    delete  @t_minus
    delete @Error
    truncate table #t_znak
    insert into #Rules exec dbo.I_CONTROL_RULES_LIST @LSF, 0,default,default,default,1
    IF @cGroup<>''
        begin
            --удалим все правила не относящиеся к группе
            delete  #Rules from #Rules A where not exists(select * from #tmp_group_ks B where A.link_rule=B.link_rule)
        end

    IF @cTables=''
        begin
            --удалим все правила не относящиеся потабличной проверке
            delete  #Rules from #Rules A where exists(select * from #Report_control_rules B where A.link_rule=B.link_rule and B.isDoschet&2=2)
        end


      select @varKSEventText = 'Форма '+RTRIM(RF.Code)+ 
      ' Дата проверки: ' + RTRIM(convert(varchar(30), getdate(), 120))+
      ' Отчетный период: ' + case Period_Type
                when 2 then convert(char(1),period_number) + ' квартал'
                when 4 then case Period_Number 
                    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 'декабрь'
                    else ''
                  end
                else ''
              end + ' ' + convert(char(4), YEAR(begin_date)) + ' г.'+
      'Организация: ' + RTRIM(D.Name)+
      'Бюджет: ' + RTRIM(B.Name)
      from report_saved_forms RSF 
      inner join #REPORT_FORMS RF on RSF.link_saved_form = @LSF and RSF.Link_form = RF.Link_Form
      left join departments D on RSF.link_organization = D.link
      left join BI_DICTION_BUDG_TYPE B on RSF.link_Type_Svod = B.link

    EXECUTE WF_GENERATEEVENT 'Внутридокументный контроль', @varKSEventText, null, 'WF_DOCTASK',null

    select  @ctmp = '<B>Форма ' + RF.Code,
      @ctmp1= '<B>Дата проверки: ' + convert(varchar(30), getdate(), 120),
      @ctmp2 = '<B>Отчетный период: ' + case Period_Type
                when 2 then convert(char(1),period_number) + ' квартал'
                when 4 then case Period_Number 
                    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 'декабрь'
                    else ''
                  end
                else ''
              end + ' ' + convert(char(4), YEAR(begin_date)) + ' г.',
      @ctmp3 = '<B>Организация: ' + D.Name,
      @ctmp4 = '<B>Бюджет: ' + B.Name
    from report_saved_forms RSF 
      inner join #REPORT_FORMS RF on RSF.link_saved_form = @LSF and RSF.Link_form = RF.Link_Form
      left join departments D on RSF.link_organization = D.link
      left join BI_DICTION_BUDG_TYPE B on RSF.link_Type_Svod = B.link


    set @i = isnull((select max(orders) from #Res),0) + 1

    insert #Res (orders, res, cdoc)
    values(@i, '<B>', @ctmp)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp1)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp2)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp3)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp4)

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка на правильный ввод'', percents = 5'
        execute(@strProgressExec)
    end


    IF @cTables=''
    BEGIN
    set @execstr=
            'insert #table_ks (orders)
            select orders from #report_tables where Link_Form in (select LinkForm from   #ListForms) and Val_Type = 1'
    exec(@execstr) 
    END
    ELSE
    BEGIN
        set @execstr=
               'insert #table_ks (orders)
                select orders from #report_tables where Link_Form in (select LinkForm from   #ListForms) and Val_Type = 1 and Link_Table in ('+@cTables+')'
        exec(@execstr) 
    END

    declare @OrderTable int 
    --проверка на правильный ввод 
--        declare cur_Table cursor local static forward_only
--        for select orders from #report_tables where Link_Form in (select LinkForm from   #ListForms) and Val_Type = 1


    while Exists(select * from #table_ks)
        begin
          select @orderTable=orders from #table_ks  
          exec dbo.RN_CHECK_DICT @LSF, @orderTable
          delete #table_ks where orders=@orderTable  
       end


    if not exists(select top 1 * from #Rules)
    begin
	  set @noKS=1	
      insert #Res (orders, res, cdoc) values (@i + 1, '-', 'Нет правил контрольных соотношений')
      insert #Res (orders, res, cdoc) values (@i + 1, '-', '')
        CONTINUE
    end
    select @cnt = max(orders) from #Res

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение списка правил для формы'', percents = 10'
    execute(@strProgressExec)
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 left 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




select  @link_form=linkform from #ListForms
IF (select top 1 code from report_forms where link_form=@link_form) like '%503379%'
    set @nprecision=0.1


select  top 1 @minDateUpdCache=Upd_date FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK) WHERE Link_Rule in (select top 1 link_rule from #Rules)
set     @minDateUpdCache=isnull(@minDateUpdCache,'19900101')
select  @maxDateModifyRule=Max(Modify_Date) from #Report_control_rules


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка списка правил для формы'', percents = 15'
    execute(@strProgressExec)
end

--если данные в кеше старые или их нет, обновим их
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
print @minDateUpdCache

IF  EXISTS(SELECT  link_rule FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
                   WHERE Link_Rule in (select link_rule from #Rules)) AND not EXISTS(select * from JURNAL where tableName='KS_REFRESH_CASH' and  link_pk=@link_form)
BEGIN
--есть данные в кеш таблице

INSERT @NRULES
    SELECT Link_rule,orders,sum(
        case when RC.val_type in (1,4) then 1
             when RC.Exec_proc<>'' then 1
             when RC.signAfter in('>','<','>=','<=','<>') then 1
             else 0 end)      
        FROM REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK)
        WHERE Link_Rule IN (select link_rule from #Rules)  Group By Link_Rule,orders

--для 428 формы удалим правила досчета
if (select Code from #report_forms where Link_Form = @link_form) like '428%'
    begin
        delete from @nrules where link_rule in (select link_rule  from report_control_rules A (nolock) where A.link_form=@link_form and A.issystemsrule=2)
    end




INSERT @NRULES1 
        SELECT A.Link_Rule,A.Orders,B.orderrule,B.[rows] 
        FROM @NRULES A INNER JOIN #REPORT_CONTROL_RULES B on A.link_rule=B.link_Rule
--        WHERE include>0 or EXISTS(select * from @link_col_cache C where C.link_rule
INSERT #T_KS
    SELECT 
        RC.Link_Rule, A.orderrule, 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 REPORT_CONTROL_ROWS_CACHE RC WITH (NOLOCK),@NRULES1 A
        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 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 -- размножаем правила
            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)


--для 428 формы удалим правила досчета
if (select Code from #report_forms where Link_Form = @link_form) like '428%'
    insert  #t_KS
    SELECT R1.Link_Rule, OrderRule, 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 R1.issystemsrule=2
else    
    insert  #t_KS
    SELECT R1.Link_Rule, OrderRule, 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)

    drop table #REPORT_CONTROL_ROWS

--and (R1.Link_Rule in (select Link_Rule from @t_Rules))

                if @cProgressTable <>'' begin
                    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Размножение правил'', percents = 30'
                    execute(@strProgressExec)
                end
    exec dbo.RO_RAZMNOJ_KS -- размножаем правила
--удалим все ненужные правила. 


insert @NRULES
select link_rule,orders,
        sum(
        case when RC.val_type in(1,2,4) then 1
             when RC.sign in('>','<','>=','<=','<>') then 1
             else 0 end)    
       from #T_KS RC group by link_rule,orders
    

UPDATE @NRULES
       set include=1       
FROM  @NRULES A
where  EXISTS(select * from #report_summa RS with (nolock),#T_KS  RRC with (nolock) where RRC.val_type=0 and RRC.link_rule=A.link_rule and RRC.orders=A.orders and RS.link_col=RRC.linkcol and RS.link_row=RRC.linkrow )  
       OR EXISTS(select * from #report_dinamics RS with (nolock),#T_KS RRC with (nolock) where RRC.val_type=3 and RRC.link_rule=A.link_rule and RRC.orders=A.orders  and RS.link_col=RRC.linkcol ) 

DELETE #T_KS 
FROM @NRULES A WHERE A.include=0 and A.link_rule=#T_KS.link_rule and A.orders=#T_KS.orders        
     
end 


   --если проверяем одну таблицу отчета - удаляем лишние правила     
   IF @cTables<>'' and @cTables<>'-1'
       begin
               set @execstr='DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE TK.LinkTable not in ('+@cTables+') AND Tk.LinkTable is not NULL)'
               exec(@execstr) 
       end 

    insert #t_znak (OrderRow, Link_Rule, orders,[sign])
    SELECT OrderRow, Link_Rule, orders,[sign]
    FROM #t_KS B
    WHERE [sign] = '=' or [sign] = '>=' or [sign] = '<=' or [sign] = '<>' or [sign] = '>' or [sign] = '<'

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 40'
    execute(@strProgressExec)
end


--для простых правил используем быстрое вычисление.
IF not EXISTS(select * from #t_ks where sign not in ('+','-','=','>','<','>=','<=','<>') or Exec_proc<>'' or  val_type in (2)) 
begin
-- подготовка к вычислению
   --сдвиг  знаков 
   insert @t_minus
   select distinct link_rule,orderrow from #t_ks where sign in ('-')

--select distinct link_rule,orderrow,sign  from #t_ks A where A.link_rule in (select link_rule from @t_minus) and A.orderrow in (select orderrow-1 from @t_minus)  

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 41'
    execute(@strProgressExec)
end




if object_id('tempdb..#sign') is not NULL 
begin
  drop table #sign 
end
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]=
    case when not D.sign in ('+','-') then D.sign else  (case when not A.sign  in ('+','-') then '+' else isnull(A.SIGN,'+') end) end 
    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)

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 42'
    execute(@strProgressExec)
end

      INSERT @ResultValue 
        select A.Link_rule,A.orders,'',sum(LeftValue),sum(RightValue) from 
       (select A.Link_rule,A.orders,
       SUM(
       CASE WHEN A.orderRow<=B.orderRow then  
       (CASE WHEN A.[sign] in ('+','=','>','<','>=','<=','<>') and  val_type=0 THEN RS.Summa 
            WHEN A.[sign] = '-' and  val_type=0 THEN -RS.Summa 
            WHEN A.[sign]  in ('+','=','>','<','>=','<=','<>') and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
            ELSE 0 END) else 0 end) as LeftValue,
       SUM(
       CASE WHEN A.orderRow>B.orderRow then  
       (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) else 0 end) as  RightValue
             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) LEFT JOIN #T_ZNAK B ON A.link_rule=B.link_Rule AND A.orders=B.orders
                        where RS.summa<>0 and RS.Link_Saved_Form=@LSF
                group by A.link_rule,A.orders
       union all  
       select A.Link_rule,A.orders,
       SUM(
       CASE WHEN isnull(A.orderRow,0)<=isnull(B.orderRow,0) then  
       (CASE WHEN A.[sign] in ('+','=','>','<','>=','<=','<>') and  val_type=3 THEN RS.Float_val 
            WHEN A.[sign] = '-' and  val_type=30 THEN -RS.Float_val
            WHEN A.[sign]  in ('+','=','>','<','>=','<=','<>') and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
            ELSE 0 END) else 0 end) as LeftValue,
       SUM(
       CASE WHEN isnull(A.orderRow,0)>isnull(B.orderRow,0) then  
       (CASE WHEN A.[sign] = '+' and  val_type=3 THEN RS.Float_val 
            WHEN A.[sign] = '-' and  val_type=3 THEN -RS.Float_val
            WHEN A.[sign] = '+' and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
              ELSE 0 END) else 0 end) as  RightValue
             from #report_dinamics RS LEFT HASH JOIN #T_KS A ON 
                        RS.link_col=A.linkcol and RS.code_row=A.coderow and A.val_type in (3,1) LEFT JOIN #T_ZNAK B ON A.link_rule=B.link_Rule AND A.orders=B.orders
                        where RS.float_val<>0 and RS.link_sf=@LSF
                group by A.link_rule,A.orders
       union all  
       select A.Link_rule,case when A.orders='' then B.orders else A.orders end ,
       SUM(
       CASE WHEN A.orderRow<=B.orderRow then  
       (CASE WHEN A.[sign] in ('+','=','>','<','>=','<=','<>') and  val_type=3 THEN 0 
            WHEN A.[sign] = '-' and  val_type=30 THEN 0
            WHEN A.[sign]  in ('+','=','>','<','>=','<=','<>') and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
            ELSE 0 END) else 0 end) as LeftValue,
       SUM(
       CASE WHEN A.orderRow>B.orderRow then  
       (CASE WHEN A.[sign] = '+' and  val_type=3 THEN 0
            WHEN A.[sign] = '-' and  val_type=3 THEN 0
            WHEN A.[sign] = '+' and  val_type=1 THEN A.Factor
            WHEN A.[sign] = '-' and  val_type=1 THEN -A.Factor
              ELSE 0 END) else 0 end) as  RightValue
             from #T_KS A 
                        LEFT JOIN #T_ZNAK B ON A.link_rule=B.link_Rule AND (A.orders='')
                        where val_type=1
            group by A.link_rule,case when A.orders='' then B.orders else A.orders end
        ) A
        group by A.link_rule,A.orders



if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 45'
    execute(@strProgressExec)
end



                



--SELECT * FROM #T_KS WHERE LINK_rule=     659877
--SELECT * FROM @resultvalue WHERE LINK_rule=     659877

    UPDATE @ResultValue
    SET sign=isnull((select top 1 sign from #T_ZNAK B where  B.link_rule=C.link_rule and B.orders=C.orders),'=')
    FROM @resultValue C  

--select * from @ResultValue where link_rule=963920  order by link_rule,orders

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование протокола проверки КС'', percents = 90'
        execute(@strProgressExec)
    end

       --формируем протокол 
    select @rounds = max(Val_Len) from #REPORT_COLOUMNS RC left join #report_tables RT on RC.Link_Table = RT.Link_Table left join report_saved_forms RSF on RT.Link_Form = RSF.Link_Form
    where RSF.Link_Saved_form = @lsf and RC.col_type = 0
     --найдем ошибки




    insert @Error (Link_rule,orders)
     select  a.link_rule,a.orders
     from @ResultValue A
     WHERE  dbo.RO_CONDITION_EVAL_RULE(0, 0, 0, 0, 0, round(A.LeftValue, @rounds), round(A.RightValue, @rounds), A.Sign, '', '',@nprecision) = 0



    insert @t_ExRes (Link_Rule,OrderRow,orders,ord,cformula,cKod ,cDoc ,cTable ,cCol,cValue)
    select distinct B.link_rule, 0, '',1,'№'+LTRIM(STR(B.OrderRule)),'',LEFT(B.str_rule,2000),'','','' res 
       from @Error A LEFT JOIN REPORT_CONTROL_RULES B (NOLOCK) ON A.link_rule=B.link_Rule 
    union
    select B.link_rule, B.OrderRow, A.orders,4,'№'+LTRIM(STR(B.OrderRule)),'Константа:'+RTRIM(B.sign),'','','',LTRIM(str(isnull(B.Factor, 0))) res 
       from @Error A LEFT JOIN #T_KS B ON A.link_rule=B.link_Rule AND (A.orders=B.orders or rtrim(isnull(B.Orders,''))='')
     Where B.val_type=1 
    union
    select T.link_rule, T.OrderRow,T.orders,4,'№'+LTRIM(STR(T.OrderRule)),RTRIM(T.sign)+RTRIM(D.code),F.Code,'№' + LTRIM(STR(B.orders))+' ('+RTRIM((B.name))+')','№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(isnull(A.summa,0),15,2)) res 
    from   #report_tables B,#REPORT_COLOUMNS C,#I_REPORT_ROWS D,#REPORT_FORMS F,@Error E  LEFT JOIN #T_KS T ON E.link_rule=T.link_Rule AND E.orders=T.orders
    left join #REPORT_SUMMA A ON A.link_col=T.linkCol and A.link_Row=T.linkRow and A.Link_Saved_Form=@LSF
     Where  T.linktable=B.link_table and C.link_table=T.linkTable AND T.linkcol=C.link_col and D.link_row=T.linkRow AND F.link_form=B.link_form and T.val_type=0 and not isnull(A.summa,0)=case when @del_null_ks=1 then 0 else isnull(A.summa,0)+1 end
    union
    select T.link_rule, T.OrderRow,T.orders,4,'№'+LTRIM(STR(T.OrderRule)),RTRIM(T.sign)+RTRIM(T.codeRow),F.Code,'№' + LTRIM(STR(B.orders))+' ('+RTRIM((B.name))+')','№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(isnull(A.Float_val,0),15,2)) res 
    from  #report_tables B,#REPORT_COLOUMNS C,#REPORT_FORMS F,@Error E  LEFT JOIN #T_KS T ON E.link_rule=T.link_Rule AND E.orders=T.orders 
     LEFT JOIN #REPORT_DINAMICS A ON  A.link_col=T.linkCol and A.Code_Row=T.CodeRow and A.link_sf=@LSF 
     Where   T.linktable=B.link_table and C.link_table=T.linkTable AND T.linkcol=C.link_col AND F.link_form=B.link_form and T.val_type=3  and not isnull(A.float_val,0)=case when @del_null_ks=1 then 0 else isnull(A.float_val,0)+1 end
    union
    select A.link_rule, 0,A.orders,7,'-','','Результат слева','','',  LTRIM(convert(varchar(50), isnull(B.LeftValue,0))) res 
       from @Error A,@ResultValue B Where A.link_rule=B.link_Rule AND A.orders=B.orders
   union 
   select A.link_rule, 0,A.orders,8,'-','','Результат справа','','',  LTRIM(convert(varchar(50), isnull(B.RightValue,0))) res 
       from @Error A,@ResultValue B Where A.link_rule=B.link_Rule AND A.orders=B.orders
    union
    select A.link_rule, 0,A.orders,9,'-','','Отклонение','','','<font color="#ff0000">'+ LTRIM(convert(varchar(50),(isnull(B.LeftValue,0)-isnull(B.RightValue,0)))) res 
       from @Error A,@ResultValue B Where A.link_rule=B.link_Rule AND A.orders=B.orders
    order by 1,2
end
else
begin
-----------------конец вычислений простых правил

--select 111
    -- ВЫЧИСЛЕНИЕ VALUE - ЛИБО ЯЧЕЙКА, ЛИБО КОНСТАНТА, ЛИБО РЕЗУЛЬТАТ ВЫПОЛНЕНИЯ ПРОЦЕДУРЫ
    update #t_KS
    set Value = case when Val_Type = 0 
      then isnull((select round(summa, Val_Len) from #REPORT_SUMMA RS with (nolock) left join #REPORT_COLOUMNS RC with (nolock) 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 with (nolock) on Link_SF = @LSF and RD.Link_Col = RC.Link_Col where RD.Link_Col = LinkCol and Code_Row = CodeRow), 0)
      end

    update #t_KS
    set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' '))) + ', ' + LTRIM(STR(@LSF))
    where val_type = 2
    update #t_KS
    set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
    where val_type = 2

-----------------
-----------------


IF EXISTS(select * from #t_KS where Val_Type = 2)
begin
    set ansi_warnings OFF
    SET ARITHABORT OFF
    SET ARITHIGNORE OFF
    
    declare Cur1 cursor static local
    for select Link_Rule, OrderRow, Exec_Proc, orders from #t_KS where Val_Type = 2 AND RTRIM(ISNULL(Exec_Proc, '')) <> ''
		order by orderRule
    open Cur1
    fetch next from Cur1
    into @linkRule, @OrderRow, @ExecProc, @ordersRule
    while @@fetch_status = 0
    begin

	 print @ExecProc     
	 insert #Val execute(@ExecProc)
     update #t_KS set Value = isnull(val,0) from #Val where Link_Rule = @LinkRule and OrderRow = @OrderRow and orders = @OrdersRule
     delete from #Val
--      truncate table #Val
      fetch next from Cur1
      into @linkRule, @OrderRow, @ExecProc, @ordersRule
    end
    close Cur1
    deallocate Cur1
    
    set ansi_warnings ON
    SET ARITHABORT ON
    SET ARITHIGNORE ON
end



--    exec dbo.RO_CHECK_KS_FILTR_MASK -- проверка по фильтрам и маскам
    -- ОТДЕЛЯЕМ ЛЕВЫЕ И ПРАВЫЕ ЧАСТИ
   
    insert  @t_LeftPart_V
    SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #t_znak B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders or A.orders='') and A.OrderRow <= B.OrderRow
    
    insert  @t_RightPart_V
    SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #t_znak B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders or A.orders='') and A.OrderRow > B.OrderRow
   
    insert  @t_LeftPart_VEx
    SELECT *
    FROM @t_LeftPart_V
    
    insert  @t_RightPart_VEx
    SELECT *
    FROM @t_RightPart_V

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 41'
    execute(@strProgressExec)
end

    -- ВЫЧИСЛЕНИЕ ПРАВИЛ
    --  declare @t_tmp table (lc int, lr int, lrule int, V float(53), o varchar(250), s char(2), cr varchar(50))
    update  @t_RightPart_V
    set OrderRow = OrderRow - oRow
    from (select Link_Rule as lr, max(OrderRow) as oRow from @t_LeftPart_V group by link_rule) A
    where lr = Link_Rule
    set @i = 2
        
    IF exists(select * from @t_LeftPart_V where OrderRow = 0)
        Update @t_LeftPart_V set orderrow=orderrow+1

    while exists(select * from @t_LeftPart_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_LeftPart_V where orderRow = @i
    
        update @t_LeftPart_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_LeftPart_V where OrderRow = @i
        set @i = @i + 1
    end
   

    insert #t_znak_not_plus (Link_Rule, orders)
    select distinct Link_Rule, orders
    from @t_RightPart_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, NULL as CodeRow, 0 as Factor, ' ' as Exec_Proc, ' ' as Exec_Proc_Desc, sum(Value) as Value, orders
    from @t_RightPart_V A
    where not exists(select top 1 * 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_RightPart_V where link_rule in (select distinct Link_rule from #t_sum)
  */  

  insert #t_sum
  select Link_Rule, OrderRule, OrderRow, 0 as Val_Type, '+' as Sign, NULL as LinkTable, NULL as LinkCol, NULL as LinkRow, '' as CodeRow, 0 as Factor, ' ' as Exec_Proc,'',  sum(Value) as Value, orders
  from @t_RightPart_V A
  where (select count(*) from @t_RightPart_V B where A.link_rule = B.link_rule and A.orders = B.orders and A.orderrow=B.orderrow)>1
  group by link_rule, OrderRule, orders,orderrow

--select * from #t_sum 
  delete @t_RightPart_V
  from @t_RightPart_V K inner hash join #t_sum S on K.Link_Rule = S.Link_Rule and K.orders=S.orders and K.orderrow=S.orderrow

    set @i = 2



if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 43'
    execute(@strProgressExec)
end


    while exists(select * from @t_RightPart_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_RightPart_V where orderRow = @i

        update @t_RightPart_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 or rtrim(isnull(A.O,''))='')
    

        delete @t_tmp
        delete @t_RightPart_V where OrderRow = @i
        set @i = @i + 1
    end

--    insert @t_RightPart_V
--    select * from #t_sum
    
    select @rounds = max(Val_Len) from #REPORT_COLOUMNS RC left join #report_tables RT on RC.Link_Table = RT.Link_Table left join report_saved_forms RSF on RT.Link_Form = RSF.Link_Form
    where RSF.Link_Saved_form = @lsf and RC.col_type = 0
    
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка КС'', percents = 44'
    execute(@strProgressExec)
end

--select * from @t_RightPart_V where link_rule=  1328530 and orders='0301010000' order by value

 update @t_RightPart_V
  set value = round(value,@rounds)  

  update @t_LeftPart_V
  set value = round(value,@rounds)  

--select * from @t_RightPart_V where link_rule=  1328530 and orders='0301010000' order by value

    insert @t_exData (Link_rule,LinkCol,LinkRow, OrderRow, orders, err,err1)
     select  a.link_rule,a.LinkCol,a.LinkRow, a.OrderRow, a.orders,case when A.Value is NULL or B.Value is null then '    Ошибка правила №' + LTRIM(STR(A.OrderRule)) + ' ' + str_rule  + CHAR(10) 
         when dbo.RO_CONDITION_EVAL_RULE(0, 0, 0, 0, 0, round(A.Value, @rounds), round(B.Value, @rounds), A.Sign, '', '',@nprecision) = 0 then '№'+LTRIM(STR(A.OrderRule)) + '##' + LTRIM(STR(A.Value - B.Value, 14, 4))   else '' end,
         case when dbo.RO_CONDITION_EVAL_RULE(0, 0, 0, 0, 0, round(A.Value, @rounds), round(B.Value, @rounds), A.Sign, '', '',@nprecision) = 0 then '№'+LTRIM(STR(A.OrderRule)) /*+' '+str_rule*/ else '' end
     from @t_LeftPart_V A, @t_RightPart_V B, #REPORT_CONTROL_RULES C
     where A.link_Rule = B.link_rule and A.orders = B.orders and A.orderRule = B.orderRule and A.Link_Rule = C.Link_Rule
    
    delete @t_exData where rtrim(isnull(err, '')) = ''

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование протокола проверки КС'', percents = 90'
        execute(@strProgressExec)
    end


    insert @t_ExRes (Link_Rule,orderRow, orders,ord,cformula,cKod ,cDoc ,cTable ,cCol,cValue)
    select distinct B.link_rule, 0, '',1,'№'+LTRIM(STR(B.OrderRule)),'',LEFT(B.str_rule,2000),'','','' res 
       from @t_ExData  A LEFT JOIN REPORT_CONTROL_RULES B (NOLOCK) ON A.link_rule=B.link_Rule 
    union
    select E.link_rule, E.OrderRow, E.orders,2,E.err1,'','','','','' res from @t_ExData E
    union 
    select A.link_rule, A.OrderRow, E.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),'Константа:'+RTRIM(A.sign),'','','',LTRIM(str(isnull(A.Factor, 0))) res from @t_leftPart_VEx A,@t_ExData E
     Where A.link_rule=E.link_rule and  A.val_type=1 and (A.orders=E.orders)-- or A.orders = '')
    union
    select A.link_rule, A.OrderRow,A.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(D.code)+RTRIM(A.sign),F.Code,'№' + LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_LeftPart_VEx A,#report_tables B,#REPORT_COLOUMNS C,#I_REPORT_ROWS D,@t_ExData E,#REPORT_FORMS F
     Where A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and D.link_row=A.linkRow AND A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form
    union
    select A.link_rule, A.OrderRow,A.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(A.coderow)+RTRIM(A.sign),F.Code,'№' + LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_LeftPart_VEx A,#report_tables B,#REPORT_COLOUMNS C,@t_ExData E,#REPORT_FORMS F
     Where A.linkrow is null and A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and  A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form
    union
    select A.link_rule, A.OrderRow,A.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(D.code)+RTRIM(A.sign),F.Code,'№' + LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_RightPart_VEx A,#report_tables B,#REPORT_COLOUMNS C,#I_REPORT_ROWS D,@t_ExData E,#REPORT_FORMS F
     Where A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and D.link_row=A.linkRow AND A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form
    union 
    select A.link_rule, A.OrderRow,A.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),LEFT(RTRIM(A.Exec_Proc_Desc),99)+RTRIM(A.sign),'','','',LTRIM(str(A.value,15,2)) res 
    from @t_RightPart_VEx A,@t_ExData E
     Where   A.orders=E.orders and A.link_rule=E.link_rule  and A.val_type=2
    union 
     select A.link_rule, A.OrderRow,E.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(A.coderow)+RTRIM(A.sign),F.Code,'№' + LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_RightPart_VEx A,#report_tables B,#REPORT_COLOUMNS C,@t_ExData E,#REPORT_FORMS F
     Where A.linkrow is null and A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col AND (A.orders=E.orders or A.orders='') and A.link_rule=E.link_rule  and F.link_form=B.link_form
    union
    select A.link_rule, A.OrderRow,E.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),'Константа:'+RTRIM(A.sign),'','','',LTRIM(str(isnull(A.Factor, 0))) res from @t_rightPart_VEx A,@t_ExData E
     Where A.link_rule=E.link_rule and  A.val_type=1 --and A.orders=E.orders
    union
    select A.link_rule, A.OrderRow,A.orders,7,'-','','Результат справа','','',  LTRIM(convert(varchar(50), isnull(A.Value,0))) res 
    from  @t_RightPart_V A,@t_ExData E where  A.orders=E.orders and A.link_rule=E.link_rule
    union
    select A.link_rule, A.OrderRow,A.orders,8,'-','','Отклонение','','','<font color="#ff0000">'+RTRIM(RIGHT(E.err, LEN(E.Err) - CHARINDEX('##', E.Err)-1)) res 
    from  @t_RightPart_V A,@t_ExData E where  A.orders=E.orders and A.link_rule=E.link_rule
    order by 1,2
    
end     
    set @i = isnull((select max(orders) from #Res),0) + 1
    
    insert #Res (orders,res,cKod,cDoc,cTable,cCol,cValue)
    select @i,cformula,ckod,cdoc,ctable,ccol,cvalue from @t_ExRes order by link_rule,orders, ord, OrderRow
    
    delete #Res where rtrim(isnull(res, '')) = ''
    
    select @i = max(orders) from #Res

	declare @count_err1 int
	set @count_err1=0
	select @count_err1=count(*) from #res where cdoc='Отклонение'
    
--    IF @i = @cnt
--для 14 формы
	IF @count_err1=0 and not exists(select * from #res where cdoc like '%Шифр строки%')
    BEGIN
    insert #Res (orders, res, cdoc)
      values(@i + 1, '-', 'Проверка выполнена успешно')
    SET @bExcess = 0
    update Report_Saved_Forms -- Признак для формы о правильности
    set IsRightKS = 1
    where Link_Saved_Form = @LSF and @cTables=''
    END
    ELSE
    update Report_Saved_Forms -- Признак для формы о неправильности
    set IsRightKS = 2
    where Link_Saved_Form = @LSF

    insert #Res (orders, res, cKod)
      values(@i+2, '-', '')

    insert #Res (orders, res, cKod)
      values(@i+3, '-', '')
    
  end
end
else begin
------------------ МЕЖДОКУМЕНТНЫЕ КС -----------------------------------------
  if LEN(LTRIM(@LinksDepartment)) = 0
  begin
    exec dbo.X_GET_OWN_DEP_LINK @linkOrg output
    select @LinksDepartment = LTRIM(STR(Link)) from report_svod_tree where Link_Org = @linkOrg and type = 1
   end
  set @Year = YEAR(@dBegin)
  set @dBegin = case @PerType when 1 then LTRIM(STR(@Year)) + '1231' 
        when 2 then dateadd(quarter, @PerNom, LTRIM(STR(@Year)) + '0101') -1
        else dateadd(month, @PerNom, LTRIM(STR(@Year)) + '0101') - 1 end

  declare @LinksGroupKS_MAIN varchar(8000)
  declare @num_gr int,@num_gr_curr int

  set @LinksGroupKS_MAIN=@LinksGroupKS
  while LEN(LTRIM(@LinksDepartment)) > 0
  begin
    exec dbo.RO_FORMULA_FUNCTIONS 1, @LinksDepartment output, @subStr output, ' '
    set @linkTree = CONVERT(int, @subStr)
  
    set @linkOrg = NULL
    set @linkBudg = NULL
    set @IsSvod = 0
    select @linkOrg = Link_report_org, @linkBudg = Link_report_budg, @IsSvod = 1 - Childrens from dbo.ro_svod_tree where Link = @LinkTree
    SELECT @ctmp = '<B>Организация: ',
           @ctmp1 = '<B>Бюджет: ',
           @ctmp2 = '<B>Отчетная дата: ',
           @ctmp3 = '<B>Дата проверки: '

    select @ctmp = '<B>Организация: ' + Name from departments where Link = @linkOrg
    select @ctmp1 = '<B>Бюджет: ' + Name from dbo.[BI_DICTION_BUDG_TYPE] where [Link] = @linkBudg
    set @ctmp2 = '<B>Отчетная дата: ' + convert(varchar(10), @dBegin, 104)
    set @ctmp3 = '<B>Дата проверки: ' + convert(varchar(30), getdate(), 120)

    select @varKSEventText = 'Организация: ' + RTRIM(Name) from departments where Link = @linkOrg
    select @varKSEventText = @varKSEventText+' Бюджет: ' + RTRIM(Name) from dbo.[BI_DICTION_BUDG_TYPE] where [Link] = @linkBudg
    set @varKSEventText = @varKSEventText+' Отчетная дата: ' + RTRIM(convert(varchar(10), @dBegin, 104))
    set @varKSEventText = @varKSEventText+' Дата проверки: ' + RTRIM(convert(varchar(30), getdate(), 120))


    EXECUTE WF_GENERATEEVENT 'Междокументный контроль', @varKSEventText, null, 'WF_DOCTASK',null

    set @i = isnull((select max(orders) from #Res),0) + 1

    insert #Res (orders, res, cdoc)
    values(@i, '<B>', @ctmp)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp1)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp2)
    insert #Res (orders, res, cdoc)
    values(@i + 1, '<B>', @ctmp3)

--проверяем по группам
  set @num_gr_curr=1
  set @num_gr=dbo.rn_getwordcount(@LinksGroupKS_MAIN,',')
  while @num_gr_curr<=@num_gr
  begin
	set @LinksGroupKS=dbo.rn_getwordnum(@LinksGroupKS_MAIN,@num_gr_curr,',')

    set @noKs=0
    delete #Rules
    truncate table #t_KS
 	select @cstr=left('Группа МДКС №'+rtrim(ltrim(code))+' '+rtrim(ltrim(name)),250) from report_group_ks where link_group_ks=cast(@LinksGroupKS as int)

	set @cProgress=(select 'Группа МДКС №'+rtrim(ltrim(code)) from report_group_ks where link_group_ks=cast(@LinksGroupKS as int))+(select ' Организация: ' + RTRIM(Name) from departments where Link = @linkOrg)

	--для 307 группы дополним коды
	declare @lt1 int,@lt2 int,@lt3 int,@lt1_2 int,@lt2_2 int,@lt3_2 int
	declare @link_form317 int
	if object_id('tempdb..#TMP_ITOG1') is not  NULL 
		begin
			drop table #TMP_ITOG1
		end

	create table #TMP_ITOG1 (link_table int,code varchar(50))
	if (SELECT code from report_group_ks where link_group_ks=cast(@LinksGroupKS as int))='307'
		begin
			select @lt1=link_table from report_tables where orders=1 and link_form=(select link_form from report_forms where code='0503317M')
			select @lt2=link_table from report_tables where orders=2 and link_form=(select link_form from report_forms where code='0503317M')
			select @lt3=link_table from report_tables where orders=3 and link_form=(select link_form from report_forms where code='0503317M')
			select @lt1_2=link_table from report_tables where orders=1 and link_form=(select link_form from report_forms where code='0503152M')
			select @lt2_2=link_table from report_tables where orders=2 and link_form=(select link_form from report_forms where code='0503152M')
			select @lt3_2=link_table from report_tables where orders=3 and link_form=(select link_form from report_forms where code='0503152M')
			select @link_form317=link_form from report_forms where code='0503317M'
			--итоговые строки
			insert #TMP_ITOG1 (link_table,code)
			select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form317,1)  

			--create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt1 from #i_report_dinamic_rows A where
			link_table=@lt1_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt1 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt1_2 from #i_report_dinamic_rows A where
			link_table=@lt1 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt1_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt1 and A.code_row=B.code)
---
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt2 from #i_report_dinamic_rows A where
			link_table=@lt2_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt2 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt2_2 from #i_report_dinamic_rows A where
			link_table=@lt2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt2_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt2 and A.code_row=B.code)

---
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt3 from #i_report_dinamic_rows A where
			link_table=@lt3_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt3 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt3_2 from #i_report_dinamic_rows A where
			link_table=@lt3 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt3_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt3 and A.code_row=B.code)
			drop table #TMP_ITOG1
		end
	--для 308 группы дополним коды
	if (SELECT code from report_group_ks where link_group_ks=cast(@LinksGroupKS as int))='308'
		begin
			select @lt1=link_table from report_tables where orders=1 and link_form=(select link_form from report_forms where code='0503117M')
			select @lt2=link_table from report_tables where orders=2 and link_form=(select link_form from report_forms where code='0503117M')
			select @lt3=link_table from report_tables where orders=3 and link_form=(select link_form from report_forms where code='0503117M')
			select @lt1_2=link_table from report_tables where orders=1 and link_form=(select link_form from report_forms where code='0503151M')
			select @lt2_2=link_table from report_tables where orders=2 and link_form=(select link_form from report_forms where code='0503151M')
			select @lt3_2=link_table from report_tables where orders=3 and link_form=(select link_form from report_forms where code='0503151M')
			select @link_form317=link_form from report_forms where code='0503117M'
			--итоговые строки
			insert #TMP_ITOG1 (link_table,code)
			select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form317,1)  
			

			--create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt1 from #i_report_dinamic_rows A where
			link_table=@lt1_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt1 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt1_2 from #i_report_dinamic_rows A where
			link_table=@lt1 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt1_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt1 and A.code_row=B.code)
---
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt2 from #i_report_dinamic_rows A where
			link_table=@lt2_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt2 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt2_2 from #i_report_dinamic_rows A where
			link_table=@lt2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt2_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt2 and A.code_row=B.code)
			and substring(code_row,15,3) not IN ('200','000','210','220','230','240','250','260','300','500','600')

---
			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt3 from #i_report_dinamic_rows A where
			link_table=@lt3_2 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt3 and B.code_row=A.code_row)

			insert #i_report_dinamic_rows (link_sf,code_row,link_table)
			select link_sf,code_row,@lt3_2 from #i_report_dinamic_rows A where
			link_table=@lt3 and not exists(select * from #i_report_dinamic_rows B where B.link_table=@lt3_2 and B.code_row=A.code_row)
			and not exists(select * from #tmp_itog1 B where A.link_table=@lt3 and A.code_row=B.code)
			drop table #TMP_ITOG1
		end
--select * from #listforms
--	select distinct code_row from #report_dinamics A where link_sf=20309
		

	set @i = isnull((select max(orders) from #Res),0) + 1
    insert #Res (orders, res, cdoc)
    values(@i, '<B>', left(@cstr,250))

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''1.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

			truncate table #ListForms_atr
            insert #ListForms_atr exec dbo.I_REPORT_ORG_FORMS_LIST @linkOrg, @dBegin, @perType, @perNom, @isSvod, @LinkBudg
			IF not exists(select * from #ListForms_atr)
				insert #ListForms_atr exec dbo.I_REPORT_ORG_FORMS_LIST @linkOrg, @dBegin, @perType, @perNom, @isSvod, null

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''2.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

            insert #Rules exec dbo.I_CONTROL_RULES_LIST_WITH_GROUP @linkOrg, 1, @perType, @perNom, @isSvod, @LinksGroupKS
			delete #ListForms_atr 
			where LinkForm not in (select isnull(A.Link_Form,0) from report_control_rows A (NOLOCK) inner join #rules B on A.link_rule=B.link_rule left loop join report_tables RT (nolock) on A.Link_Table = RT.Link_Table)

--select @linkOrg, 1, @perType, @perNom, @isSvod, @LinksGroupKS
--select * from  #Rules 
			select @cnt_f_r=count(*) from (select A.Link_Form from report_control_rows A (NOLOCK) inner join #rules B on A.link_rule=B.link_rule left loop join report_tables RT (nolock) on A.Link_Table = RT.Link_Table where A.link_form is not null group by A.link_form) A
			select distinct @cnt_f_f=count(linkform) from #ListForms_atr

			IF 	@cnt_f_f<=1 and @cnt_f_r>1
				  set @noKS=1 

--select * from #ListForms_atr
--end
--обработка атрибутов
--create table #ListForms (lsf int, linkForm int, codeForm char(20), startDate datetime)
--create table #atr (lsf int, atr varchar(50), str_val varchar(50))
    if NOT exists(select * from #ListForms_atr)
    begin
	  set @noKS=1		
      insert #Res (orders, res, cdoc) values (@i + 1, '-', 'Нет отчетов для этой группы МДКС') 
    end



    if (select count(*) from #Rules) = 0
    begin
	  set @noKS=1      
	  insert #Res (orders, res, cdoc) values (@i + 1, '-', 'Нет правил контрольных соотношений')
      insert #Res (orders, res, cdoc) values (@i + 1, '-', '')
	  set @num_gr_curr=@num_gr_curr+1
      CONTINUE
    end

		truncate table #Atr
		truncate table #Atr_empty
		insert #atr
		select A.lsf,B.code_atr,isnull(B.str_val,'') from #ListForms_atr A left join report_atribut_values B ON A.lsf=B.link_saved_form and B.code_atr in ('REPORTS_ATR_ADM','REPORTS_ATR_DATE','REPORTS_ATR_ACC')

		insert #atr_empty
		select A.lsf,B.code_atr,isnull(B.str_val,'') from #ListForms_atr A left join report_atribut_values B ON A.lsf=B.link_saved_form and B.code_atr in ('REPORTS_ATR_ADM','REPORTS_ATR_DATE','REPORTS_ATR_ACC')
		where B.str_val is null	

		truncate table #ListForms

    truncate table #ListForms
	select top 1 @atr=str_val,@code_atr=atr from #atr
	insert into #atr_cur (lsf, atr, str_val) select top 1 lsf, atr, str_val from #atr

	insert  #ListForms
	select lsf, linkForm, codeForm, startDate from #ListForms_atr A
	where A.lsf in (select lsf from #atr where str_val=@atr or (str_val='' and @atr='000') or (str_val='000' and @atr='')  or str_val='')
	
---отладка
--select * from #Atr
--select * from #ListForms
---
	set @name_atr_main=dbo.get_val(@code_atr,'SHORT_NAME',0)
	while exists(select * from #Atr)begin
		IF isnull(@atr,'')<>'' begin
			set @i = isnull((select max(orders) from #Res),0) + 1
			select @cstr='Проверка по атрибуту '+@name_atr_main+'='+@atr
			insert #Res (orders, res, cdoc)
			values(@i, '<B>', left(@cstr,250))
		end
		else begin
			set @i = isnull((select max(orders) from #Res),0) + 1
			select @cstr='Проверка форм без атрибутов'
			insert #Res (orders, res, cdoc)
			values(@i, '<B>', left(@cstr,250))
		end

	    delete #Rules

		truncate table #t_KS

		insert #Rules exec dbo.I_CONTROL_RULES_LIST_WITH_GROUP @linkOrg, 1, @perType, @perNom, @isSvod, @LinksGroupKS
		delete #atr where str_val=@atr  or (str_val='' and @atr='000') or (str_val='000' and @atr='')
		set @name_atr=case when  @atr<>'' then @name_atr_main+'='+@atr else '' end

		-- ПОЛУЧАЕМ ПРАВИЛА
		insert  #t_KS
		SELECT R1.Link_Rule, OrderRule, 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 (nolock) left join REPORT_CONTROL_ROWS R2 (nolock) on r1.Link_Rule = r2.Link_Rule
		WHERE R1.Link_Rule in (select link_rule from #Rules)

		if @cProgressTable <>'' begin
			set @strProgressExec = 'update '+@cProgressTable+' set msg = ''3.'+left(@cProgress,200)+''', percents = 40'
			execute(@strProgressExec)
		end


		set @Str1 = ''

		if exists(select top 1 * from report_tables A (NOLOCK) where link_table in (select linkTable from #t_KS where not linkTable is null) and not exists(select * from #ListForms where linkForm = A.Link_Form)) -- удаление правил, для которых нет отчетов
		begin
			set @noKS=1		
			insert #Res (orders, res, cdoc) values (@i + 1, '-', 'Отсутствуют отчеты: ') 
			insert #Res (orders, res, cdoc) 
			select @i + 1, '<B>', RTRIM(Code)+' '+ Name 
			from (select distinct rtrim(B.Code)+'(версия от '+convert(varchar(20),B.Start_Date,104)+') '+@name_atr code, B.Name from report_tables A (nolock) left join report_forms  B WITH (NOLOCK) on A.link_Form = B.Link_Form where link_table in (select linkTable from #t_KS where not linkTable is null) and not exists(select * from #ListForms where linkForm = A.Link_Form)) C
			set @orders = @orders + 3
  
			delete from @t_temp_M

			insert @t_temp_M
			select * from  #t_KS
			where (not linkTable is null) and not exists(select * from #ListForms LF left join report_tables RT (nolock) on LF.LinkForm = RT.Link_Form where RT.Link_Table = LinkTable)

			delete #t_KS
			where Link_Rule in (select Link_Rule from @t_temp_M)
    
			delete from @t_temp_M
		end
    
		delete #ListForms where LinkForm not in (select Link_Form from #t_KS M left loop join report_tables RT (nolock) on M.LinkTable = RT.Link_Table)

		truncate table #t_Col

		if @cProgressTable <>'' begin
			set @strProgressExec = 'update '+@cProgressTable+' set msg = ''4.'+left(@cProgress,200)+''', percents = 40'
			execute(@strProgressExec)
		end

		insert #t_Col (Link_Col, Name, Link_Table, Val_Len, OrderCol)
		select distinct 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 report_saved_forms RSF on RT.Link_Form = RSF.Link_Form
		  inner join #ListForms LF on RSF.Link_Saved_Form = LF.LSF

--select * from #t_ks

    exec dbo.RO_RAZMNOJ_KS -- размножение правил



--select * from #t_ks where link_rule=    1118314 order by orders 

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''5.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

    -- ВЫЧИСЛЕНИЕ VALUE - ЛИБО ЯЧЕЙКА, ЛИБО КОНСТАНТА, ЛИБО РЕЗУЛЬТАТ ВЫПОЛНЕНИЯ ПРОЦЕДУРЫ
    update #t_KS
      set Value = case when Val_Type = 0 
        then isnull((select top 1 round(summa, Val_Len) from #REPORT_SUMMA RS inner join #REPORT_COLOUMNS RC on RS.Link_Col = RC.Link_Col inner join #report_tables RT on RC.Link_Table = RT.Link_Table inner join #ListForms LF on RT.Link_Form = LF.LinkForm and RS.Link_Saved_Form = LF.LSF where RS.link_Col = LinkCol and Link_Row = LinkRow),0) 
        when Val_Type = 1 then isnull(Factor, 0) 
        when Val_Type = 3 then isnull((select top 1 round(float_val, Val_Len) from #REPORT_COLOUMNS RC inner join #REPORT_DINAMICS RD with (nolock) on RD.Link_Col = RC.Link_Col inner join #report_tables RT on RC.Link_Table = RT.Link_Table  inner join #ListForms LF on RT.Link_Form = LF.LinkForm and RD.Link_SF = LF.LSF where RC.Link_Col = LinkCol and Code_Row = CodeRow), 0)
        else 0
        end

    update #t_KS
    set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))
    where val_type = 2

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''6.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

   
--    set ansi_warnings OFF
--    SET ARITHABORT OFF
--    SET ARITHIGNORE OFF
-- select * from #ListForms

    select @begin_ord= isnull((select max(orders) from #Res),0) 

    declare Cur1 cursor static local
      for select Link_Rule, OrderRow, Exec_Proc, orders from #t_KS where Val_Type = 2 AND RTRIM(ISNULL(Exec_Proc, '')) <> ''
    open Cur1
    fetch next from Cur1
    into @linkRule, @OrderRow, @ExecProc, @ordersRule
    while @@fetch_status = 0
    begin
      --print  @ExecProc
      insert #Val 
      execute(@ExecProc)
      update #t_KS 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

  
--    set ansi_warnings ON
--    SET ARITHABORT ON
--    SET ARITHIGNORE ON
    
    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''7.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

    -- ОТДЕЛЯЕМ ЛЕВЫЕ И ПРАВЫЕ ЧАСТИ
    insert #t_znak (OrderRow, Link_Rule, orders)
    SELECT OrderRow, Link_Rule, orders
    FROM #t_KS B
    WHERE [sign] = '=' or [sign] = '>=' or [sign] = '<=' or [sign] = '<>' or [sign] = '>' or [sign] = '<'

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''8.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

    
    insert  @t_LeftPart_M
    SELECT A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, max(A.LinkRow), max(A.CodeRow), A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, SUM(A.Value), A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders  and not (A.orders = '' and A.val_type=1)) and A.OrderRow <= B.OrderRow
    group by A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol,  A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.orders

    insert  @t_LeftPart_M
    SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol,(A.LinkRow), (A.CodeRow), A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, (A.Value), A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = '' and A.val_type=1) and A.OrderRow <= B.OrderRow

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''9.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


    insert  @t_RightPart_M
    SELECT A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, max(A.LinkRow), max(A.CodeRow), A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, sum(A.Value), A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders and not (A.orders = '' and A.val_type=1)) and A.OrderRow > B.OrderRow 
    group by A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.orders

    insert  @t_RightPart_M  
      SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, (A.LinkRow), (A.CodeRow), A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, (A.Value), A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders ='' and A.val_type=1) and A.OrderRow > B.OrderRow 

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''10.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


    insert  @t_LeftPart_MEx
    SELECT A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders and not (A.orders = '' and A.val_type=1))  and A.OrderRow <= B.OrderRow
    union    
    SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = ''  and A.val_type=1)  and A.OrderRow <= B.OrderRow
 
    insert  @t_RightPart_MEx
    SELECT A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = B.orders and not (A.orders =  '' and A.val_type=1)) and A.OrderRow > B.OrderRow
    union 
    SELECT distinct A.Link_Rule, A.OrderRule, A.OrderRow, A.Val_Type, A.Sign, A.LinkTable, A.LinkCol, A.LinkRow, A.CodeRow, A.Factor, A.Exec_Proc, A.Exec_Proc_Desc, A.Value, A.orders
    FROM #T_ZNAK B inner join #t_KS A on B.Link_Rule = A.Link_Rule and (A.orders = ''  and A.val_type=1) and A.OrderRow > B.OrderRow
    

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''11.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


   -- ВЫЧИСЛЕНИЕ ПРАВИЛ
    update  @t_RightPart_M
    set OrderRow = OrderRow - oRow
    from (select Link_Rule as lr, max(OrderRow) as oRow from @t_LeftPart_M group by link_rule) A
    where lr = Link_Rule
    set @i = 2
    while exists(select * from @t_LeftPart_M 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_LeftPart_M where orderRow = @i
    
      update @t_LeftPart_M
      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, #ListForms B
      where OrderRow = 1 and link_rule = A.lRule and (A.o = orders or rtrim(isnull(A.O,''))='') and (LinkCol is NULL or LinkCol in (select Link_Col from #t_col RC left loop join #report_tables RT on RC.Link_Table = RT.Link_Table where RT.Link_Form = B.LinkForm))
    
      delete @t_tmp
      delete @t_LeftPart_M where OrderRow = @i
      set @i = @i + 1
    end
    
    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''12.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


  update @t_LeftPart_M
     set [sign]=B.sign
      from @t_LeftPart_M A left join (select C.sign,D.link_rule,D.orders from #t_ks C , #T_ZNAK D where C.link_rule=D.link_rule and C.orders=D.orders and C.orderrow=D.orderrow) B
         ON A.link_rule=B.link_rule and A.orders=B.orders
   

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''13.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


    insert #t_znak_not_plus (Link_Rule, orders)
    select distinct Link_Rule, orders
    from @t_RightPart_M 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, NULL as CodeRow, 0 as Factor, ' ' as Exec_Proc, ' ' as Exec_Proc_Desc, sum(Value) as Value, orders
    from @t_RightPart_M A
    where not exists(select top 1 * from #t_znak_not_plus B where A.link_rule = B.link_rule and A.orders = B.orders)
    group by link_rule, OrderRule, orders
*/    
  insert #t_sum
  select Link_Rule, OrderRule, OrderRow, 0 as Val_Type, '+' as Sign, NULL as LinkTable, NULL as LinkCol, NULL as LinkRow, '' as CodeRow, 0 as Factor, ' ' as Exec_Proc,'',  sum(Value) as Value, orders
  from @t_RightPart_M A
  where (select count(*) from @t_RightPart_M B where A.link_rule = B.link_rule and A.orders = B.orders and A.orderrow=B.orderrow)>1
  group by link_rule, OrderRule, orders,orderrow

--select * from #t_sum 
  delete @t_RightPart_M
  from @t_RightPart_m K inner hash join #t_sum S on K.Link_Rule = S.Link_Rule and K.orders=S.orders and K.orderrow=S.orderrow

--    delete @t_RightPart_M where link_rule in (select distinct Link_rule from #t_sum)
    

    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''14.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end

    set @i = 2
    while exists(select * from @t_RightPart_M 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_RightPart_M where orderRow = @i
    
      update @t_RightPart_M
      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, #ListForms B
      where OrderRow = 1 and link_rule = A.lRule and (A.o = orders or rtrim(isnull(A.O,''))='') and (LinkCol is NULL or LinkCol in (select Link_Col from #t_col RC left loop join #report_tables RT on RC.Link_Table = RT.Link_Table where RT.Link_Form = B.LinkForm))
    
      delete @t_tmp
      delete @t_RightPart_M where OrderRow = @i
      set @i = @i + 1
    end
    
    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''15.'+left(@cProgress,200)+''', percents = 40'
        execute(@strProgressExec)
    end


--    insert @t_RightPart_M
--    select * from #t_sum
    
     insert @t_exData (Link_rule,LinkCol,LinkRow,OrderRow,orders, err,err1)
     select  a.link_rule,a.LinkCol,a.LinkRow,a.OrderRow,a.orders,case when A.Value is NULL or B.Value is null then '    Ошибка правила №' + LTRIM(STR(A.OrderRule)) + ' ' + str_rule  + '##'
         when dbo.RO_CONDITION_EVAL_RULE(0, 0, 0, 0, 0, A.Value, B.Value, A.Sign, '', '',@nprecision) = 0 then '№'+LTRIM(STR(A.OrderRule)) + '##' + LTRIM(STR(A.Value - B.Value, 14, 4))   else '' end,
         case when dbo.RO_CONDITION_EVAL_RULE(0, 0, 0, 0, 0, A.Value, B.Value, A.Sign, '', '',@nprecision) = 0 then '№'+LTRIM(STR(A.OrderRule)) /*+' '+str_rule*/ else '' end
     from @t_LeftPart_M A left join @t_RightPart_M B on A.link_Rule = B.link_rule and 
     A.orders = B.orders and A.orderRule = B.orderRule left join #REPORT_CONTROL_RULES C on 
     A.Link_Rule = C.Link_Rule



     delete @t_exData where rtrim(isnull(err, '')) = ''
    
    if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование протокола проверки КС'', percents = 40'
        execute(@strProgressExec)
    end

 

    insert @t_ExRes (Link_Rule,OrderRow,orders,ord,cformula,cKod ,cDoc ,cTable ,cCol,cValue)
    select distinct B.link_rule, 0, '',1,'№'+LTRIM(STR(B.OrderRule)),'',LEFT(B.str_rule,2000),'','','' res 
       from @t_ExData  A LEFT JOIN REPORT_CONTROL_RULES B (NOLOCK) ON A.link_rule=B.link_Rule 
    union
    select E.link_rule,E.OrderRow,E.orders,2,E.err1,'','','','','' res from @t_ExData E
    union 
    select A.link_rule,A.OrderRow,E.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),'Константа:'+RTRIM(A.sign),'','','',LTRIM(str(isnull(A.Factor, 0))) res from @t_leftPart_MEx A,@t_ExData E
     Where A.link_rule=E.link_rule and  A.val_type=1 and (A.orders=E.orders or rtrim(isnull(A.Orders,''))='')
    union
    select A.link_rule,A.OrderRow,A.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(D.code)+RTRIM(A.sign),RTRIM(F.code)+' '+@name_atr,'№'+LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_LeftPart_MEx A,#report_tables B,#REPORT_COLOUMNS C,#I_REPORT_ROWS D,@t_ExData E,#REPORT_FORMS F
     Where A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and D.link_row=A.linkRow AND A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form  and not A.value=case when @del_null_ks=1 then 0 else A.value+1 end
    union 
    select A.link_rule,A.OrderRow,A.orders,4,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(A.coderow)+RTRIM(A.sign),RTRIM(F.code)+' '+@name_atr,'№'+LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_LeftPart_MEx A,#report_tables B,#REPORT_COLOUMNS C,@t_ExData E,#REPORT_FORMS F
     Where A.linkrow is null and A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and  A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form and not A.value=case when @del_null_ks=1 then 0 else A.value+1 end
    union
    select A.link_rule,A.OrderRow,A.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(D.code)+RTRIM(A.sign),RTRIM(F.code)+' '+@name_atr,'№'+LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_RightPart_MEx A,#report_tables B,#REPORT_COLOUMNS C,#I_REPORT_ROWS D,@t_ExData E,#REPORT_FORMS F
     Where A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col and D.link_row=A.linkRow AND A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form and not A.value=case when @del_null_ks=1 then 0 else A.value+1 end
    union 
    select A.link_rule,A.OrderRow,A.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),RTRIM(A.coderow)+RTRIM(A.sign),RTRIM(F.code)+' '+@name_atr,'№'+LTRIM(STR(B.orders)),'№'+LTRIM(str(C.EXPORT_ORDER)),LTRIM(str(A.value,15,2)) res 
    from @t_RightPart_MEx A,#report_tables B,#REPORT_COLOUMNS C,@t_ExData E,#REPORT_FORMS F
     Where A.linkrow is null and A.linktable=B.link_table and C.link_table=A.linkTable AND A.linkcol=C.link_col AND A.orders=E.orders and A.link_rule=E.link_rule  and F.link_form=B.link_form and not A.value=case when @del_null_ks=1 then 0 else A.value+1 end
    union
    select A.link_rule,A.OrderRow,E.orders,5,LEFT(E.err, CHARINDEX('##', E.err) - 1),'Константа:'+RTRIM(A.sign),'','','',LTRIM(str(isnull(A.Factor, 0))) res from @t_rightPart_MEx A,@t_ExData E
     Where A.link_rule=E.link_rule and  A.val_type=1 and (A.orders=E.orders or rtrim(isnull(A.Orders,''))='')
    union
    select A.link_rule,A.OrderRow,A.orders,7,'-','','Результат слева','','',  LTRIM(convert(varchar(50), isnull(A.Value,0))) res 
    from  @t_lEFTPart_M A,@t_ExData E where  A.orders=E.orders and A.link_rule=E.link_rule
    union
    select A.link_rule,A.OrderRow,A.orders,7,'-','','Результат справа','','',  LTRIM(convert(varchar(50), isnull(A.Value,0))) res 
    from  @t_RightPart_M A,@t_ExData E where  A.orders=E.orders and A.link_rule=E.link_rule
    union
    select A.link_rule,A.OrderRow,A.orders,8,'-','','Отклонение','','','<font color="#ff0000">'+RTRIM(RIGHT(E.err, LEN(E.Err) - CHARINDEX('##', E.Err)-1)) res 
    from  @t_RightPart_M A,@t_ExData E where  A.orders=E.orders and A.link_rule=E.link_rule
    order by 1,2

    IF (select count(*) from @t_ExRes)>0 or (@begin_ord<(select max(orders) from #Res)) 
		set @noKS=1
    --select * from @t_exRes
    
   
    set @i = isnull((select max(orders) from #Res),0) + 1

    insert #Res (orders,res,cKod,cDoc,cTable,cCol,cValue)
    select @i,cformula,ckod,cdoc,ctable,ccol,cvalue from @t_ExRes order by link_rule,orders,ord,OrderRow


    --select * from #Res
        
    delete #Res where res = ''--CHAR(9)

    if --(select max(ord) from #Res) = (select max(ord) from #Res where res = '<B>') and 
		@noKS=0
    begin
      insert #Res (orders, res, cdoc)
      values(@i, '-', 'Проверка КС выполнена успешно')
      SET @bExcess = 0
      --  set @orders = @orders + 1
    end
    insert #Res (orders, res, cdoc) values (@i, '-', '')
    insert #Res (orders, res, cdoc) values (@i, '-', '')
    delete @t_LeftPart_M
    delete @t_RightPart_M
    delete @t_temp_M
    delete @t_LeftPart_Mex
    delete @t_RightPart_Mex
    delete @t_ExRes
    delete @t_ExData
    delete #T_ZNAK
    truncate table #t_sum
    truncate table #t_znak_not_plus
    truncate table #ListForms
	truncate table #atr_cur
	select top 1 @atr=str_val,@code_atr=atr from #atr
	insert into #atr_cur (lsf, atr, str_val) select top 1 lsf, atr, str_val from #atr

    set	@noKS=0

	insert  #ListForms
	select lsf, linkForm, codeForm, startDate from #ListForms_atr A
	where A.lsf in (select lsf from #atr where str_val=@atr or (str_val='' and @atr='000') or (str_val='000' and @atr='') or str_val='')
		or A.lsf in (select lsf from #atr_empty)

	end--atr

	  set @num_gr_curr=@num_gr_curr+1
  end
end
end
declare @count_err int
set @count_err=0
select @count_err=count(*) from #res where cdoc='Отклонение'
set @i = isnull((select max(orders) from #Res),0) + 1
IF @count_err>0
    begin
        insert #Res (orders,res,cKod,cDoc,cTable,cCol,cValue)
        select @i+1,'','','Количество ошибок: '+ltrim(str(@count_err)),'','',''

        insert #Res (orders,res,cKod,cDoc,cTable,cCol,cValue)
        select 0,'','','Количество ошибок: '+ltrim(str(@count_err)),'','',''

    end


IF @tmpTable=''
	select isnull(res,'') res,isnull(cdoc,'') cdoc,isnull(ctable,'') ctable,isnull(ckod,'') ckod,isnull(ccol,'') ccol,isnull(cvalue,'') value from #Res order by orders,ord
ELSE
	begin
		set @ExecStr='insert '+@tmpTable+' select isnull(res,'''') res,isnull(cdoc,'''') cdoc,isnull(ctable,'''') ctable,isnull(ckod,'''') ckod,isnull(ccol,'''') ccol,isnull(cvalue,'''') value from #Res order by orders,ord'
		
		execute(	@ExecStr)
	end

drop table #Rules
drop table #ListForms
drop table #ListForms_atr
drop table #atr
drop table #atr_cur
drop table #atr_empty
drop table #t_mdks
drop table #ListFormsV
drop table #Val
drop table #Res
drop table #t_KS
drop table #REPORT_FORMS
drop table #report_tables
drop table #REPORT_COLOUMNS
drop table #I_REPORT_ROWS
drop table #i_report_dinamic_rows
drop table #REPORT_CONTROL_RULES
drop table #REPORT_SUMMA
drop table #REPORT_DINAMICS
drop table #link_col_summa
drop table #tmp_group_ks
drop table #link_uzel
drop table #t_znak
drop table #t_znak_not_plus
drop table #t_sum
drop table #table_ks



GO
GRANT EXECUTE ON dbo.[RO_CHECK_KS] 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_CREATE_PROV_ZAYAVKA_KR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_CREATE_PROV_ZAYAVKA_KR]
GO








CREATE	PROCEDURE BB_CREATE_PROV_ZAYAVKA_KR
	@iLinkDoc 	int,
	@iDel		tinyint = 0,
	@iTypLink	int = null	
AS

DECLARE 
	@iLink 		int,
	@iLinkUp 	int,
	@cNameOper 	varchar(250),
	@nSumma 	numeric(28,2),
	@iKBK 		int,
	@iSGU 		int, 
	@iDtACC		int,
	@iEKR 		int, 
	@iDopCl 	int,
	@cSource 	int,
 
	@iDep 		int, 
	@iDepAcc 	int, 
	@iKor 		int, 
	@iKorAcc 	int, 
	@iLinkGP1 	int,
	@iOrders 	int,
	@iRet		int,
	@cErrTxt 	varchar(60),
	@cG2Name 	varchar(254),
	@iOsnovLink	int


IF @iLinkDoc IS NULL OR @iLinkDoc <= 0
	RETURN -1	


select @iKorAcc = ACC
from dbo.G_PROV
WHERE LINK = @iLinkDoc

select @iDep = DA.LINK_UP, @iDepAcc  = DA.LINK
from dbo.FINANSE_PAYS F
inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = F.D_ACC
WHERE F.LINK = @iLinkDoc

select @iOsnovLink = LINK_OSNOV
from dbo.ZAYAVKA_KR_OSNOV
WHERE LINK_UP = @iLinkDoc and OSN = 1


DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR
SELECT LINK, LINK_KBK, LINK_SGU, LINK_DCL, LINK_DT_ACC, SOURCE, SUMMA
FROM  dbo.ZAYAVKA_KR_TABLE 
where SUMMA <> 0 and LINK_UP = @iLinkDoc

IF @iDel = 1
	DELETE FROM G_PROV1 WHERE LINK_UP = @iLinkDoc
if @iTypLink is null
	SELECT TOP 1 @iTypLink = TO_LINK 
	FROM dbo.BB_ZAYAVKA_KR_OPTIONS

IF @iTypLink IS NULL OR @iTypLink = 0 or @iTypLink < -1
	RETURN -2	

SELECT @cNameOper = NAME_OPER
FROM dbo.G_PROV1 
WHERE LINK = @iTypLink


SET @iOrders = 0

OPEN GRID_CUR
FETCH NEXT FROM GRID_CUR INTO @iLink, @iKBK, @iEKR, @iDopCL, @iDtACC, @cSource, @nSumma
WHILE @@FETCH_STATUS = 0
BEGIN
	if @iTypLink = -1
		select @iTypLink = A.OPER, @cNameOper = A.COMMENT 
		from (select TOP 1 OPER, COMMENT 
				from dbo.IMPORT_OPER O
				inner join dbo.KL_KBK KBK on KBK.LINK = @iKBK and replace(KBK.CODE,'.','') LIKE rtrim(KBK) + '%' 
				inner join dbo.KOSGU SGU on SGU.LINK = @iEKR and replace(SGU.CODE,'.','') LIKE rtrim(SGU) + '%' 
				where O.USED = 1
				order BY O.ORDERS) A
				
	IF @iTypLink IS NULL OR @iTypLink < 1
		RETURN -2	
		
	SET @iOrders = @iOrders + 1
	SET @iLinkGP1 = NULL
	EXEC X_UPDATE_G_PROV1 @iLinkGP1 OUTPUT, @iLinkDoc, @iTypLink, @cNameOper, @iOrders

	IF @iLinkGP1 IS NULL
		RETURN -3	
	
	EXEC @iRet = FB_SAVE_G_PROV2_AP_LIMIT @iLinkGP1, @iTypLink, @nSumma, NULL, @iKBK, @iEKR,  @iDopCL, NULL, @iDep, @iDepAcc, @cNameOper, @cSource, @iKor, @iKorAcc, @iDtACC, 0,0,@iOsnovLink
	IF @iRet <> 0
	  BEGIN
	    	SET @cErrTxt = CASE @iRet
				WHEN -1 THEN '"Не задан линк операции"'
	
			   END
	    	PRINT 'Ошибка при записи проводки по Финансированию: '
		RETURN @iRet
	 END
	FETCH NEXT FROM GRID_CUR INTO @iLink, @iKBK, @iEKR, @iDopCL, @iDtACC, @cSource, @nSumma
END

CLOSE GRID_CUR
DEALLOCATE GRID_CUR

EXEC X_SALDO_COMMITCHANGES	


RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHECK_CODE_ROW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_CODE_ROW]
GO

--проверка наличия строк в формах 
CREATE                     PROCEDURE dbo.RO_CHECK_CODE_ROW  
  @code_form1 varchar(500),
  @code_form2 varchar(500),
  @table int, --номер таблицы
  @mask1 varchar(50), 
  @mask2 varchar(50), 
	@filter1 varchar(1000),
	@filter2 varchar(1000),
   @col1    int = NULL,
   @col2    int = NULL,
   @greater TINYINT = 0 -- 0 - равно с col1, 1 - больше или равно col1, 2 - меньше или равно col1
 AS

declare @lsf1 int,@lsf2 int,@i int,@link_table1 int,@link_table2 int,@link_form1 int,@link_form2 int,@nomErr int,@link_col1 int,@link_col2 int, @ExecStr nvarchar(4000)
select @code_form1=codeForm,@lsf1=lsf,@link_form1=linkForm from  #ListForms where codeForm like @code_form1
select @code_form2=codeForm,@lsf2=lsf,@link_form2=linkForm from  #ListForms where codeForm like @code_form2
select @link_table1 = link_table from #report_tables where link_form = @link_form1 and orders = @table
select @link_table2 = link_table from #report_tables where link_form = @link_form2 and orders = @table

IF @lsf2 is null or @lsf1 is null
 RETURN 

--итоговые строки
create table #TMP_ITOG1 (link_table int,code varchar(50))
create table #TMP_ITOG2 (link_table int,code varchar(50))

insert #TMP_ITOG1 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form1,1)  

if left(@code_form1,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form1,1)  
end

if left(@code_form1,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form1,1)  
end

insert #TMP_ITOG2 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form2,1)  

if left(@code_form2,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form2,1)  
end

if left(@code_form2,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form2,1)  
end

declare @cstr varchar(8000)
set @i=@table 


IF @code_form1 in ('0503117M','0503127M', '0503127G', '0503117G') and @table=2
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 and substring(code_row,15,3) IN ('200','000','210','220','230','240','250','260','300','500','600')
	end

IF @code_form1 in ('0503317M') and @table=3 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and substring(code_row,1,3) IN ('751', '752', '753', '754', '755', '756')
	end

IF @code_form1 in ('0503317M') and @table=1 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00087000000000000151', '00087000000000001151', '00087000000000002151', '00087000000000000120')
	end

IF @code_form1 in ('0503317M') and @table=2 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00097000000000000251', '00097000000000000231')
	end

		


create table #err (code varchar(250),code_form1 varchar(50),code_form2 varchar(50))

if @mask2 = '' and @mask1 = '' and @filter1 = '' and @filter2 = ''
begin
	insert #err (code,code_form1,code_form2)		
	select distinct dbo.RA_MASK(code_row,@mask2),@code_form2,@code_form1 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.orders = @table
	 where link_sf=@lsf2 and  float_val<>0 and RC.orders = isnull(@col2,RC.orders)
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 and link_col in (select link_col from #report_coloumns where link_table=@link_table1 and orders = CASE WHEN  @greater =0 then isnull(@col1, orders) ELSE CASE WHEN orders >= @col1 THEN orders ELSE @col1 END  END ) and float_val<>0   and dbo.RA_Mask(A.code_row, @mask2) = dbo.RA_Mask(B.code_row, @mask1))
		and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)
end
else
begin
	set @ExecStr = 'insert #err (code,code_form1,code_form2)		
	select distinct ' + case when @mask2 = '' then 'code_row' else 'dbo.RA_MASK(code_row,@mask2)' end + ',@code_form2,@code_form1 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.link_table = @link_table2
	 where link_sf=@lsf2 and RC.orders = isnull(@col2,RC.orders) and  float_val<>0 ' + case when @filter2 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter2, 'code', 'A.Code_Row'), ']',')'), '[', '(') end + '
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 ' + case when @filter1 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter1, 'code', 'B.Code_Row'), ']',')'), '[', '(') end + ' and link_col in (select link_col from #report_coloumns where link_table=@link_table1 and orders = CASE WHEN  @greater =0 then isnull(@col1, orders) ELSE CASE WHEN orders >= @col1 THEN orders ELSE @col1 END  END) and float_val<>0   and ' + case when @mask2 = '' then 'A.code_row' else 'dbo.RA_Mask(A.code_row, @mask2)' end + ' = ' + case when @mask1 = '' then 'B.Code_Row' else 'dbo.RA_Mask(B.code_row, @mask1)' end + ')
	and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)'

print @ExecStr
	exec sp_executesql @ExecStr, N'@mask1 varchar(50), @mask2 varchar(50), @lsf1 int, @lsf2 int, @link_table1 int, @link_table2 int, @code_form2 varchar(30),@code_form1 varchar(30), @col1 int, @col2 int, @greater tinyint', @mask1 = @mask1, @mask2 = @mask2, @lsf1 = @lsf1, @lsf2 = @lsf2, @link_table1 = @link_table1, @link_table2 = @link_table2, @code_form2=@code_form2,@code_form1=@code_form1, @col1 = @col1, @col2 = @col2, @greater = @greater
end

IF exists(select * from #err)
	begin
		select @nomErr=MAX(ORDERS) FROM #res 
		insert #Res(orders, res, cdoc, ctable)	
		select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
		from #err
		delete #err
	end

delete #err
if @mask2 = '' and @mask1 = '' and @filter1 = '' and @filter2 = ''
begin
	insert #err (code,code_form1,code_form2)		
	select distinct dbo.RA_MASK(code_row,@mask1),@code_form1,@code_form2 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.orders = @table
	where link_sf=@lsf1 and float_val<>0 and RC.orders = CASE WHEN  @greater =0 then isnull(@col1, RC.orders) ELSE CASE WHEN RC.orders >= @col1 THEN RC.orders ELSE @col1 END  END
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 and link_col in (select link_col from #report_coloumns where link_table=@link_table2 and orders = isnull(@col2,orders)) and float_val<>0   and dbo.RA_MASK(A.code_row,@mask1)=dbo.RA_MASK(B.code_row,@mask2))
		and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)
end
else
begin
	set @ExecStr = 'insert #err (code,code_form1,code_form2)		
	select distinct ' + case when @mask1 = '' then 'code_row' else 'dbo.RA_MASK(code_row,@mask1)' end + ',@code_form1,@code_form2 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.link_table = @link_table1
	 where link_sf=@lsf1 and RC.orders = CASE WHEN  @greater =0 then isnull(@col1, RC.orders) ELSE CASE WHEN RC.orders >= @col1 THEN RC.orders ELSE @col1 END  END and   float_val<>0 ' + case when @filter1 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter1, 'code', 'A.Code_Row'), ']',')'), '[', '(') end + '
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 ' + case when @filter2 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter2, 'code', 'B.Code_Row'), ']',')'), '[', '(') end + ' and link_col in (select link_col from #report_coloumns where link_table=@link_table2 and orders = isnull(@col2,orders)) and float_val<>0   and ' + case when @mask1 = '' then 'A.code_row' else 'dbo.RA_Mask(A.code_row, @mask1)' end + ' = ' + case when @mask2 = '' then  'B.code_row' else 'dbo.RA_Mask(B.code_row, @mask2)' end + ')
	and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)'
print @ExecStr
	exec sp_executesql @ExecStr, N'@mask1 varchar(50), @mask2 varchar(50), @lsf1 int, @lsf2 int, @link_table1 int, @link_table2 int, @code_form2 varchar(30),@code_form1 varchar(30),@col1 int, @col2 int, @greater tinyint', @mask1 = @mask1, @mask2 = @mask2, @lsf1 = @lsf1, @lsf2 = @lsf2, @link_table1 = @link_table1, @link_table2 = @link_table2, @code_form2=@code_form2,@code_form1=@code_form1, @col1 = @col1, @col2 = @col2, @greater = @greater
end
	
IF exists(select * from #err)
	begin
		select @nomErr=MAX(ORDERS) FROM #res 
		insert #Res(orders, res, cdoc, ctable)	
		select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
		from #err
		delete #err
	end

drop table #err

select 0 
GO
GRANT ALL ON dbo.[RO_CHECK_CODE_ROW] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_GET_LINK_FORM]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_GET_LINK_FORM]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
-- Процедура определения LINK_FORM импортируемой формы.
-- Вход: таблица #IMPORT_TABLE с загруженными данными формы.
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_GET_LINK_FORM]
   @iLINK_FORM INT OUTPUT, -- Возвращаемая ссылка на REPORT_FORMS.
   -- Следующие параметры д.б. либо заданы все (искл. @tPRD), либо не определен ни один из параметров и они берутся из #IMPORT_TABLE
   @cCODE_FORM CHAR(20) = NULL, -- Код формы (КФ,КОДФ)
   @tPRD       TINYINT  = NULL OUTPUT, -- Период(ПРД)
   @dDT        DATETIME = NULL, -- Отчетная дата (ДТ), если не задана, берется из #IMPORT_TABLE. 
   @bVF0       BIT      = NULL, -- Признак внутреннего формата (ВФ=0)
	@vcFileName VARCHAR(500) = NULL -- Имя импортируемого файла.
AS  
SET NOCOUNT ON

print 'dbo.[RA_IMPORT_FORM_GET_LINK_FORM]'

-- Список возвращаемых кодов ошибок:
-- -1 - Не найдена таблица #IMPORT_TABLE
-- -2 - Код формы (КФ,КОДФ) не определен
-- -3 - Вид формы (ВФ=0) не определен
-- заблокировано (м.б. неопределено) -- -4 - Периодичность (ПРД) не определена.
-- -5 - Дата документа (ДТ) не определена
-- -6 - Неправильный формат даты документа (ДТ)
-- -7 - Отчета с таким кодом и переодичностью не существует (введены уточняющие коды ошибок -9,-10,-11,-12) 
-- -8 -- Отчета с таким кодом не существует
-- -9 -- Отчета с таким кодом и месячной периодичностью не существует
-- -10 -- Отчета с таким кодом и квартальной периодичностью не существует
-- -11 -- Отчета с таким кодом и месячной (квартальной) периодичностью не существует
-- -12 -- Отчета с таким кодом и годовой периодичностью не существует

DECLARE @liError         INT,
        @ltPERIODIC      TINYINT,        
        @lvcTxt          VARCHAR(250),
        @i               INT,
        @ltMode          TINYINT,
        @ltPRD           TINYINT,
        @lvcTmp          VARCHAR(8000),
        @iXML_DOC_HANDLE INT
        

SET @ltMode = CASE 
                 WHEN ISNULL(LEN(@cCODE_FORM),0)+ ISNULL(@tPRD,0) + ISNULL(@bVF0,0) + ISNULL(@dDT,0) = 0 THEN 0 -- выбор параметров из #IMPORT_TABLE
                 ELSE 1 -- параметры заданы пользователем
              END

IF @ltMode = 0 AND 
   OBJECT_ID('tempdb..#IMPORT_TABLE') IS NULL
BEGIN
   RETURN -1 -- Не найдена таблица #IMPORT_TABLE
END

IF @ltMode = 0
BEGIN    
   IF EXISTS(SELECT *
             FROM #IMPORT_TABLE
             WHERE LEFT([TXT],5)='<?xml') 
   BEGIN      

      EXEC dbo.[RA_IMPORT_FORM_ANALYZE_XML] @cCODE_FORM OUTPUT,
                                            NULL,
                                            NULL,
                                            @dDT        OUTPUT,
                                            NULL,
                                            @bVF0       OUTPUT ,
                                            @iXML_DOC_HANDLE OUTPUT

      EXEC sp_xml_removedocument @iXML_DOC_HANDLE
   END
   ELSE BEGIN
      SELECT @lvcTxt = RTRIM([TXT])
      FROM #IMPORT_TABLE
      WHERE CHARINDEX('КФ=', [TXT]) = 1 OR 
            CHARINDEX('КОДФ=', [TXT]) = 1      
      
      SET @cCODE_FORM = RTRIM(RIGHT(@lvcTxt,LEN(@lvcTxt) - CHARINDEX('=',@lvcTxt)))

     
      IF EXISTS (SELECT *
                 FROM #IMPORT_TABLE
                 WHERE [TXT] IN ('ВФ=0','ВФ=1'))
      BEGIN
         SET @bVF0 = 1
      END              
      ELSE BEGIN
         SET @bVF0 = 0
      END   
      
      SELECT @lvcTmp = RTRIM(RIGHT([A].[TXT],LEN([A].[TXT]) - CHARINDEX('=',[A].[TXT])))
      FROM (
         SELECT [TXT] = RTRIM([TXT])
         FROM #IMPORT_TABLE
         WHERE CHARINDEX('ПРД=', [TXT]) = 1
      ) [A]   
      
      IF LEN(@lvcTmp)=1 AND dbo.[RA_ISNUMERIC](@lvcTmp)=1
	   BEGIN
         SELECT @tPRD = CASE @bVF0 
                           WHEN 1 THEN CAST(@lvcTmp AS TINYINT)
                           ELSE (CASE @lvcTmp
                                    WHEN '3' THEN 4
                                    WHEN '4' THEN 2
                                    WHEN '5' THEN 1                                 
                                 END)
                        END
      END            
         
      SET @lvcTxt = NULL   
      SELECT @lvcTxt = RTRIM([TXT])
      FROM #IMPORT_TABLE
      WHERE CHARINDEX('ДТ=', [TXT]) = 1 OR 
            CHARINDEX('РДТ=', [TXT]) = 1

      IF @lvcTxt IS NOT NULL
      BEGIN
         SET @lvcTxt = RIGHT(@lvcTxt,LEN(@lvcTxt) - CHARINDEX('=',@lvcTxt))
         IF PATINDEX('__.__.__%', @lvcTxt) > 0 AND
            ISDATE(@lvcTxt) = 1
         BEGIN                
            SELECT @i = CASE 
                           WHEN LEN(@lvcTxt) = 8 THEN 4
                           ELSE 104
                        END,
                   @dDT = CONVERT(DATETIME,@lvcTxt, @i)
         END
         ELSE BEGIN
            RETURN -6 -- Неправильный формат даты документа (ДТ)'.
         END  
      END 

/*
	   -- Обработка 151 формы.
      IF LEFT(dbo.[RA_GETWORDNUM](@vcFileName,2,'.'),2) = 'PW'
      BEGIN
		      SELECT @bVF0=0,
                   @cCODE_FORM = '0503151'

		      SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],7,'|')),104)
		      FROM #IMPORT_TABLE
		      WHERE LEFT([TXT],3)='PW|' AND 
				      ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],7,'|'))) = 1
      END

      ELSE BEGIN
	      IF (LEFT(dbo.[RA_GETWORDNUM](@vcFileName,2,'.'),2) = 'RD' OR (@vcFileName = '0503151.TXT')) AND
		      EXISTS (SELECT *
				        FROM #IMPORT_TABLE
				        WHERE LEFT([TXT],3) = 'FK|')
	      BEGIN
		      SELECT @bVF0=0,
				       @cCODE_FORM = '0503151'

		      IF EXISTS (SELECT * 
					        FROM #IMPORT_TABLE
					        WHERE LEFT([TXT],3)='BF|')
		      BEGIN       			
			      SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|')),104)
			      FROM #IMPORT_TABLE
			      WHERE LEFT([TXT],3)='BF|' AND 
					      ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|'))) = 1
		      END
		      ELSE BEGIN
			      SELECT @dDT = CONVERT(DATETIME,RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|')),104)
			      FROM #IMPORT_TABLE
			      WHERE LEFT([TXT],3)='OT|' AND 
					      ISDATE(RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|'))) = 1
		      END		
	      END
      END
*/
   END
END

-- Обработка 152 формы.
IF @vcFileName LIKE '%622%'-- AND 
  -- SUBSTRING(@vcFileName,6,1) in ('o','r')
BEGIN
   SELECT @bVF0=0,
          @cCODE_FORM = '622'     
END

IF RTRIM(@vcFileName) LIKE '%155%.TXT'-- AND 
  -- SUBSTRING(@vcFileName,6,1) in ('o','r')
BEGIN
   SELECT @bVF0=0,
          @cCODE_FORM = '0503155M'     
END

IF RTRIM(@vcFileName) LIKE '%154%.TXT'-- AND 
  -- SUBSTRING(@vcFileName,6,1) in ('o','r')
BEGIN
   SELECT @bVF0=0,
          @cCODE_FORM = '0503154M'     
END


IF SUBSTRING(@vcFileName,3,4)='660z'
BEGIN
   SELECT @bVF0=0,
          @cCODE_FORM = '660'          
END

IF @cCODE_FORM IS NULL
BEGIN
   RETURN -2 -- Код формы (КФ,КОДФ) не определен.
END

IF @bVF0 IS NULL 
BEGIN
   RETURN -3 -- Вид формы (ВФ=0) не определен.
END

IF @dDT IS NULL
BEGIN
   RETURN -5 -- Дата документа (ДТ) не определена.
END

IF (SELECT COUNT(*) 
    FROM dbo.[REPORT_FORMS]
    WHERE [CODE] = @cCODE_FORM OR 
          [ExportCode] = @cCODE_FORM) = 0
BEGIN
   RETURN -8 -- Отчета с таким кодом не существует
END

-- Квартальные и месячные формы имеют один и тот же код.
IF @bVF0 = 0 AND 
   @tPRD = 4 AND 
   MONTH(@dDT) IN (1,4,7,10)
BEGIN
   SET @tPRD = 6
END

SET @ltPRD = ISNULL(@tPRD,255)

-- Определение LINK_FORM.    
IF @bVF0=1 /* OR
   EXISTS (SELECT *
           FROM dbo.[REPORT_FORMS]
           WHERE [CODE] = @cCODE_FORM)
*/           
BEGIN
   SELECT TOP 1 @iLINK_FORM = [LINK_FORM],
                @ltPERIODIC = [PERIODIC]
   FROM dbo.[REPORT_FORMS]
   WHERE [CODE] = @cCODE_FORM AND
         ([PERIODIC] & @ltPRD > 0) AND
			ISNULL([END_DATE],CAST('99991231' AS DATETIME)) = (SELECT MIN(ISNULL([END_DATE],CAST('99991231' AS DATETIME)))
  																				 FROM dbo.[REPORT_FORMS]
 																				 WHERE [CODE] = @cCODE_FORM AND
																						([PERIODIC] & @ltPRD > 0) AND
			 																			ISNULL([END_DATE],CAST('99991231' AS DATETIME)) >= CAST((LEFT(CONVERT(VARCHAR(8),ISNULL(@dDT,CAST('99991231' AS DATETIME)),112),6)+'01') AS DATETIME)-1)
   ORDER BY [START_DATE] DESC   
END           
ELSE BEGIN      
   SELECT TOP 1 @iLINK_FORM = [LINK_FORM],
                @ltPERIODIC = [PERIODIC]   
   FROM dbo.[REPORT_FORMS] [A]
   WHERE CASE 
            WHEN [A].[EXPORTCODE] = '' THEN [A].[CODE] 
            ELSE [A].[EXPORTCODE]
         END = @cCODE_FORM  AND 
         [A].[PERIODIC] & @ltPRD > 0 AND
			ISNULL([END_DATE],CAST('99991231' AS DATETIME)) = (SELECT MIN(ISNULL([END_DATE],CAST('99991231' AS DATETIME)))
																			   FROM dbo.[REPORT_FORMS] [B]
																			   WHERE (CASE 
																							WHEN [B].[EXPORTCODE] = '' THEN [B].[CODE] 
																					 		ELSE [B].[EXPORTCODE]
																					   END) = @cCODE_FORM AND
																					  ([B].[PERIODIC] & @ltPRD > 0) AND
																					  ISNULL([B].[END_DATE],CAST('99991231' AS DATETIME)) >= CAST((LEFT(CONVERT(VARCHAR(8),ISNULL(@dDT,CAST('99991231' AS DATETIME)),112),6)+'01') AS DATETIME)-1)
	ORDER BY [START_DATE] DESC

/*
select @ltPRD,@dDT,@cCODE_FORM
1	2009-01-01 00:00:00.000	237                 

select end_date,* from report_forms where exportcode='237'



(SELECT MIN(ISNULL([END_DATE],CAST('99991231' AS DATETIME)))
																			   FROM dbo.[REPORT_FORMS]
																			   WHERE [CODE] = @cCODE_FORM AND
																					  ([PERIODIC] & 1 > 0) AND
																					  ISNULL([END_DATE],CAST('99991231' AS DATETIME)) >= CAST((LEFT(CONVERT(VARCHAR(8),ISNULL(@dDT,CAST('99991231' AS DATETIME)),112),6)+'01') AS DATETIME)

*/
END

IF @iLINK_FORM IS NULL
BEGIN
--   RETURN -7 -- Форма не найдена.
   RETURN CASE @tPRD
             WHEN 1 THEN -12
             WHEN 2 THEN -10
             WHEN 4 THEN -9
             WHEN 6 THEN -11       
             ELSE -7
          END
END

IF @ltPRD NOT IN (1,2,4) -- Если период должным образом не определен.
BEGIN
   SET @tPRD = CASE 
                  WHEN (@ltPERIODIC & 4 = 4) AND (@ltPRD & 4 = 4) THEN 4 -- Наивысший приоритет у месяца.
                  WHEN (@ltPERIODIC & 1 = 1) AND (@ltPRD & 1 = 1) THEN 1 -- Средний приоритет у года.
                  WHEN (@ltPERIODIC & 2 = 2) AND (@ltPRD & 2 = 2) THEN 2 -- Низший приоритет у квартала.
               END      
END

--select @iLINK_FORM
RETURN 0

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_GET_LINK_FORM] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_PRINT_RRO2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_PRINT_RRO2]
GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RT_PRINT_RRO2
	@LSF int,
	@empty_row tinyint,
	@PeriodCode datetime
AS
	declare @link_f int,
			@link_t int,
			-----------
			@nlen int,
			@tmp_table varchar(100),
			@cstr varchar(8000)

	set @nlen = 43

	create table #table1 (
		col1  varchar(50),
		col2  varchar(8000), 
		col3  varchar(9), 
		col4  varchar(8000), 
		col5  varchar(8000),
		col6  varchar(254),
		col7  varchar(254),
		col8  varchar(254),
		col9  varchar(254),
		col10 varchar(254),
		col11 varchar(254),
		col12 varchar(254),
		col13 varchar(254),
		col14 varchar(254),
		col15 varchar(254),
		col16 varchar(254),
		col17 varchar(254),
		col18 varchar(8000),
		col19 varchar(254),
		col20 varchar(254),
		col21 varchar(254),
		col22 varchar(254),
		col23 varchar(254),
		col24 varchar(254),
		col25 varchar(254),
		col26 varchar(254),
		col27 varchar(254),
		col28 varchar(254),
		col29 varchar(254),
		col30 varchar(254),
		col31 varchar(8000),
		col32 varchar(254),
		col33 varchar(254),
		col34 varchar(254),
		col35 varchar(254),
		col36 varchar(254),
		col37 varchar(254),
		col38 varchar(254),
		col39 varchar(254),
		col40 varchar(254),
		col41 varchar(254),
		col42 varchar(254),
		col43 varchar(254),
		col44 numeric(20,4),
		col45 numeric(20,4),
		col46 numeric(20,4),
		col47 numeric(20,4),
		col48 numeric(20,4),
		col49 numeric(20,4),
		col50 varchar(8000),
		col51 varchar(3),
		code  varchar(50))

	declare @table2 table (
		col1  varchar(50),
		col2  varchar(8000), 
		col3  varchar(9), 
		col4  varchar(8000), 
		col5  varchar(8000),
		col6  varchar(8000),
		col7  varchar(8000),
		col8  varchar(8000),
		col9  varchar(8000),
		col10 varchar(8000),
		col11 varchar(8000),
		col12 varchar(8000),
		col13 varchar(8000),
		col14 numeric(20,4),
		col15 numeric(20,4),
		col16 numeric(20,4),
		col17 numeric(20,4),
		col18 numeric(20,4),
		col19 numeric(20,4),
		col20 varchar(8000),
		del tinyint,
		orders varchar(50))
	
	select @link_f = link_form from dbo.report_saved_forms where link_saved_form = @LSF
	select @link_t = link_table from dbo.report_tables where link_form = @link_f and orders = 2

	EXEC dbo.X_GET_TABLE_NAME @tmp_table OUTPUT
	set @cstr='exec ri_proc_t'+ltrim(str(@link_t))+' '+ltrim(str(@LSF))+',default,default,default,default,default,0,'+@tmp_table
	execute(@cstr)
	set @cstr='
		insert into #table1 (col1,col2,col3,col4, col5, col6,col7, col8, col9, col10,col11,col12,col13,col14,col15,col16,col17,col18,col19,col20,col21,col22,col23,col24,col25,col26,col27,col28,col29,col30,col31,col32,col33,col34,col35,col36,col37,col38,col39,col40,col41,col42,col43,col44,col45,col46,col47,col48,col49,col50,col51,code)
		select				 col7,col8,col9,col10,col11,null,col17,col18,col20,col19,col12,col13,col14,col15,col16,col21,col22,col23,null ,col29,col30,col32,col31,col24,col25,col26,col27,col28,col33,col34,col35,null, col41,col42,col44,col43,col36,col37,col38,col39,col40,col45,col46,col1, col2, col3, col4, col5, col6, col47,col48,code from '+@tmp_table+' where rtrim(col9) in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(2,'''+rtrim(convert(varchar,@PeriodCode,112))+'''))'
	execute(@cstr)
	set @cstr='drop table '+@tmp_table
	execute(@cstr)
   
 
	-- заполнили таблицу @table1
	-- select * from @table1
	update #table1
	set col6 = case
					when len([col11]) !> 0 and len([col12]) !> 0 and len([col13]) !> 0 and len([col14]) !> 0 and len([col15]) !> 0
					then ''
					else 
						case
							when len([col11]) > 0 
							then 'абз. ' + [col11]
							else ''
						end +
						case
							when len([col12]) > 0 
							then (case when len([col11]) > 0 then ', ' else '' end) + 'подп. ' + [col12]
							else ''
						end +
						case
							when len([col13]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 then ', ' else '' end) + 'п. ' + [col13]
							else ''
						end +
						case
							when len([col14]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 or len([col13]) > 0 then ', ' else '' end) + 'ч. ' + [col14]
							else ''
						end +
						case
							when len([col15]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 or len([col13]) > 0 or len([col14]) > 0 then ', ' else '' end) + 'ст. ' + [col15]
							else ''
						end
				end,
		 col19 = case
					when len([col24]) !> 0 and len([col25]) !> 0 and len([col26]) !> 0 and len([col27]) !> 0 and len([col28]) !> 0
					then ''
					else 
						case
							when len([col24]) > 0 
							then 'абз. ' + [col24]
							else ''
						end +
						case
							when len([col25]) > 0 
							then (case when len([col24]) > 0 then ', ' else '' end) + 'подп. ' + [col25]
							else ''
						end +
						case
							when len([col26]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 then ', ' else '' end) + 'п. ' + [col26]
							else ''
						end +
						case
							when len([col27]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 or len([col26]) > 0 then ', ' else '' end) + 'ч. ' + [col27]
							else ''
						end +
						case
							when len([col28]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 or len([col26]) > 0 or len([col27]) > 0 then ', ' else '' end) + 'ст. ' + [col28]
							else ''
						end
				end,
		 col32 = case
					when len([col37]) !> 0 and len([col38]) !> 0 and len([col39]) !> 0 and len([col40]) !> 0 and len([col41]) !> 0
					then ''
					else 
						case
							when len([col37]) > 0 
							then 'абз. ' + [col37]
							else ''
						end +
						case
							when len([col38]) > 0 
							then (case when len([col37]) > 0 then ', ' else '' end) + 'подп. ' + [col38]
							else ''
						end +
						case
							when len([col39]) > 0 
							then (case when len([col37]) > 0 or len([col38]) > 0 then ', ' else '' end) + 'п. ' + [col39]
							else ''
						end +
						case
							when len([col40]) > 0 
							then (case when len([col37]) > 0 or len([col38]) > 0 or len([col39]) > 0 then ', ' else '' end) + 'ч. ' + [col40]
							else ''
						end +
						case
							when len([col41]) > 0 
							then (case when len([col37]) > 0 or len([col38]) > 0 or len([col39]) > 0 or len([col40]) > 0 then ', ' else '' end) + 'ст. ' + [col41]
							else ''
						end
				end


	-- если не задан пункт (col1) то, очищаем все колонки кроме колонок с суммами
	update #table1
	set col4 = '', 
		col5 = '', 
		col6 = '', 
		col7 = '', 
		col8 = '', 
		col9 = '',
		col10 = '',
		col11 = '',
		col12 = '',
		col13 = '',
		col14 = '',
		col15 = '',
		col16 = '',
		col17 = '',
		col18 = '',
		col19 = '',
		col20 = '',
		col21 = '',
		col22 = '',
		col23 = '',
		col24 = '',
		col25 = '',
		col26 = '',
		col27 = '',
		col28 = '',
		col29 = '',
		col30 = '',
		col37 = '',
		col38 = '',
		col39 = '',
		col40 = '',
		col41 = '',
		col42 = '',
		col43 = '',
		col50 = '',
		col51 = ''
	where len(col1)=0
	-- если @empty_row = 1 то добавляем в таблицу #table1 все узлы дерева
	if @empty_row = 1 begin
		insert into #table1 (col1,col2,col3,col51)
		select pnum, true_name, code, '000' from dbo.RT_GET_RECORDS_RRO(2,@PeriodCode) where rtrim(code) not in (select rtrim(col3) from #table1)
	end

	create table #tmp_table(nnp varchar(50), code varchar(9), orders varchar(20))
	insert into #tmp_table (nnp, code, orders)
	select col1,col3,'' from #table1 group by col1,col3
	--select * from #tmp_table
	exec dbo.RT_RRO_ORDERS_BY_TREE

	
	declare @col1 varchar(50),
			@col3 varchar(50),
			@orders varchar(50),
			@cStr1 varchar(8000),
			@cStr2 varchar(8000),
			@cStr3 varchar(8000),
			@i int,
			@nNumRow int
	declare the_cursor cursor local static for
	--select col1,col3,dbo.RT_RRO_NORMALIZE_NNP(col1) as Orders from #table1 group by col1,col3 order by dbo.RT_RRO_NORMALIZE_NNP(col1)
	select nnp,code,orders from #tmp_table order by orders
	open the_cursor
	fetch next from the_cursor into @col1,@col3,@orders 
	while @@fetch_status = 0 BEGIN
		insert into @table2 (col1,col3,orders,del) values (@col1,@col3,@orders,0)
		-- col2
		-- поле Наименование полномочия РО. 
		-- используем значение в строке с минимальным кодом строки

      
		update @table2
		set col2 = (
			select max(rtrim(col2)) from #table1 where col1 = @col1 and col3 = @col3 and col51 = (select min(col51) from #table1 where col1 = @col1 and col3 = @col3)
		)
		where col1 = @col1 and col3 = @col3 and orders = @orders

		-- col4
		-- поле Код 
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем)
		select @cStr = col4 from #table1 where col1 = @col1 and col3 = @col3 group by col4
		-- и, собственно, запихиваем это дело в @table2
		update @table2
		set col4 = @cStr
		where col1 = @col1 and col3 = @col3 and orders = @orders
		
		-- col5,col6,col7
		-- поля Наименование и реквизиты нормативного правового акта, абзац, подпункт и т.д., дата вступления в силу и срок действия
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем) самое забавное то, что дубликаты ищем по след. колонкам: col8 - col15
		exec DropTempTable '#tmp1'
		create table #tmp1 (nn int identity(1,1), col5 varchar(8000), col6 varchar(8000), col7 varchar(8000), norm_col5 varchar(8000), norm_col6 varchar(8000), norm_col7 varchar(8000))	
		set @nNumRow = 0
		insert into #tmp1 (col5, col6, col7, norm_col5, norm_col6, norm_col7)
		select  col5,
			    col6,
			    col7,
			    norm_col5 = dbo.RT_RRO_CUTWORD(col5,@nlen),
			    norm_col6 = dbo.RT_RRO_CUTWORD(col6,@nlen),
				norm_col7 = dbo.RT_RRO_CUTWORD(col7,@nlen)
		from #table1 
		where col1 = @col1 and col3 = @col3 and col51/*код строки*/ in (select min(col51/*код строки*/) from #table1 where col1 = @col1 and col3 = @col3 group by col8,col9,col10,col11,col12,col13,col14,col15 having len(col8)>0 or len(col9)>0 or len(col10)>0 or len(col11)>0 or len(col12)>0 or len(col13)>0 or len(col14)>0 or len(col15)>0)
		select @nNumRow = @@ROWCOUNT		


		update #tmp1 set norm_col6 = norm_col6 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col5) !< dbo.RT_RRO_COUNT_CR(norm_col6) then dbo.RT_RRO_COUNT_CR(norm_col5) - dbo.RT_RRO_COUNT_CR(norm_col6) else 0 end)
		update #tmp1 set norm_col7 = norm_col7 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col5) !< dbo.RT_RRO_COUNT_CR(norm_col7) then dbo.RT_RRO_COUNT_CR(norm_col5) - dbo.RT_RRO_COUNT_CR(norm_col7) else 0 end)

		if @nNumRow	> 0 begin
			set @cStr1 = ''
			set @cStr2 = ''
			set @cStr3 = ''
--			select @cStr1 = left(norm_col5,len(norm_col5)-2), @cStr2 = left(norm_col6,len(norm_col6)-2), @cStr3 = left(norm_col7,len(norm_col7)-2) from #tmp1 where nn = 1
			select
					@cStr1 = case when len(norm_col5)>1 then left(norm_col5,len(norm_col5)-2) else '' end, 
					@cStr2 = case when len(norm_col6)>1 then left(norm_col6,len(norm_col6)-2) else '' end, 
					@cStr3 = case when len(norm_col7)>1 then left(norm_col7,len(norm_col7)-2) else '' end
			from #tmp1 where nn = 1
			update @table2
			set col5 = replace(@cStr1,char(13)+char(10),char(10)), col6 = replace(@cStr2,char(13)+char(10),char(10)), col7 = replace(@cStr3,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		
			delete from #tmp1 where nn = 1			
 
			while exists(select * from #tmp1) begin
				select top 1 @i = nn from #tmp1

				if not exists(select * from @table2 where orders = @orders + right('000'+cast(@i as varchar),3))
					insert into @table2 (orders,del) values (@orders + right('000'+cast(@i as varchar),3),0)

--				select @cStr1 = left(norm_col5,len(norm_col5)-2), @cStr2 = left(norm_col6,len(norm_col6)-2), @cStr3 = left(norm_col7,len(norm_col7)-2) from #tmp1 where nn = @i
				select
 						@cStr1 = case when len(norm_col5)>1 then left(norm_col5,len(norm_col5)-2) else '' end, 
						@cStr2 = case when len(norm_col6)>1 then left(norm_col6,len(norm_col6)-2) else '' end, 
						@cStr3 = case when len(norm_col7)>1 then left(norm_col7,len(norm_col7)-2) else '' end
				from #tmp1 where nn = @i
				update @table2
				set col5 = replace(@cStr1,char(13)+char(10),char(10)), col6 = replace(@cStr2,char(13)+char(10),char(10)), col7 = replace(@cStr3,char(13)+char(10),char(10))
				where orders = @orders + right('000'+cast(@i as varchar),3)
				
				delete from #tmp1 where nn = @i
			end
		end

		exec DropTempTable '#tmp1'

		-- col18,col19,col20
		-- поля Наименование и реквизиты нормативного правового акта, абзац, подпункт и т.д., дата вступления в силу и срок действия
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем) самое забавное то, что дубликаты ищем по след. колонкам: col21 - col28
		exec DropTempTable '#tmp2'
		create table #tmp2 (nn int identity(1,1), col18 varchar(8000), col19 varchar(8000), col20 varchar(8000), norm_col18 varchar(8000), norm_col19 varchar(8000), norm_col20 varchar(8000))	
		set @nNumRow = 0
		insert into #tmp2 (col18, col19, col20, norm_col18, norm_col19, norm_col20)
		select  col18,
			    col19,
			    col20,
			    norm_col18 = dbo.RT_RRO_CUTWORD(col18,@nlen),
			    norm_col19 = dbo.RT_RRO_CUTWORD(col19,@nlen),
				norm_col20 = dbo.RT_RRO_CUTWORD(col20,@nlen)
		from #table1 
		where col1 = @col1 and col3 = @col3 and col51/*код строки*/ in (select min(col51/*код строки*/) from #table1 where col1 = @col1 and col3 = @col3 group by col21,col22,col23,col24,col25,col26,col27,col28 having len(col21)>0 or len(col22)>0 or len(col23)>0 or len(col24)>0 or len(col25)>0 or len(col26)>0 or len(col27)>0 or len(col28)>0)
		select @nNumRow = @@ROWCOUNT		
		
		update #tmp2 set norm_col19 = norm_col19 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col18) !< dbo.RT_RRO_COUNT_CR(norm_col19) then dbo.RT_RRO_COUNT_CR(norm_col18) - dbo.RT_RRO_COUNT_CR(norm_col19) else 0 end)
		update #tmp2 set norm_col20 = norm_col20 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col18) !< dbo.RT_RRO_COUNT_CR(norm_col20) then dbo.RT_RRO_COUNT_CR(norm_col18) - dbo.RT_RRO_COUNT_CR(norm_col20) else 0 end)

		if @nNumRow	> 0 begin
			set @cStr1 = ''
			set @cStr2 = ''
			set @cStr3 = ''
			select 
				@cStr1 = case when len(norm_col18)>1 then left(norm_col18,len(norm_col18)-2) else '' end, 
				@cStr2 = case when len(norm_col19)>1 then left(norm_col19,len(norm_col19)-2) else '' end, 
				@cStr3 = case when len(norm_col20)>1 then left(norm_col20,len(norm_col20)-2) else '' end
			from #tmp2 where nn = 1

			update @table2
			set col8 = replace(@cStr1,char(13)+char(10),char(10)), col9 = replace(@cStr2,char(13)+char(10),char(10)), col10 = replace(@cStr3,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		
			delete from #tmp2 where nn = 1			

			while exists(select * from #tmp2) begin
				select top 1 @i = nn from #tmp2

				if not exists(select * from @table2 where orders = @orders + right('000'+cast(@i as varchar),3))
					insert into @table2 (orders,del) values (@orders + right('000'+cast(@i as varchar),3),0)

				select 
					@cStr1 = case when len(norm_col18)>1 then left(norm_col18,len(norm_col18)-2) else '' end, 
					@cStr2 = case when len(norm_col19)>1 then left(norm_col19,len(norm_col19)-2) else '' end, 
					@cStr3 = case when len(norm_col20)>1 then left(norm_col20,len(norm_col20)-2) else '' end
--					@cStr1 = left(norm_col18,len(norm_col18)-2), 
--					@cStr2 = left(norm_col19,len(norm_col19)-2), 
--					@cStr3 = left(norm_col20,len(norm_col20)-2) 
				from #tmp2 where nn = @i
				update @table2
				set col8 = replace(@cStr1,char(13)+char(10),char(10)), col9 = replace(@cStr2,char(13)+char(10),char(10)), col10 = replace(@cStr3,char(13)+char(10),char(10))
				where orders = @orders + right('000'+cast(@i as varchar),3)
				
				delete from #tmp2 where nn = @i
			end
		end

		exec DropTempTable '#tmp2'

		-- col31,col32,col33
		-- поля Наименование и реквизиты нормативного правового акта, абзац, подпункт и т.д., дата вступления в силу и срок действия
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем) самое забавное то, что дубликаты ищем по след. колонкам: col34 - col41
		exec DropTempTable '#tmp3'
		create table #tmp3 (nn int identity(1,1), col31 varchar(8000), col32 varchar(8000), col33 varchar(8000), norm_col31 varchar(8000), norm_col32 varchar(8000), norm_col33 varchar(8000))	
		set @nNumRow = 0
		insert into #tmp3 (col31, col32, col33, norm_col31, norm_col32, norm_col33)
		select  col31,
			    col32,
			    col33,
			    norm_col31 = dbo.RT_RRO_CUTWORD(col31,@nlen),
			    norm_col32 = dbo.RT_RRO_CUTWORD(col32,@nlen),
				norm_col33 = dbo.RT_RRO_CUTWORD(col33,@nlen)
		from #table1 
		where col1 = @col1 and col3 = @col3 and col51/*код строки*/ in (select min(col51/*код строки*/) from #table1 where col1 = @col1 and col3 = @col3 group by col34,col35,col36,col37,col38,col39,col40,col41 having len(col34)>0 or len(col35)>0 or len(col36)>0 or len(col37)>0 or len(col38)>0 or len(col39)>0 or len(col40)>0 or len(col41)>0)
		select @nNumRow = @@ROWCOUNT		
		
		update #tmp3 set norm_col32 = norm_col32 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col31) !< dbo.RT_RRO_COUNT_CR(norm_col32) then dbo.RT_RRO_COUNT_CR(norm_col31) - dbo.RT_RRO_COUNT_CR(norm_col32) else 0 end)
		update #tmp3 set norm_col33 = norm_col33 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col31) !< dbo.RT_RRO_COUNT_CR(norm_col33) then dbo.RT_RRO_COUNT_CR(norm_col31) - dbo.RT_RRO_COUNT_CR(norm_col33) else 0 end)

		if @nNumRow	> 0 begin
			set @cStr1 = ''
			set @cStr2 = ''
			set @cStr3 = ''
--			select @cStr1 = left(norm_col31,len(norm_col31)-2), @cStr2 = left(norm_col32,len(norm_col32)-2), @cStr3 = left(norm_col33,len(norm_col33)-2) from #tmp3 where nn = 1
			select
 					@cStr1 = case when len(norm_col31)>1 then left(norm_col31,len(norm_col31)-2) else '' end, 
					@cStr2 = case when len(norm_col32)>1 then left(norm_col32,len(norm_col32)-2) else '' end, 
					@cStr3 = case when len(norm_col33)>1 then left(norm_col33,len(norm_col33)-2) else '' end
			from #tmp3 where nn = 1
			update @table2
			set col11 = replace(@cStr1,char(13)+char(10),char(10)), col12 = replace(@cStr2,char(13)+char(10),char(10)), col13 = replace(@cStr3,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		
			delete from #tmp3 where nn = 1			

			while exists(select * from #tmp3) begin
				select top 1 @i = nn from #tmp3

				if not exists(select * from @table2 where orders = @orders + right('000'+cast(@i as varchar),3))
					insert into @table2 (orders,del) values (@orders + right('000'+cast(@i as varchar),3),0)

--				select @cStr1 = left(norm_col31,len(norm_col31)-2), @cStr2 = left(norm_col32,len(norm_col32)-2), @cStr3 = left(norm_col33,len(norm_col33)-2) from #tmp3 where nn = @i
				select
 						@cStr1 = case when len(norm_col31)>1 then left(norm_col31,len(norm_col31)-2) else '' end, 
						@cStr2 = case when len(norm_col32)>1 then left(norm_col32,len(norm_col32)-2) else '' end, 
						@cStr3 = case when len(norm_col33)>1 then left(norm_col33,len(norm_col33)-2) else '' end
				from #tmp3 where nn = @i
				update @table2
				set col11 = replace(@cStr1,char(13)+char(10),char(10)), col12 = replace(@cStr2,char(13)+char(10),char(10)), col13 = replace(@cStr3,char(13)+char(10),char(10))
				where orders = @orders + right('000'+cast(@i as varchar),3)
				
				delete from #tmp3 where nn = @i
			end
		end

		exec DropTempTable '#tmp3'

		-- col44,col45,col46,col47,col48,col49
		-- числовые поля
		update @table2
		set col14 = (select sum(col44) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders
 
		update @table2
		set col15 = (select sum(col45) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders

		update @table2
		set col16 = (select sum(col46) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders

		update @table2
		set col17 = (select sum(col47) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders
		
		update @table2
		set col18 = (select sum(col48) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders

		update @table2
		set col19 = (select sum(col49) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3 and orders = @orders

		-- и наконец примечание col37
		select  col50 = max(col50),
			    norm_col50 = dbo.RT_RRO_CUTWORD(max(col50),@nlen/2)
		into #tmp4 
		from #table1 
		where col1 = @col1 and col3 = @col3 
		group by col50
		having len(col50) > 0
		
		set @cStr = ''
		update #tmp4 set @cStr = @cStr + norm_col50
			update @table2
			set col20 = replace(@cStr,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3 and orders = @orders
		drop table #tmp4

		fetch next from the_cursor into @col1,@col3,@orders 
	end

	select col1,col3,col4,col5,col6,replace(col7,'01.01.2999','не установлен') as col7,col8,col9,replace(col10,'01.01.2999','не установлен') as col10,col11,col12,replace(col13,'01.01.2999','не установлен') as col13,col14,col15,col16,col17,col18,col19,col20,col2,del,orders from @table2 order by orders

	drop table #table1
	drop table #tmp_table
GO
GRANT EXECUTE ON dbo.[RT_PRINT_RRO2] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
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]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_ZS]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE BB_EXPORT_ZS
	@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,
			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_PROV,
			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(@iDepLink, 'Руководитель') B on ZS.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(@iDepLink, 'Главный бухгалтер') 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) + ZT.EKR_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) + ZT.EKR_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_SZV4_PACHKA_SAVE2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV4_PACHKA_SAVE2]

GO
CREATE   PROCEDURE dbo.SA_SZV4_PACHKA_SAVE2
	@LINK		int	OUTPUT,
	@LINK_SELF INT = NULL,
	@sum_uplata_dolga_str INT = 0,
	@sum_uplata_dolga_nak INT = 0,
	@LINK_SELF2 INT = NULL
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int 	
declare @varKSPeriodLink	 int, @varKSsoLink int, @varKSRowCount INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

UPDATE dbo.SZV4_PACHKA WITH (ROWLOCK) 
SET LINK_SELF = @LINK_SELF,
	SUM_UPLATA_DOLGA_STR = @SUM_UPLATA_DOLGA_STR, 
	SUM_UPLATA_DOLGA_NAK = @SUM_UPLATA_DOLGA_NAK, 
	LINK_SELF2 = @LINK_SELF2
WHERE LINK = @LINK

SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
IF @varKSERROR <> 0
BEGIN
	ROLLBACK
	RETURN 7
END
IF @varKSRowCount = 0
BEGIN
	ROLLBACK
	RETURN 2
END


declare @varKSEventText varchar(200)
SET @varKSEventText = 'Пачка для персонифицированного учета № обновление информации о предыдущем отчёте'
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV4_PACHKA',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_SAVE2] 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].[BV_SAVE_G_PROV1_OS1B_OS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_SAVE_G_PROV1_OS1B_OS]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE dbo.BV_SAVE_G_PROV1_OS1B_OS
	@varKSnLINK_DOC INT,
	@varKSnDEL	TINYINT = 0	
AS

DECLARE @varKSnTYP_LINK INT,			
	@varKScNAME_OPER VARCHAR(250),
	@varKScNAME_OPER_OS VARCHAR(250),
	@varKSnLINK_OS INT, 
	@varKScCODE_OS VARCHAR(100),
	@varKSnSUMMA1 NUMERIC(28,2),
	@varKSnSUMMA2 NUMERIC(28,2),
	@varKSnQTY NUMERIC(19,2),
	@varKSnLINK_GP1 INT,
	@varKSnORDERS INT,
	@varKSdCALC_DATE DATETIME,
	@varKSxRet	INT,
	@varKScSOU_CODE CHAR(1),
	@varKScErrTxt VARCHAR(60),
	@strINV_TYPE VARCHAR (30)

DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT INV_TYPE,
		INV_LINK,
		INV_CODE,
		BALANCE,
		DEPRE_SUM,
		QTY,
		SOU_CODE
	FROM dbo.DOC_TABLE_NFA_VIEW
	WHERE LINK_UP = @varKSnLINK_DOC
--		AND (LAST_COST <> 0 OR DEPRE_SUM <> 0)

/*
select * from DOC_TABLE_NFA_VIEW
	WHERE LINK_UP = @varKSnLINK_DOC
		AND (LAST_COST <> 0 OR DEPRE_SUM <> 0)
*/

-- FETCH NEXT FROM GRID_CUR INTO @varKSnLINK_OS, @varKScCODE_OS, @varKSnSUMMA1, @varKSnSUMMA2, @varKSnQTY, @varKScSOU_CODE

IF @varKSnLINK_DOC IS NULL OR @varKSnLINK_DOC <= 0
	RETURN -1	

IF @varKSnDEL = 1
  BEGIN
	PRINT 'Удаление существующих проводок'
	DELETE FROM G_PROV1 WHERE LINK_UP = @varKSnLINK_DOC
  END

IF EXISTS(Select * from BV_DOC_OS1B_VIEW where LINK = @varKSnLINK_DOC AND (UPPER(TRANSFER) = 'ПРИЕМ' or UPPER(TRANSFER) = 'ПРИЁМ'))
	SELECT TOP 1 @varKSnTYP_LINK = TYP_LINK FROM DOC_OS1B_OPTIONS_70N
ELSE
	SELECT TOP 1 @varKSnTYP_LINK = TYP_LINK_2 FROM DOC_OS1B_OPTIONS_70N

IF @varKSnTYP_LINK IS NULL OR @varKSnTYP_LINK <= 0
	RETURN -2	

SELECT @varKScNAME_OPER = NAME_OPER FROM G_PROV1 WHERE LINK = @varKSnTYP_LINK
SELECT @varKSdCALC_DATE = DATE + 1 FROM G_PROV WHERE LINK = @varKSnLINK_DOC

SET @varKSnORDERS = 0

OPEN GRID_CUR
FETCH FROM GRID_CUR
	INTO @strINV_TYPE, @varKSnLINK_OS, @varKScCODE_OS, @varKSnSUMMA1, @varKSnSUMMA2, @varKSnQTY, @varKScSOU_CODE
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSnORDERS = @varKSnORDERS + 1
	IF @varKSnQTY IS NOT NULL AND @varKSnQTY > 1
	  BEGIN
		SET @varKSnSUMMA1 = @varKSnSUMMA1 * @varKSnQTY
		SET @varKSnSUMMA2 = @varKSnSUMMA2 * @varKSnQTY
	  END
	SET @varKScNAME_OPER_OS = RTRIM(ISNULL(@varKScNAME_OPER,'Операция')) + ' Инв.№ "' + RTRIM(@varKScCODE_OS) + '"'

	SET @varKSnLINK_GP1 = NULL
	EXEC X_UPDATE_G_PROV1 @varKSnLINK_GP1 OUTPUT, @varKSnLINK_DOC, @varKSnTYP_LINK,
			@varKScNAME_OPER_OS, @varKSnORDERS

	IF @varKSnLINK_GP1 IS NULL
		RETURN -3	

	EXEC @varKSxRet = dbo.BV_SAVE_G_PROV2_AP_OS2
			@varKSnLINK_GP1,		
			@varKSnTYP_LINK,		
			@varKSnLINK_OS,		
			@varKSnSUMMA1,
			@varKSnSUMMA2,
			@varKSnQTY,	
			@varKSdCALC_DATE,	
			1,
			@varKScSOU_CODE,
			@strINV_TYPE

	Print @varKSxRet
	IF @varKSxRet <> 0
	  BEGIN
	    SET @varKScErrTxt = CASE @varKSxRet
				WHEN -1 THEN '"Не задан линк операции"'
				WHEN -2 THEN '"Не найден остаток по данному ОС"'
			   END
	    PRINT 'Ошибка при записи проводки по ОС: "'+ RTRIM(@varKScCODE_OS)+ '" ' + RTRIM(@varKScErrTxt)
	    IF @varKSxRet = -2
		  RETURN -5	
	    ELSE
		  RETURN -4	
	  END
	FETCH NEXT FROM GRID_CUR 
		INTO @strINV_TYPE, @varKSnLINK_OS, @varKScCODE_OS, @varKSnSUMMA1, @varKSnSUMMA2, @varKSnQTY, @varKScSOU_CODE
END

CLOSE GRID_CUR
DEALLOCATE GRID_CUR

EXEC X_SALDO_COMMITCHANGES	

RETURN 0

GO
GRANT ALL ON dbo.[BV_SAVE_G_PROV1_OS1B_OS] 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.[SZV4_PLAT_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PLAT_FILL]

GO
CREATE PROCEDURE DBO.SZV4_PLAT_FILL @LINK INT, @MODE TINYINT = 0, @SUM_STR NUMERIC(18,2) OUTPUT, @SUM_NAK NUMERIC(18,2) OUTPUT
AS
BEGIN

	DECLARE @PERIOD_BEG DATETIME, @PERIOD_END DATETIME, @DEP_LINK INT, @Y INT, @M INT, @LINK_SELF INT, @LINK_SELF2 INT, @Y_PREV INT

	SELECT @DEP_LINK = LINK_DEP, @Y = YEAR_BEGIN, @Y_PREV = YEAR_BEGIN-1, @M = MONTH_END, 
			@PERIOD_BEG = DBO.ConvertDMY2Date(1,1,YEAR_BEGIN), @PERIOD_END = DATE, @LINK_SELF = LINK_SELF, @LINK_SELF2 = LINK_SELF2
	FROM DBO.SZV4_PACHKA 
	WHERE LINK = @LINK

	IF ISNULL(@LINK,0) > 0 AND @MODE = 0 BEGIN

		CREATE TABLE #PLAT (VID TINYINT, MON TINYINT, SUMMA NUMERIC(18,2))

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'

		INSERT INTO BUFFER (link, id)
		select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '10' --С 290экр НЕ ДОЛЖЕН БРАТЬСЯ

		INSERT INTO BUFFER (link, id)
		select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

		INSERT INTO BUFFER (link, id)
		select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

		INSERT INTO #PLAT (VID, MON, SUMMA)
		SELECT 1, MON = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')), P.SUMMA
		from 
			dbo.AProvByBufferConditionsShortDate(@PERIOD_BEG, @PERIOD_END, 'DT', 'KT') P	
			inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
			inner join dbo.g_prov G on G.link = PA.link
			LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
		WHERE
			P.DEP_LINK = @DEP_LINK
			AND
			G.DEP = @DEP_LINK
			AND
			CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
			AND
			CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
			AND
			DG.CODE <> '290'

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'

		INSERT INTO BUFFER (link, id)
		select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '11'

		INSERT INTO BUFFER (link, id)
		select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

		INSERT INTO BUFFER (link, id)
		select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

		INSERT INTO #PLAT (VID, MON, SUMMA)
		SELECT 2, MON = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')), P.SUMMA
		from 
			dbo.AProvByBufferConditionsShortDate(@PERIOD_BEG, @PERIOD_END, 'DT', 'KT') P	
			inner join DOCUMENTS_PAY_ADD PA on P.link = PA.link
			inner join g_prov G on G.link = PA.link
			LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
		WHERE
			P.DEP_LINK = @DEP_LINK
			AND
			G.DEP = @DEP_LINK
			AND
			CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
			AND
			CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
			AND
			DG.CODE <> '290'			

		exec dbo.BufferClear 'DT'
		exec dbo.BufferClear 'KT'

		DELETE FROM DBO.SZV4_PLAT WHERE LINK_UP = @LINK

		DECLARE @PERIOD_END2 DATETIME
		SET @PERIOD_END2 = DBO.DATEENDOFMONTH(DBO.ConvertDMY2Date(1,@M,@Y))

		INSERT INTO DBO.SZV4_PLAT(LINK_UP, MON, SUM_STR, SUM_NAK)
		SELECT
			@LINK,
			 m,
			 SUM_STR = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE VID = 1 AND MON = M),0),
			 SUM_NAK = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE VID = 2 AND MON = M),0)
		FROM DBO.months_ex(@PERIOD_BEG, @PERIOD_END2)

		--UPDATE DBO.SZV4_PACHKA
		--SET 
		--	INSUR1 = ISNULL((SELECT SUM(SUM_STR) FROM dbo.SZV4_PLAT WHERE LINK_UP = @LINK),0),
		--	GAIN1 = ISNULL((SELECT SUM(SUM_NAK) FROM dbo.SZV4_PLAT WHERE LINK_UP = @LINK),0)
		--WHERE LINK = @LINK		

		DROP TABLE #PLAT

	END

	IF ISNULL(@LINK_SELF2,0) > 0 AND @MODE = 1 BEGIN
		
		--Расчёт остатка долга за прошлый год по физлицам

		--1. Остаток долга на начало текущего года			
		CREATE TABLE #DOLG_PREV_YEAR (
			LINK_PERS INT, 
			FIO VARCHAR(100), 
			BIRTH DATETIME, 
			INSUR_NUM VARCHAR(14), 
			AGE_TYPE TINYINT, 
			SUM_STR NUMERIC(18,2), 
			SUM_STR_P NUMERIC(18,2), 
			SUM_NAK NUMERIC(18,2), 
			SUM_NAK_P NUMERIC(18,2)
		)
		
		INSERT INTO #DOLG_PREV_YEAR(LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, SUM_STR, SUM_STR_P, SUM_NAK, SUM_NAK_P)
		EXECUTE [dbo].[SA_PF_REPORT] @Y_PREV, 12, @LINK_SELF2
	
		--2. Уплата долга в текущем году за прошлый год
		INSERT INTO #DOLG_PREV_YEAR(LINK_PERS, FIO, BIRTH, INSUR_NUM, AGE_TYPE, SUM_STR_P, SUM_NAK_P)
		EXECUTE [dbo].[SA_PF_REPORT2] @Y_PREV, 12, @LINK
		
		SET @SUM_STR= ISNULL((SELECT SUM(SUM_STR) FROM #DOLG_PREV_YEAR),0) - ISNULL((SELECT SUM(SUM_STR_P) FROM #DOLG_PREV_YEAR),0)
		SET @SUM_NAK= ISNULL((SELECT SUM(SUM_NAK) FROM #DOLG_PREV_YEAR),0) - ISNULL((SELECT SUM(SUM_NAK_P) FROM #DOLG_PREV_YEAR),0)

		UPDATE dbo.SZV4_PACHKA
		SET 
			SUM_UPLATA_DOLGA_NAK = @SUM_NAK,
			SUM_UPLATA_DOLGA_STR = @SUM_STR
		WHERE LINK = @LINK

	END	
	
END
RETURN 0	

GO


GRANT EXECUTE ON dbo.[SZV4_PLAT_FILL] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_4FSS_EXPORT_v04]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_4FSS_EXPORT_v04]

GO


CREATE      PROCEDURE [dbo].SA_4FSS_EXPORT_v04 ( @Link int /*Ссылка на расчет*/ ) 
AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))


INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------

DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, 
		@Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS 
WHERE LINK_SAVED_FORM = @link

DECLARE 
	@first_month_of_quarter TINYINT, 
	@second_month_of_quarter TINYINT, 
	@third_month_of_quarter TINYINT

IF @Period_Number = 1
	SELECT @first_month_of_quarter = 1, @second_month_of_quarter = 2, @third_month_of_quarter = 3
IF @Period_Number = 2
	SELECT @first_month_of_quarter = 4, @second_month_of_quarter = 5, @third_month_of_quarter = 6
IF @Period_Number = 3
	SELECT @first_month_of_quarter = 7, @second_month_of_quarter = 8, @third_month_of_quarter = 9
IF @Period_Number = 4
	SELECT @first_month_of_quarter = 10, @second_month_of_quarter = 11, @third_month_of_quarter = 12

SELECT  @first_month_of_quarter = ISNULL(@first_month_of_quarter,1), @second_month_of_quarter = ISNULL(@second_month_of_quarter,2), @third_month_of_quarter = ISNULL(@third_month_of_quarter,3)

SELECT top 1
	DD1.OKPO AS OKPO1, 
	DD1.INN AS INN1, DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	DD1.OGRN AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	DD1.OGRN,
	DD1.OKATO,
	DD1.OKVED,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TaxType = DD1.FSS_KP_PC1,
	TaxType2 = DD1.FSS_KP_PC2,
	TaxType3 = DD1.FSS_KP_PC3
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @NumDotC VARCHAR(2), @NumDot INT
SELECT @NumDotC = ISNULL(dbo.RN_GET_ATR_VALUE(@LINK, 'REPORTS_ATR_NOM_OBR'),'00')
SET @NumDot = CASE WHEN ISNUMERIC(@NumDotC) =1 THEN CONVERT(INT,@NumDotC) ELSE 0 END

DECLARE @Cur0 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @Cur CURSOR, @Cur1 CURSOR, @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254)

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = FSS_REG_NUM + '_' + CONVERT(VARCHAR(4),@YEAR)  + '_' +  (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="windows-1251"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?F4FORM version="0.4"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<F4REPORT>'
  
  /** Титул **/
  
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<TITLE' 
		+ ' REG_NUM="' + LTRIM(RTRIM(FSS_REG_NUM)) + '"'
		+ ' KPS_NUM="' + LTRIM(RTRIM(FSS_KOD_P)) + '"'
		+ ' DOP_NUM="' + LTRIM(RTRIM(FSS_KOD_DOP)) + '"'
		+ ' INN="' + LTRIM(RTRIM(INN1)) + '"'
		+ ' KPP="' + LTRIM(RTRIM(KPP1)) + '"'
		+ ' OGRN="' + LTRIM(RTRIM(OGRN)) + '"'
		--+ ' OKOPF="' + LTRIM(RTRIM(OKOPF)) + '"'
		+ ' OKATO="' + REPLACE(LTRIM(RTRIM(OKATO)),' ','') + '"'
		--+ ' OKPO="' + LTRIM(RTRIM(OKPO)) + '"'
		--+ ' OKFS="' + LTRIM(RTRIM(OKFS)) + '"'
		+ ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"'
		+ ' QUART_NUM="' + (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '"'
		+ ' YEAR_NUM="' + CONVERT(VARCHAR(4),@YEAR) + '"'
		+ ' NAME="' + LTRIM(RTRIM(REPLACE(FULL_NAME,'"','&quot;'))) + '"'
		+ ' CRE_DATE="' + convert(varchar(10),@modify_date,120) + '"'
		+ ' WRO="' + LEFT(FSS_REG_NUM,4) + '"'
		+ ' CEO="' + LTRIM(RTRIM(CHIEF_FIO)) + '"'
		+ ' CFO="' + LTRIM(RTRIM(GLBUH_FIO)) + '"'
		+ ' AUTHOR="' + ISNULL(dbo.AdminGetUserFIO(default),'') + '"'
		+ ' PHONE="' +(SELECT LTRIM(RTRIM(phone)) FROM DICTIONARY_OTV_FACE  WHERE Dep_LINK=dbo.GetOwnDepLink() and name = 'Главный бухгалтер') + '"'
		+ ' NumCorr="' + LTRIM(RTRIM(CONVERT(VARCHAR(3),@Version))) + '"' --Номер корректировки
		+ ' NumDot="' + LTRIM(RTRIM(CONVERT(VARCHAR(2),@NumDot))) + '"' --Номер корректировки
		+ ' TaxType="' + LEFT(LTRIM(RTRIM(TaxType)),3) + '"' --Шифр (первая часть)
		+ ' TaxType2="' + LEFT(LTRIM(RTRIM(TaxType2)),2) + '"' --Шифр (вторая часть)
		+ ' TaxType3="' + LEFT(LTRIM(RTRIM(TaxType3)),2) + '"' --Шифр (третья часть)		
		+ ' T1R1C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 1, 3)),0)))) + '"' --Численность работников	
		+ ' T1R2C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 2, 3)),0)))) + '"' --из них: женщин	
		+ ' T1R4C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 3, 3)),0)))) + '"' --из них: работающих инвалидов	
		+ ' T1R6C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 4, 3)),0)))) + '"' --из них: работающих, занятых на работах с вредными и (или) опасными производственными факторами	
		+ '/>'
		FROM #DEP_DATA
--  /** Раздел I **/

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INF1 '
		--Таблица 1 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 3, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Ch' + LTRIM(STR(ROW +1 - 5)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (5,6,7)				
		--Таблица 1 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' N0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 9, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' N' + LTRIM(STR(ROW + 1 - 11)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (11,12,13)				
		--Таблица 1 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 14, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 18, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 19, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R13="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 20, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 22, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 24, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 25, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 26, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 7 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2N="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 27, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FssDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 29, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 11 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R18="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 31, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R19="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 32, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 14 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 34, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R21="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 36, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Re' + LTRIM(STR(ROW + 1 - 38)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (38,39,40)				
		--Таблица 1 строка 16  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R27="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 42, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R29="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R30="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R26="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 17  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R32="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 47, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 19  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 49, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 20  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDelDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 50, 3) WHERE SUMMA2 <> 0

		--Таблица 2 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 3  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 4  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 6  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 4) WHERE SUMMA2<> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 7  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 2 строка 8  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 9  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 10  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 11  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 6) WHERE SUMMA2 <> 0				

		--Таблица 3 строка 1  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S1' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 1, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 2  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S2' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 2, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 3  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S4' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 3, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 5  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S3' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 5, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 6  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S6' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 6, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 7  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S7' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 7, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		
		
		--Таблица 4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 6) WHERE SUMMA2 <> 0				
		
		--Таблица 4.1 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 6) WHERE SUMMA2 <> 0				

		-- Таблица 4.2 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_WRK_CNT="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_WRK_CNT1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 6) WHERE SUMMA2 <> 0	
		-- Таблица 4.2 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_ALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_ALL1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_SPC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_SPC1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_DT="' 
							+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
								WHEN 10 THEN 
									SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
								WHEN 8 THEN 
									'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
								ELSE
								''
							END	+ '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 4) WHERE ISNULL(STR_VAL,'') <> ''
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_NM="' + LEFT(STR_VAL,8) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 5) WHERE ISNULL(STR_VAL,'') <> ''
	
		--Таблица 4.3 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OPUS_SIALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 3) WHERE SUMMA <> 0				
		--Таблица 4.3 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OPUS_SI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 3) WHERE SUMMA <> 0				


		--Таблица 4.4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIALL1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIS1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIG="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIG1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIE="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NOUS_SIE1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 4) WHERE SUMMA <> 0				
	
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'
	
		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 4)

		--Сведения об инвалидах
		CREATE TABLE #INVALID (
			LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10), 
			GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10), 
			SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

		CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
		SELECT DISTINCT 
			FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
			DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
			PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
			SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
			SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
			SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
			SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
		FROM
			#TAB5 T5

		DROP TABLE #TAB5

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
			SPACE(1) + ' <F4INVAL'  + 
				' LNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '"' +
				' FNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '"' +
				' MNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '"' +
				' MSEDATE="' + CASE LEN(LTRIM(RTRIM(ISNULL(DATE_SPR,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)								
									ELSE
										''
								END + '"' +
				CASE WHEN ISNULL(PER_END,'') <> ''
				THEN 
					' MSEDATEF="' 
								+ CASE LEN(LTRIM(RTRIM(ISNULL(PER_END,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)								
									ELSE
									''
								END + '"'
				ELSE
					''	
				END +
				' S="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '"' +
				' S1="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '"' +
				' S2="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '"' +
				' S3="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '"' +
			' />' 
		FROM #INVALID 
		ORDER BY FIO2

		DROP TABLE #INVALID

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INF1>'

  /** Раздел II **/
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(1)

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INFO '		
		--Таблица 5 Строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C8="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 12) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C18="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 13) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 14) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 15) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 17) WHERE SUMMA2 <> 0				

		--Таблица 6 Строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 5) WHERE SUMMA2 <> 0
		--Таблица 6 графа 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_MIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,1),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 6) WHERE SUMMA2 <> 0
		--Таблица 6 графа 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_DEC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 7) WHERE SUMMA2 <> 0
		--Таблица 6 графа 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' INC_DATE="' 
					+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
						WHEN 10 THEN 
							SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
						WHEN 8 THEN 
							'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
						ELSE
						''
					END + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 8) WHERE ISNULL(STR_VAL,'') <> ''

		--Таблица 6 графа 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_INC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 9) WHERE SUMMA2 <> 0

		--Таблица 7 строка 1 
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 6, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R7C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 8, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 9, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R11C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 10, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 11, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R17C61="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 12, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 14, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 10
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 15, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R21C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 17, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R23C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 19, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R24C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 20, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R25C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 21, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 12
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R27C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 23, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R29C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R30C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R31C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 13
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R38C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 28, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 15
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R34C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 30, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 16
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R35C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 31, 3) WHERE SUMMA2 <> 0


		--Таблица 8 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 2, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 2, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 4, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 4, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 9, 4) WHERE SUMMA2 <> 0

		--Таблица 9
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' M' + CONVERT(VARCHAR(2),ROW) + '="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, DEFAULT, 3) WHERE ROW IN (1,2,3,5) AND SUMMA <> 0

		--Таблица 10 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R1C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R1C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R1C3="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 5) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R1C4="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 6) WHERE SUMMA <> 0

		--Таблица 10 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R2C5="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 2, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T10R2C6="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 2, 8) WHERE SUMMA <> 0
		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'


		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 25, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 26, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 27, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 4)
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INFO>'
	
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, SPACE(0) + '</F4REPORT>'

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]



GO


GRANT EXECUTE ON dbo.[SA_4FSS_EXPORT_v04] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SS_PRINT_SZV63]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SS_PRINT_SZV63]

GO
CREATE PROC dbo.SS_PRINT_SZV63 
	
	@YEAR INT,	 /*Год*/
	@nOption int, /*Тип сведений*/
	/*Фильтры*/
	@nPach varchar(5),
	@nFilterLink INT,
	@cVal1 char(1) = '', @nOtborLink1 int = null /* Отбор сотрудников */,
	@cVal2 char(1) = '', @nOtborLink2 int = null /* Отбор физических лиц */,
	@cVal3 char(1) = '', @nOtborLink3 int = null /* Отбор подразделений */,
	
	@MODE TINYINT = 0
	
AS
BEGIN

IF ISNUMERIC(@nPach) = 0
	SET @nPach = 1

declare @DEP_LINK int,
		@LINK_EMPL INT , /*Сотрудник*/
		@LINK_PERSON INT /*Физ лицо*/
		
exec dbo.xd_whats_zb @DEP_LINK output	

Create TABLE #T_PERSON (LINK_PERS INT)

if @cVal1 != '' or @cVal3 != '' or (@cVal1 = '' and @cVal2 = '' and @cVal3 = '')
begin
		DECLARE @SCRIPT1 VARCHAR(8000), @SCRIPT_BODY VARCHAR(8000)

		SET @SCRIPT1 = '
						insert into #T_PERSON(link_pers)
						SELECT /*DISTINCT*/ e.PERS_LINK 
						FROM dbo.EMPL e 
						WHERE 
							e.DEP_LINK = ' + CONVERT(VARCHAR(20), @DEP_LINK)

		SET @SCRIPT_BODY = ''+ CASE WHEN ISNULL(@cVal1,'') = '' THEN '' ELSE ' 
							/* Отбор сотрудников */
							AND EXISTS (SELECT RECORD 
											FROM DBO.OBJECT_VAR_EMPL 
											WHERE RECORD = e.LINK AND LINK_UP = ' + CONVERT(VARCHAR(20), @nOtborLink1) + ' ) ' END 
							+	
								CASE WHEN ISNULL(@cVal2,'') = '' THEN '' ELSE '
							/*AND
							/* Отбор физических лиц */
							EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_PERSON WHERE RECORD = e.PERS_LINK AND LINK_UP = ' + CONVERT(VARCHAR(20), @nOtborLink2) + ' )
							 */' END
							+ 
							CASE WHEN ISNULL(@cVal3,'') = '' THEN '' ELSE '
							AND
							/* Отбор подразделений */
							EXISTS (select pers_link from dbo.KU_EMPL_PLACING WHERE pers_link = e.PERS_LINK AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SUBDIV_HEAD WHERE RECORD = SUBDIV_head AND LINK_UP = ' + CONVERT(VARCHAR(20), @nOtborLink3) + ' ))
							 ' END
							+ 
							''

		if isnull(@SCRIPT_BODY,'') <> ''
		begin
			SET @SCRIPT1 = @SCRIPT1 + @SCRIPT_BODY 
		end 

		exec(@SCRIPT1)
end


/* Отбор физических лиц */
-- Для договорников смотрим не в EMPL, а в PERSON
if @cVal2 != '' 
	begin 
		insert #T_PERSON (link_pers)	
		SELECT DISTINCT pers_link 
		  FROM dbo.SALARY_REESTR_DGH 
			where year([date]) = @YEAR
			and DEP_LINK = @DEP_LINK
			and pers_link in (select link from dbo.PERSON 
											where DEP_LINK = @DEP_LINK and LINK IN (SELECT RECORD FROM DBO.OBJECT_VAR_PERSON 
																		 WHERE LINK_UP = CONVERT(VARCHAR(20), @nOtborLink2) 
															)
								)
	end
if (@cVal1 = '' and @cVal2 = '' and @cVal3 = '') 
	begin
		insert #T_PERSON (link_pers)	
		SELECT DISTINCT pers_link 
		  FROM dbo.SALARY_REESTR_DGH 
			where year([date]) = @YEAR
			and DEP_LINK = @DEP_LINK
	end	
--

---Отбрасываются пенсионеры
DELETE FROM #T_PERSON
WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = LINK_PERS  and K.CHECK_SZV = 0)
---
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, D TINYINT)

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, D)
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, 0
from 
	dbo.SA_ESN_VIEW(@YEAR, 12, @DEP_LINK, null) S 
	inner join dbo.PERSON P on S.REF_PHYS_PERS = P.link
	inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
WHERE 
	WAY_CALC = 6
	and s.ref_phys_pers in (select link_pers from #T_PERSON)
	
--Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E, D)
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, 1
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join dbo.PERSON P on GT.PERS_LINK = P.link
	inner join 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 in (select ISNULL(link_pers,0) from #T_PERSON) /*OR (select count(*) from #T_PERSON) = 0*/)

--CREATE TABLE #KATEG (LINK INT IDENTITY(1,1),I TINYINT, E TINYINT, D TINYINT)

--INSERT INTO #KATEG(I, E, D)
--SELECT DISTINCT I, E, D from #SPR_ESN

----Установка категорий
--UPDATE #SPR_ESN
--SET KATEG = (SELECT K.LINK FROM #KATEG K WHERE K.I = #SPR_ESN.I AND K.E = #SPR_ESN.E AND K.D = #SPR_ESN.D)

--Раздел 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 in (select link_pers from #T_PERSON) /*OR (select count(*) from #T_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 EXISTS (SELECT LINK_PERS FROM #T_PERSON WHERE #T_PERSON.LINK_PERS = P1.link)	
GROUP BY
	PERS_LINK, PERIOD_BEGIN, LINK_VKR, ( CASE WHEN YEAR(p1.birthdate)<= 1966 THEN 1 ELSE 2 END )	


SELECT 
	link_pers,

	MON, 
	
	FACE_GROUP, 
	
	SUMMA_ALL_TD = SUM(CASE WHEN link_empl IS NOT NULL THEN SUMMA_ALL ELSE 0 END),
	SUMMA_ALL_GD = SUM(CASE WHEN link_empl IS NULL THEN SUMMA_ALL ELSE 0 END),
	
	SUMMA_NO_TD = SUM(CASE WHEN link_empl IS NOT NULL THEN SUMMA_NO ELSE 0 END), 
	SUMMA_NO_GD = SUM(CASE WHEN link_empl IS NULL THEN SUMMA_NO ELSE 0 END), 
	
	SUMMA_ALL_I_TD = SUM( CASE WHEN link_empl IS NOT NULL THEN SUMMA_ALL_I ELSE 0 END),
	SUMMA_ALL_I_GD = SUM( CASE WHEN link_empl IS NULL THEN SUMMA_ALL_I ELSE 0 END),
	
	SUMMA_NO_I_TD = SUM(CASE WHEN link_empl IS NOT NULL THEN SUMMA_NO_I ELSE 0 END),
	SUMMA_NO_I_GD = SUM(CASE WHEN link_empl IS NULL THEN SUMMA_NO_I ELSE 0 END),	
	
	SUMMA_ALL_E_TD = SUM(CASE WHEN link_empl IS NOT NULL THEN SUMMA_ALL_E ELSE 0 END), 
	SUMMA_ALL_E_GD = SUM(CASE WHEN link_empl IS NULL THEN SUMMA_ALL_E ELSE 0 END), 
	
	SUMMA_NO_E_TD = SUM(CASE WHEN link_empl IS NOT NULL THEN SUMMA_NO_E ELSE 0 END),
	SUMMA_NO_E_GD = SUM(CASE WHEN link_empl IS NULL THEN SUMMA_NO_E ELSE 0 END)
	
INTO #SALARY_SUM2
FROM 
( -- сотрудники
select 
	link_pers = p1.link,
	link_empl = cj.link_empl,
	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 CJ.SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	( CASE WHEN YEAR(p1.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 CJ.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 CJ.SUMMA ELSE 0 END),
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 AND I.LINK IS NULL THEN CJ.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 CJ.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
where 	
	Year(period_begin) = @YEAR
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
	AND (P1.link in (select link_pers from #T_PERSON) /*OR (select count(*) from #T_PERSON) = 0*/)
GROUP BY
	p1.link,CJ.link_empl,Month(CJ.PERIOD_BEGIN), ( CASE WHEN YEAR(p1.birthdate)<= 1966 THEN 1 ELSE 2 END )
UNION ALL 
-- договорники	
select 
	link_pers = CJ.PERS_LINK,
	link_empl = NULL,
	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 CJ.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 CJ.SUMMA - ISNULL(B1.SUMMA_BASE,0) ELSE 0 END),
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 AND I.LINK IS NULL THEN CJ.SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND I.LINK IS NULL THEN CJ.SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END)
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
	CJ.PERS_LINK, Month(CJ.PERIOD_BEGIN), FACE_GROUP	
) AS T
GROUP BY 
	LINK_PERS, MON, FACE_GROUP
--========================================================================================================

CREATE TABLE #RES(CODE_STR VARCHAR(4), LINK_PERS INT, 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, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1101',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_TD - SUMMA_ALL_I_TD - SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1201',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1301',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T 
 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2101',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_GD - SUMMA_ALL_I_GD - SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2201',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_E_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T  

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2301',
	T.LINK_PERS,
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS), 0),
	ISNULL((SELECT SUM(SUMMA_ALL_I_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS), 0)	
 FROM #T_PERSON T  
  
-- сбор сведений для выяснения суммы на которую начисляются страховые взносы
INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1103', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1203', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1303', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T	

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2103', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2203', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2303', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T		

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1105',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_TD - SUMMA_NO_I_TD - SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 0 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
 FROM #T_PERSON T 
 
 INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1205',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 0 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
 FROM #T_PERSON T 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'1305',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_TD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 0 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
 FROM #T_PERSON T  

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2105',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_GD - SUMMA_NO_I_GD - SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND D = 1 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
FROM #T_PERSON T 

 INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2205',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_E_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 1 AND D = 1 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
 FROM #T_PERSON T 

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT DISTINCT
	'2305',
	t.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 1 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 1 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 2 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 2 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 3 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 3 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 4 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 4 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 5 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 5 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 6 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 6 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 7 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 7 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 8 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 8 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 9 AND LINK_PERS = T.LINK_PERS),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 9 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 10 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 10 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 11 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 11 AND REF_PHYS_PERS = T.LINK_PERS), 0),
	ISNULL( (SELECT SUM(SUMMA_NO_I_GD) FROM #SALARY_SUM2 WHERE MON = 12 AND LINK_PERS = T.LINK_PERS),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND E = 0 AND D = 1 AND MONTH_BASE = 12 AND REF_PHYS_PERS = T.LINK_PERS), 0)
 FROM #T_PERSON T  
 
INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1107', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1207', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '1307', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2107', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2207', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12) 
	SELECT DISTINCT '2307', T.LINK_PERS ,0,0,0,0,0,0,0,0,0,0,0,0 FROM #T_PERSON T

--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

---
SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_11 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_11 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_11 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 1 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_12 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_12 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_12 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 1 AND E = 1 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_13 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_13 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_13 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 2 AND E = 0 AND D = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_21 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_21 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_21 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 1 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_22 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_22 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_22 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 1 AND E = 1 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1_23 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_23 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_23 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 2 AND E = 0 AND D = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_11
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_11 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_11 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_11 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_12
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_12 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_12 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_12 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_13
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_13 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_13 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_13 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_21
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_21 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_21 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_21 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_22
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_22 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_22 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_22 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

--
SELECT T.REF_PHYS_PERS, T.M, T.FACE_GROUP, SUMMA = SUM(SUMMA)
INTO #SPR_ESN2_23
FROM
(
SELECT DISTINCT  T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00)
FROM 
	#SPR_ESN1_23 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_23 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_23 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
)t
GROUP BY T.REF_PHYS_PERS, T.M, T.FACE_GROUP

	
INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '1111',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_11 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '1211',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_12 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '1311',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_13 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T	

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '2111',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_21 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '2211',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_22 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct
  '2311',
	T.LINK_PERS,
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 1 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 2 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 3 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 4 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 5 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 6 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 7 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 8 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 9 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 10 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 11 and REF_PHYS_PERS = T.LINK_PERS) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2_23 WHERE M = 12 and REF_PHYS_PERS = T.LINK_PERS) ,0)
	from #T_PERSON T	
	

-- Из них на которые начислены страховые взносы на обязательное пенсионное страхование
INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'1113',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1103', '1105', '1107', '1111')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'1213',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1203', '1205', '1207', '1211')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R

INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'1313',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '1301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('1303', '1305', '1307', '1311')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R


INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'2113',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2101'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2103', '2105', '2107', '2111')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R


INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'2213',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2201'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2203', '2205', '2207', '2211')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R


INSERT INTO #RES (CODE_STR, LINK_PERS, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT distinct 
	'2313',
	R.LINK_PERS,
	ISNULL( (SELECT MIN(R1.SUM01) - SUM(R2.SUM01) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS) ,0),
	ISNULL( (SELECT MIN(R1.SUM02) - SUM(R2.SUM02) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM03) - SUM(R2.SUM03) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM04) - SUM(R2.SUM04) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM05) - SUM(R2.SUM05) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM06) - SUM(R2.SUM06) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM07) - SUM(R2.SUM07) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM08) - SUM(R2.SUM08) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM09) - SUM(R2.SUM09) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM10) - SUM(R2.SUM10) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM11) - SUM(R2.SUM11) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0),
	ISNULL( (SELECT MIN(R1.SUM12) - SUM(R2.SUM12) FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '2301'
				WHERE r1.LINK_PERS = r.LINK_PERS and R2.CODE_STR IN ('2303', '2305', '2307', '2311')	
				and R2.LINK_PERS = R1.LINK_PERS),0)
FROM #RES R


--====================================================================
CREATE TABLE #RES1(MON VARCHAR(3), S_1 NUMERIC(18,2), S_2 NUMERIC(18,2))


--- Сумма выплат и иных вознаграждений, начисленных в пользу физического лица
--- и -- Из них на которые начислены страховые взносы на обязательное пенсионное страхование


CREATE TABLE #RES2( link_pers int, KATEG TINYINT, DOG TINYINT, S1_1 NUMERIC(18,2), S1_2 NUMERIC(18,2), S1_3 NUMERIC(18,2), S1_4 NUMERIC(18,2), S1_5 NUMERIC(18,2), S1_6 NUMERIC(18,2), S1_7 NUMERIC(18,2), S1_8 NUMERIC(18,2), S1_9 NUMERIC(18,2), S1_10 NUMERIC(18,2), S1_11 NUMERIC(18,2), S1_12 NUMERIC(18,2),
					S2_1 NUMERIC(18,2), S2_2 NUMERIC(18,2), S2_3 NUMERIC(18,2), S2_4 NUMERIC(18,2), S2_5 NUMERIC(18,2), S2_6 NUMERIC(18,2), S2_7 NUMERIC(18,2), S2_8 NUMERIC(18,2), S2_9 NUMERIC(18,2), S2_10 NUMERIC(18,2), S2_11 NUMERIC(18,2), S2_12 NUMERIC(18,2), S1_ALL NUMERIC(18,2), S2_ALL NUMERIC(18,2))

INSERT INTO #RES2 (	link_pers, KATEG, DOG, S1_1, S1_2, S1_3, S1_4, S1_5, S1_6, S1_7, S1_8, S1_9, S1_10, S1_11, S1_12,
					S2_1, S2_2, S2_3, S2_4, S2_5, S2_6, S2_7, S2_8, S2_9, S2_10, S2_11, S2_12, S1_ALL, S2_ALL)
SELECT
	r.link_pers,
	KATEG = CONVERT(INT,SUBSTRING(R.CODE_STR,2,1)),
	DOG = CONVERT(INT,SUBSTRING(R.CODE_STR,1,1)),
	r.Sum01,
	r.sum02,
	r.sum03,
	r.Sum04,
	r.sum05,
	r.sum06,
	r.Sum07,
	r.sum08,
	r.sum09,
	r.Sum10,
	r.sum11,
	r.sum12,
	r1.sum01,
	r1.sum02,
	r1.sum03,
	r1.sum04,
	r1.sum05,
	r1.sum06,
	r1.sum07,
	r1.sum08,
	r1.sum09,
	r1.sum10,
	r1.sum11,
	r1.sum12,
	0,
	0							
FROM #RES R INNER JOIN #RES R1 ON r1.link_pers = r.link_pers
WHERE R1.CODE_STR like '%13' and R.CODE_STR like '%01' AND SUBSTRING(R1.CODE_STR,2,1) = SUBSTRING(R.CODE_STR,2,1) AND SUBSTRING(R1.CODE_STR,1,1) = SUBSTRING(R.CODE_STR,1,1)

--====================================================================

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_ALL_GR (ID int identity (1,1), NUM_PACH INT, LINK int,	FM varchar(50), IM varchar(50),	OT varchar(50), INSUR_NUM varchar(14),
							 [YEAR] varchar(4), CODE VARCHAR(20),	T_DOGOV	int, REG_NOM_PF VARCHAR(15), INN varchar(12), KPP varchar(9), OKPO varchar(20),	
							 DCOUNT int, PERS_INN VARCHAR(12), [TYPE] int, DEP_NAME varchar(256), DEP_FN varchar(2000), NUM_STR int, 
							 DATE_DOC datetime, s1_1 NUMERIC(18,2), s1_2 NUMERIC(18,2), s1_3 NUMERIC(18,2), s1_4 NUMERIC(18,2), s1_5 NUMERIC(18,2), 
							 s1_6 NUMERIC(18,2), s1_7 NUMERIC(18,2), s1_8 NUMERIC(18,2), s1_9 NUMERIC(18,2), s1_10 NUMERIC(18,2), s1_11 NUMERIC(18,2),
							 s1_12 NUMERIC(18,2), s2_1 NUMERIC(18,2), s2_2 NUMERIC(18,2), s2_3 NUMERIC(18,2), s2_4 NUMERIC(18,2), s2_5 NUMERIC(18,2),
							 s2_6 NUMERIC(18,2), s2_7 NUMERIC(18,2), s2_8 NUMERIC(18,2), s2_9 NUMERIC(18,2), s2_10 NUMERIC(18,2), s2_11 NUMERIC(18,2),
							 s2_12 NUMERIC(18,2))

INSERT INTO #RES_ALL_GR (NUM_PACH,LINK,FM,IM,OT,INSUR_NUM,[YEAR],CODE,T_DOGOV,REG_NOM_PF,INN,KPP,
	OKPO,DCOUNT,PERS_INN,TYPE,DEP_NAME,DEP_FN, NUM_STR,DATE_DOC,s1_1,s1_2,s1_3,s1_4,s1_5,s1_6,s1_7,
	s1_8,s1_9,s1_10,s1_11,s1_12,s2_1,s2_2,s2_3,s2_4,s2_5,s2_6,s2_7,s2_8,s2_9,s2_10,s2_11,s2_12)
SELECT distinct
	NUM_PACH = 0,		-- Номер пачки
	P.LINK,
	P.FM,					-- фамилия
	P.IM,					-- имя
	P.OT,					-- отчество
	--DIF.DOC_NUM,			
	P.INSUR_NUM,			-- страховой номер
	[YEAR] = @YEAR,			-- отчетный период: год
	CODE = K.CODE,			-- код категории застрахованного лица
	T_DOGOV = CASE WHEN ISNULL(R.DOG,1) = 1 THEN 1 ELSE 0 END, -- договор (тип договора) б заключенный с застрахованным лицом
	REG_NOM_PF = @NOM_PF,	-- регистрационный номер ПФР
	INN = @INN,				-- ИНН
	KPP = @KPP,				-- КПП
	OKPO = @OKPO,			-- ОКПО

	DCOUNT = (select count(*) from #res2),
	PERS_INN = P.INN,		
	[TYPE] = @nOption,		-- тип сведений
	DEP_NAME = @DEP_NAME,  -- Наименование организации (короткое)
	DEP_FN = @DEP_FN ,		-- Полное наименование орг
	NUM_STR = 0,
	DATE_DOC = Getdate(),	-- Дата составления документа
	r.s1_1,					-- суммы по месяцам
	r.s1_2,
	r.s1_3,
	r.s1_4,
	r.s1_5,
	r.s1_6,
	r.s1_7,
	r.s1_8,
	r.s1_9,
	r.s1_10,
	r.s1_11,
	r.s1_12,
	r.s2_1,
	r.s2_2,
	r.s2_3,
	r.s2_4,
	r.s2_5,
	r.s2_6,
	r.s2_7,
	r.s2_8,
	r.s2_9,
	r.s2_10,
	r.s2_11,
	r.s2_12
FROM 
	#T_PERSON T
	INNER JOIN dbo.PERSON P ON p.link = t.link_pers
	INNER JOIN #RES2 R on r.link_pers = P.LINK
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK2 = R.KATEG	
	LEFT JOIN dbo.CITIZENSHIP S ON S.LINK = P.CITIZ_LINK
WHERE 
	@YEAR BETWEEN K.YBEG AND K.YEND
	AND 
	(
		(ISNULL(s1_1,0)+ISNULL(s1_2,0)+ISNULL(s1_3,0)+ISNULL(s1_4,0)+ISNULL(s1_5,0)+ISNULL(s1_6,0)+ISNULL(s1_7,0)+ISNULL(s1_8,0)+ISNULL(s1_9,0)+ISNULL(s1_10,0)+ISNULL(s1_11,0)+ISNULL(s1_12,0)) <> 0
		OR
		(ISNULL(s2_1,0)+ISNULL(s2_2,0)+ISNULL(s2_3,0)+ISNULL(s2_4,0)+ISNULL(s2_5,0)+ISNULL(s2_6,0)+ISNULL(s2_7,0)+ISNULL(s2_8,0)+ISNULL(s2_9,0)+ISNULL(s2_10,0)+ISNULL(s2_11,0)+ISNULL(s2_12,0)) <> 0
	)	
	
ORDER BY
	P.FM,					-- фамилия
	P.IM,					-- имя
	P.OT	

DECLARE 
	@Cur1 CURSOR, @ID int, @CODE varchar(20), @T_DOGOV int, @NUM int, @NUM_STR INT,
	@CODE1 varchar(20), @T_DOGOV1 int, @cnt int, @SA_SZV4_OPT1 int
	
	set @SA_SZV4_OPT1 = dbo.sa_get_option_by_code('SA_SZV4_OPT1')

	select @CODE1 = '', @T_DOGOV1 = -1, @cnt = 0, @NUM= @nPach -1  , @NUM_STR = 0
	if @NUM <0 
	begin 
	  set @NUM = 0
	end 
	
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR select ID, CODE, T_DOGOV from #RES_ALL_GR order by CODE, T_DOGOV
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @ID, @CODE, @T_DOGOV 
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			IF @CODE <> @CODE1 OR @T_DOGOV <> @T_DOGOV1 OR @cnt >= @SA_SZV4_OPT1
			BEGIN
				SET @NUM = @NUM + 1
				SELECT @CODE1 = @CODE, @T_DOGOV1 = @T_DOGOV, @cnt = 0, @NUM_STR = 0
			END
			
			SET @cnt = @cnt + 1
			SET @NUM_STR = @NUM_STR + 1
			
			UPDATE #RES_ALL_GR SET NUM_PACH = @NUM, NUM_STR = @NUM_STR WHERE ID = @ID
			
		END
	
		FETCH NEXT FROM @Cur1 INTO @ID, @CODE, @T_DOGOV 
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1

--РЕЗУЛЬТАТ 1
IF @MODE = 0 OR @MODE = 1
	SELECT * FROM #RES_ALL_GR ORDER BY NUM_PACH ,NUM_STR, FM, IM, OT

IF @MODE = 0 OR @MODE = 2
	SELECT 
	NUM_PACH, CODE,T_DOGOV,
	[YEAR],REG_NOM_PF,INN,KPP,OKPO,[TYPE],DEP_NAME,DEP_FN,DATE_DOC,
	s1_all = SUM(ISNULL(s1_1,0)+ISNULL(s1_2,0)+ISNULL(s1_3,0)+ISNULL(s1_4,0)+ISNULL(s1_5,0)+ISNULL(s1_6,0)+ISNULL(s1_7,0)+ISNULL(s1_8,0)+ISNULL(s1_9,0)+ISNULL(s1_10,0)+ISNULL(s1_11,0)+ISNULL(s1_12,0)),
	s2_all = SUM(ISNULL(s2_1,0)+ISNULL(s2_2,0)+ISNULL(s2_3,0)+ISNULL(s2_4,0)+ISNULL(s2_5,0)+ISNULL(s2_6,0)+ISNULL(s2_7,0)+ISNULL(s2_8,0)+ISNULL(s2_9,0)+ISNULL(s2_10,0)+ISNULL(s2_11,0)+ISNULL(s2_12,0)), 
	DCOUNT = COUNT(DCOUNT)
	FROM 
		#RES_ALL_GR 
	GROUP BY 
		NUM_PACH,CODE,T_DOGOV,[YEAR],REG_NOM_PF,INN,KPP,OKPO,[TYPE],DEP_NAME,DEP_FN,DATE_DOC
	ORDER BY 
		NUM_PACH
	

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..#RES') IS NOT NULL
--	DROP TABLE #RES1
		
IF object_id('tempdb..#RES') IS NOT NULL
	DROP TABLE #RES2	

IF object_id('tempdb..#SPR_ESN1') IS NOT NULL
	DROP TABLE #SPR_ESN1

IF object_id('tempdb..#SPR_ESN2') IS NOT NULL
	DROP TABLE #SPR_ESN2

IF object_id('tempdb..#DGH_CJ') IS NOT NULL
	DROP TABLE #DGH_CJ

END

RETURN 0









GO


GRANT EXECUTE ON dbo.[SS_PRINT_SZV63] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_773]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_773]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_773]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '*|*****|***|***|********|', '8|88888|888|888|88888888|')
      WHERE TXT LIKE '%*|*****|***|***|********|%'
            and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=03')
         and [ORDER] < (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=04')

      UPDATE #IMPORT_TABLE
      SET TXT = REPLACE(TXT, '*|*****|***|***|********|', '9|99999|999|999|99999999|')
      WHERE TXT LIKE '%*|*****|***|***|********|%'
         and [ORDER] > (select min([ORDER]) from #IMPORT_TABLE where TXT = 'ТБ=04')

      UPDATE #IMPORT_TABLE
      SET TXT = ''
      WHERE TXT IN ('ТБ=02', 'ТБ=04')


      UPDATE #IMPORT_TABLE
      SET TXT = 'ТБ=02'
      WHERE TXT IN ('ТБ=03')
 
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_773] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
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)

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 (LINK_EMPL)
	Select @LINK_EMPL
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(
	LINK_FACE INT,
	FIO VARCHAR(254),
	[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)

while @y <= year(@varKSdDate2)
begin
	insert into @months_ex
	select @y, months.* from months
	set @y = @y + 1	
end

--Список суммы последних квартальных премий
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
	(SELECT DISTINCT * from  #PERS) as E
	inner join dbo.empl em  on 1=1
	inner join 	dbo.S_J_C_Short j on e.PERS_LINK = J.LINK_FACE  
	inner join dbo.PAYS_REF PR on PR.LINK_PAYS = j.LINK_PAYS
	--inner join dbo.empl em  on 1=1
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 
	e.PERS_LINK,
	dbo.KU_GETPERSFIO(e.PERS_LINK),
	y, m, mname as mname,
	work = 	(CASE WHEN em.SYST_PAY = 1 THEN 
			dbo.SA_GET_EMPL_WD (em.link, 0, DEFAULT, dbo.ConvertDMY2Date(1,m,y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)), DEFAULT, 0)
			ELSE 
			dbo.SA_GET_EMPL_WH (em.link, 0, DEFAULT,  dbo.ConvertDMY2Date(1,m,y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)), DEFAULT, 0)
			END),
	NORM =	(CASE WHEN em.SYST_PAY = 1 THEN 
			dbo.NORM_DAY_DH (em.link,  dbo.ConvertDMY2Date(1,m,y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)))
			ELSE 
			dbo.NORM_HOUR_DH (em.link,  dbo.ConvertDMY2Date(1,m,y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)))
			END)	,
	COMMENT   =  DBO.SA_GET_EMPL_NWD_COMMENT (em.link,  DEFAULT,  dbo.ConvertDMY2Date(1,m,y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,m,y)))	,	
			
	ISNULL(SUM(case 
			when SJC.TYP_OPER = 1 then case when sjc.period_begin between @date_3mAGO and @Date1 and  sjc.year_begin = e.y and sjc.month_begin = e.m then SJC.SUMMA else 0 end 
			else 0
		end)
	, 0),
	
	qprem = convert(numeric(18,2),0)
	
from 	
	(SELECT DISTINCT * from @months_ex, #PERS) as E
	inner join dbo.empl em  on 1=1
	left outer join dbo.S_J_C_Short SJC on e.PERS_LINK = SJC.LINK_FACE 

	inner join dbo.PAYS_REF PR on PR.LINK_PAYS = SJC.link_pays
where
	em.link = @LINK_EMPL
	and
	LINK_GROUPS = @Link_GR_PAY
	AND
	(Y * 100 + M) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
	AND
	(Y * 100 + M) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
	AND
	SJC.TYP_OPER = 1
	AND
	SJC.LINK_DEP = @DEP_LINK
	and SJC.WAY_CALC not in (13, 14, 15, 6, 7)
group by
	e.PERS_LINK, y,m, mname ,em.link ,em.SYST_PAY

-- подсчитаем среднюю зп за последних 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 месяца 
DECLARE cursor2 SCROLL CURSOR FOR
SELECT WORK FROM #RES

OPEN cursor2
FETCH ABSOLUTE @Count_rows1 FROM cursor2
INTO @DF1

FETCH ABSOLUTE @Count_rows2 FROM cursor2
INTO @DF2

FETCH ABSOLUTE @Count_rows3 FROM cursor2
INTO @DF3

CLOSE cursor2
DEALLOCATE cursor2
--
--2. Количество дней по графику за 3 месяца
DECLARE cursor3 SCROLL CURSOR FOR
SELECT NORM FROM #RES

OPEN cursor3
FETCH ABSOLUTE @Count_rows1 FROM cursor3
INTO @DR1

FETCH ABSOLUTE @Count_rows2 FROM cursor3
INTO @DR2

FETCH ABSOLUTE @Count_rows3 FROM cursor3
INTO @DR3

CLOSE cursor3
DEALLOCATE cursor3

-- 3. подсчет последней Квартальной премии с разбивкой по трем последним месяцам 
if @Date1 = dbo.DateEndOfMonth(@Date1)  
	begin	
	   set @QPREM_SUMM = isnull((select Sum(summa) from #QPREM where month(date2) = convert( int ,(select  max([month]) from #RES  where [year] = year(@Date1)and [month] = (select  month(max(date2)) from #QPREM  )))),0)
	   set @QPREM_MON3 = convert( int ,(select  max([month]) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))
	   set @QPREM_MON2 = @QPREM_MON3 - 1 
	   set @QPREM_MON1 = @QPREM_MON3 - 2 	
	end
else 
	begin
	   set @QPREM_SUMM = isnull((select sum(summa) from #QPREM where month(date2) = convert( int ,(select  max([month]-1) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))),0)
	   set @QPREM_MON3 = convert( int ,(select  max([month]-1) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))	
 	   set @QPREM_MON2 = @QPREM_MON3 - 1 
 	   set @QPREM_MON1 = @QPREM_MON3 - 2 
 	end

-- сумма премии на первый месяц
SET @QPREM_S1  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR1),0)	
-- сумма премии на второй месяц
SET @QPREM_S2  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR2),0)	
-- сумма премии на третий месяц
SET @QPREM_S3  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR3),0)	

-- обновление таблицы - к суммам по последним трем месяцам, прибавляется разбитая квартальная премия 
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else (SUMMA + @QPREM_S1) end
from #RES where [month] = @QPREM_MON1 and [year] = year(@Date1)
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else (SUMMA + @QPREM_S2) end
from #RES where [month] = @QPREM_MON2 and [year] = year(@Date1)
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else  (SUMMA + @QPREM_S3) end 
from #RES where [month] = @QPREM_MON3 and [year] = year(@Date1)
---

--4. Сумма за 3 последних месяца		
DECLARE cursor1 SCROLL CURSOR FOR
SELECT SUMMA FROM #RES

OPEN cursor1 
FETCH ABSOLUTE @Count_rows1 FROM cursor1
INTO @SUMMA1

FETCH ABSOLUTE @Count_rows2 FROM cursor1
INTO @SUMMA2

FETCH ABSOLUTE @Count_rows3 FROM cursor1
INTO @SUMMA3

CLOSE cursor1
DEALLOCATE cursor1
-- 
--  Подсчет средней заработной платы за 3 последних месяца с учетом последней квартальной премии

if  isnull ((@dF1 + @dF2 + @dF3) , 0  ) > 0
	begin
		SET @SR_SUM_3MONTH  = (((@SUMMA1 + @SUMMA2 + @SUMMA3)/ (@dF1 + @dF2 + @dF3)) * (@dR1 + @dR2 + @dR3)) /3	
	end
else 
	begin
		set @SR_SUM_3MONTH = (@SUMMA1 + @SUMMA2 + @SUMMA3) / 3 
	end
---

declare @work_date datetime
set @work_date = (select workdate from user_info)
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
SELECT	RR.*,
	[NUM_SPR]	= @cNum_SPR,
	[fio] 		= KU_EM.FIO,
	[date_beg] 	= KU_EM.DATE_BEGIN,
	[PERS_INN]	= S.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
		/*R.SUMMA_NDFL AS NDFL,
		R.SUMMA_PROF AS PROF,
		R.SUMMA_ALIM AS ALIM,
		R.SUMMA_ISL AS ISL,
		R.SUMMA - R.SUMMA_UD AS DOHOD,
		R.SUMMA_UD - R.SUMMA_NDFL - R.SUMMA_PROF - R.SUMMA_ALIM - R.SUMMA_ISL AS PROCH*/
	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
	inner join sd_empl s on s.link = KU_EM.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_SZV4_PACHKA_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV4_PACHKA_SAVE]

GO
CREATE   PROCEDURE dbo.SA_SZV4_PACHKA_SAVE
	@LINK		int	OUTPUT,
	@Numer		int = null,
	@Date		datetime = null,
	@year_begin	int = null,
	@month_end	tinyint = null,
	@PER		tinyint = null,
	@YEAR_EDT	int = null,
	@PER_EDT	tinyint = null,
	@KATEG		tinyint = null,
	@type		tinyint = null,
	@vid_kor	tinyint = null,
	@LINK_SELF INT = NULL
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int 	
declare @varKSPeriodLink	 int, @varKSsoLink int, @varKSRowCount INT


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

IF @Numer IS NULL OR @Numer = '' or @Date IS NULL OR @year_begin  IS NULL OR @month_end  IS NULL OR @type  IS NULL OR @vid_kor  IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV4_PACHKA'

IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO dbo.SZV4_PACHKA WITH (ROWLOCK) (Numer,[Date],year_begin,month_end,PER,YEAR_EDT, PER_EDT, KATEG, [type],vid_kor, link_dep, LINK_SELF)  
			VALUES (@Numer, @Date ,@year_begin, @month_end, @PER, @YEAR_EDT, @PER_EDT, @KATEG, @type, @vid_kor, @DEP_LINK, @LINK_SELF)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE dbo.SZV4_PACHKA WITH (ROWLOCK) 
		SET 	Numer = @Numer, [Date] = @Date, year_begin = @year_begin, month_end = @month_end, 
				PER = @PER, YEAR_EDT = @YEAR_EDT, PER_EDT = @PER_EDT, KATEG = @KATEG,
				[type] = @type, vid_kor = @vid_kor, LINK_SELF = @LINK_SELF
		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END


declare @varKSEventText varchar(200)
SET @varKSEventText = 'Пачка для персонифицированного учета № ' + RTRIM(LTRIM(convert(varchar(10),@Numer))) + ' от ' + CONVERT(VARCHAR(10),@Date,104)
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV4_PACHKA',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_SAVE] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
SET ANSI_WARNINGS OFF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_REPORT_ANALITICS_GET_LSF]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_REPORT_ANALITICS_GET_LSF]
GO

CREATE procedure [dbo].[RT_REPORT_ANALITICS_GET_LSF]
	@nPeriod_Type int,
	@nPeriod_Date_Start datetime,
	@nPeriod_Number_Start int,
	@nPeriod_Date_Stop datetime,
	@nPeriod_Number_Stop int,
	@nStatus int,
	@nFormVersion int = null,
	@cTable varchar(254) = null
as

CREATE table #analitics_period_links (period_type int, period_date datetime, period_number int, link_form int, link_table int, link_col int, link_col_base int, col_type tinyint, keyflag tinyint)

declare	@this_link_form int,
		@this_link_table int,
		@this_link_col int,
		@this_link_col_type tinyint


while exists(select * from #analitics_links) begin -- цикл по отмеченным формам (потому что может быть отмечена более чем одна форма)
	select top 1 @this_link_form = link_f, @this_link_table = link_t, @this_link_col = link_c, @this_link_col_type = col_type from #analitics_links
	-- заполняем таблицу #analitics_period_links. каждому периоду будет соответствовать акуальная в том периоде форма

   
	insert into #analitics_period_links (period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, col_type, keyflag)
	select distinct
		rsf.period_type, 
		rsf.begin_date, 
		rsf.period_number,
		rsf.link_form,
		[link_table] = (
			case 
				when exists(select * from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
				then (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
				else (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[orders] = (select top 1 rt1.[orders] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
			end
		),
		[link_col] = (
			case
				when exists(
					select * 
					from dbo.report_coloumns as rc0 (nolock)
					where rc0.link_table = (
						case 
							when exists(select * from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							then (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							else (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[orders] = (select top 1 rt1.[orders] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
						end
					)
					and rc0.[name] = (select top 1 rc1.[name] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col)
				)
				then (
					select top 1 rc0.link_col 
					from dbo.report_coloumns as rc0 (nolock)
					where rc0.link_table = (
						case 
							when exists(select * from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							then (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select top 1 rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							else (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[orders] = (select top 1 rt1.[orders] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
						end
					)
					and rc0.[name] = (select top 1 rc1.[name] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col)
					and rc0.[col_type] = (select top 1 rc1.[col_type] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col)
				)
				else (
					select top 1 rc0.link_col 
					from dbo.report_coloumns as rc0 (nolock)
					where rc0.link_table = (
						case 
							when exists(select * from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							then (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[name] = (select rt1.[name] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
							else (select top 1 rt0.link_table from dbo.report_tables as rt0 (nolock) where rt0.link_form = rsf.link_form and rt0.[orders] = (select rt1.[orders] from dbo.report_tables as rt1 (nolock) where rt1.link_table = @this_link_table))
						end
					)
					and rc0.[orders] = (select rc1.[orders] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col)
					and rc0.[col_type] = (select rc1.[col_type] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col)
				)
			end
		),
	link_col_base = @this_link_col,
	col_type = (select rc1.[col_type] from dbo.report_coloumns as rc1 (nolock) where link_col = @this_link_col),
	null
	from 
		dbo.report_saved_forms as rsf (nolock)
	where 
		rsf.link_form = (select top 1 rf.link_form from dbo.report_forms as rf (nolock) where rf.code = (select rf0.code from dbo.report_forms as rf0 (nolock) where rf0.link_form = @this_link_form) and rsf.begin_date between rf.start_date and isnull(rf.end_date,'20501231')) -- линк формы ищется по коду формы
		and rsf.period_type = @nPeriod_Type 
		and (rsf.begin_date between @nPeriod_Date_Start and @nPeriod_Date_Stop)
		
	delete from #analitics_links where link_c = @this_link_col
end
update #analitics_period_links
set keyflag = (case when apl.link_col = (select a.link_code_col from dbo.report_tables as a where a.link_table = apl.link_table) then 1 else 0 end)
from #analitics_period_links as apl

--select * from #analitics_period_links

-- Создание таблицы сохранённых форм
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)
-- предполагается, что к этому моменту существует таблица #analitics_filters, содержащая среди прочего код аналитического признака CODE и текстовое значение VALUE 



insert into #sf
select DISTINCT
	rsf.link_saved_form,
	rsf.link_form, 
	rsf.period_type, 
	rsf.period_number,
	rsf.begin_date,
	rsf.link_organization,
	[btype] = (select [name] from dbo.BI_DICTION_BUDG_TYPE (nolock) where link = rsf.link_type_svod),
    rsf.link_type_svod
from report_saved_forms as rsf (nolock) 
	inner join (select distinct period_type, period_date, period_number, link_form from #analitics_period_links) as apl
	on 
		apl.link_form = rsf.link_form
      AND rsf.del = 0
		and apl.period_date = rsf.begin_date
		and apl.period_type = rsf.period_type
		and apl.period_number = rsf.period_number
where  
	rsf.version = 
		case
			when @nFormVersion < 0 or @nFormVersion is null
			then(
				select top 1 version
	 			from 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 lrsf.[atr_code] = rsf.[atr_code]
				order by  version desc
			)
			else @nFormVersion
		end		
	and rsf.IsSvod in (
        case when @nStatus&0x10 = 0x10 then 1 else -1 end,
		case when @nStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (
        case when @nStatus&0x01 = 0x01 then 0 else -1 end,
		case when @nStatus&0x02 = 0x02 then 1 else -1 end,
		case when @nStatus&0x04 = 0x04 then 2 else -1 end,
		case when @nStatus&0x08 = 0x08 then 3 else -1 end,
		case when @nStatus&0x40 = 0x40 then 4 else -1 end,
		case when @nStatus&0x80 = 0x80 then 5 else -1 end)

if @cTable is not null
	execute('insert into '+@cTable+'(link_sf) select distinct link_sf from #sf')
exec DropTempTable '#analitics_period_links'
exec DropTempTable '#sf'
GO
grant execute on [dbo].[RT_REPORT_ANALITICS_GET_LSF] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_ZKR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_ZKR]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE dbo.BB_EXPORT_ZKR
	@cBuffId	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS
DECLARE @iDepLink	int, 
	@cCodeOpt 	int,
	@iNoteDCL	tinyint,
	@cPrefDCL	varchar(10), 
	@cKorrName	varchar(254), 
	@iLongFio tinyint, 
	@iPostRuk tinyint, 
	@iPostGl tinyint


set @iPostRuk = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_RUK')
set @iPostGl = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_GL')
set @iLongFio = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_FIO')

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
select @cCodeOpt = KODBP,
	@iNoteDCL = isnull(T_DCL,0),
	@cPrefDCL = isnull(rtrim(PREF_DCL) + ' ',''),
	@cKorrName = isnull(rtrim(KOR_NAME),'<Наим_орг_полн>')
from dbo.BB_ZAYAVKA_KR_OPTIONS

-- Таблица 2 (FROM)
SELECT 	BUDG_LEVEL  = case D.BUH_TYPE WHEN 1 then cast(replace(B.CODE_EL,'0','') as char(1)) else '6' end,
		KOD_UBP = case cast(replace(B.CODE_EL,'0','') as char(1)) when 1 then D.CODE_UBP else BUDG end,
		NAME_UBP	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,254),
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME,
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



-- Таблица 4 (ZR)


	SELECT  LINK 		 = ZKR.LINK,
			LINK_UP		 = ZKR.LINK,
			GUID_FK		 = '',
			[TYPE]		 = cast(ZKR.SHORT + 1 as char(1)),
			NOM_ZR		 = ZKR.NUMBER,
			DATE_ZR		 = ZKR.DATE,
			KOD_UBP_PAY	 = case @cCodeOpt when 1 then ZKR.DEP_UBP else '' end,
			NAME_UBP_PAY = ZKR.DEP_FNAME, 
			LS_UBP_PAY	 = ZKR.ACC_CODE,
			INN_UBP		 = '',
			KPP_UBP		 = '',
			GLAVA_GRS	 = case ZKR.dep_type WHEN 1 then ZKR.GRBS_CODE else '' end,
			NAME_UBP_GRS = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.GRBS_NAME else ZKR.UCHR_NAME end  else '' end,
			NAME_BUD	 = case ZKR.dep_type WHEN 1 then ZKR.BUDG_NAME else '' end,
			NAME_FO		 = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.FO_NAME else '' end else '' end,
			KOD_TOFK	 = ZKR.TOFK_CODE,
			NAME_TOFK	 = ZKR.TOFK_NAME,
			DATE_ISP	 = ZKR.SROK,
			NOM_BO		 = ZKR.BO_NUM,
			KOD_ISP		 = '',
			PR_ISP		 = '',
			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		 = ZKR.KOR_RACC,
			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(@iDepLink, 'Руководитель') B on ZKR.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(@iDepLink, 'Главный бухгалтер') 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
	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))
	order by ZO.LINK


-- Таблица 4 (ZRST)
	select  ZT.LINK,
			LINK_UP = coalesce((select top 1 LINK from ZAYAVKA_KR_OSNOV where LINK_UP = ZT.LINK_UP order by LINK desc),ZT.LINK_UP),
			KOD_IST_KBK	  = cast(ZT.VID_SR as char(1)),
			TYPE_KBK_PAY  = case ZT.KBK_TYPE when 1 then '10'
											 when 2 then '20'
											 when 4 then '31'
											 when 8 then '32'
											 else '' end,
			KBK_PAY		  = left(replace(ZT.BK_CODE,'.',''),20),
			TYPE_KBK_RCP  = case ZKR.SHORT when 0 then case ZT.KBK_TYPE_d when 1 then '10'
																		  when 2 then '20'
																		  when 4 then '31'
																		  when 8 then '32'
																		  else '' end else '' end,
			KBK_RCP		  = case ZKR.SHORT when 0 then left(replace(ZT.BKD_CODE,'.',''),20) else '' end,
			ADD_KLASS_PAY = ZT.DCL_CODE,
			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
	where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_EXPORT_ZKR to public
GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV4_PACHKA_CALC_Buffer2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV4_PACHKA_CALC_Buffer2]

GO

CREATE   PROCEDURE [dbo].SA_SZV4_PACHKA_CALC_Buffer2 (@BufferCode varchar(10), @link int, @Year int, @Month tinyint) 
AS

DECLARE @SQL VARCHAR(1000)

SET @SQL = '
delete from dbo.Buffer
where RTRIM(LTRIM(ID)) = RTRIM(LTRIM( ''' + @BufferCode + ''' ))
	and link IN (select S.link_pers from dbo.SZV4_SVEDENIA S where S.link_up = ' + CONVERT(VARCHAR(20),@LINK) + ')'
--EXEC (@SQL)	

CREATE TABLE #PERSON (LINK INT)	

SET @SQL = '
INSERT INTO #PERSON (LINK)
SELECT DISTINCT LINK FROM dbo.Buffer WHERE RTRIM(LTRIM(ID)) = RTRIM(LTRIM(''' + @BufferCode + '''))'
EXEC (@SQL)	

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @PER TINYINT, @MONTH_END TINYINT, @MONTH_BEG TINYINT
SELECT @Year = YEAR_BEGIN, @PER = PER, @MONTH_END = MONTH_END
FROM dbo.SZV4_PACHKA WHERE LINK = @link

DECLARE @PeriodBegin datetime, @PeriodEnd datetime

IF @Year = 2010
BEGIN
	SET @MONTH_BEG = (CASE WHEN @PER = 2 THEN 1 ELSE 7 END)
	SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+6-1) THEN @MONTH_END ELSE (@MONTH_BEG+6-1) END)
END

IF @Year > 2010
BEGIN
	SET @MONTH_BEG = (CASE @PER WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 WHEN 4 THEN 10 END)
	SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)
END

SELECT @PeriodBegin = dbo.ConvertDMY2Date(1,@MONTH_BEG,@Year), @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH_END,@Year))

--ВЫДЕЛЕНИЕ КАТЕГОРИЙ ФИЗ.ЛИЦ
--ИНВАЛИДЫ
DECLARE @LINK_OZOI INT
SET @LINK_OZOI = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 3 AND @Year BETWEEN YBEG AND YEND),1)

------	у кого была инвалидность в заданном периоде
SELECT PERS_LINK, DATE_BEGIN = MIN(ISNULL(I.DATE_BEGIN,@PeriodBegin)), DATE_END = MAX(ISNULL(I.DATE_END,@PeriodEnd))
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin
GROUP BY PERS_LINK

insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, 2, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_OZOI,
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END,
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
from 
	(	SELECT B.LINK 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK 
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	INNER JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		

----ОБЩИЕ
DECLARE @LINK_NR INT
SET @LINK_NR = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 1 AND @Year BETWEEN YBEG AND YEND),1)
	
insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, 2, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_NR,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodBegin < CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		THEN @PeriodBegin 
		ELSE CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END + 1
	END,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodEnd > CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		THEN @PeriodEnd
		ELSE CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END - 1
	END
from 
	(	SELECT B.LINK 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK 
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		
WHERE --Добавляем если не было инвалидов или инвалидность была не весь период
	I.PERS_LINK IS NULL --не было инвалидов
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1	

----ЕНВД
DECLARE @LINK_USEN INT
SET @LINK_USEN = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 2 AND @Year BETWEEN YBEG AND YEND),1)		
	
insert into dbo.SZV4_SVEDENIA 
	(link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
SELECT 	
	link_up, orders, forma, link_pers, ISNULL(sum_doh,0), ISNULL(sum_str,0), ISNULL(sum_nak,0), ISNULL(sum_dop,0), ISNULL(dper_vn_m,0), ISNULL(dper_vn_d,0), ISNULL(dper_oz_m,0), ISNULL(dper_oz_d,0), ISNULL(isum_str,0), ISNULL(isum_nak,0), @LINK_USEN, DATE_BEG, DATE_END
FROM
	#PERSON B INNER JOIN dbo.SZV4_SVEDENIA S ON B.LINK = S.link_pers 
WHERE
	link_up = @link
	AND
	LINK_KATEG = @LINK_NR	
		
----СУММЫ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ
CREATE TABLE #PERS_SUM (LINK_PERS INT, LINK_KATEG INT, SUMMA_BASE NUMERIC(18,2), SUMMA_I NUMERIC(18,2), SUMMA_G NUMERIC(18,2))
INSERT INTO #PERS_SUM (LINK_PERS, LINK_KATEG, SUMMA_BASE, SUMMA_I, SUMMA_G)
SELECT LINK_PERS, LINK_KATEG,
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA_BASE ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 7 THEN SUMMA ELSE 0 END)	
FROM
(
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.link_pers = B.LINK
		INNER JOIN dbo.EMPL E ON E.PERS_LINK = S.LINK_PERS
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_EMPL = E.LINK AND J.PERIOD_BEGIN BETWEEN S.DATE_BEG AND S.DATE_END
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND P.[OBJECT] = 3
		AND P.[WAY_CALC] IN (6, 7)
		AND J.LINK_DEP = @DEP_LINK
		AND
		(LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG
	UNION ALL	
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.PERS_LINK = S.LINK_PERS AND J.PERIOD_BEGIN BETWEEN S.DATE_BEG AND S.DATE_END
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND P.[OBJECT] = 3
		AND P.[WAY_CALC] IN (6, 7)
		AND J.LINK_DEP = @DEP_LINK
		AND
		(LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG
) T
GROUP BY LINK_PERS, LINK_KATEG

--
UPDATE S SET
	sum_doh = ISNULL(SUMMA_I,0), --После 10 года содержит начисленную страховую часть
	sum_str = 0, --После 10 года должен содержать перечисленную страховую часть, но т.к. ее не знаем - то 0, потом определим
	sum_nak = ISNULL(SUMMA_G,0), --Для все периодов содержит начисленную накопительную часть
	sum_dop = 0 -- После 10 года должен содержать перечисленную накопительную часть, но т.к. ее не знаем - то 0, потом определим
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #PERS_SUM P ON P.LINK_PERS = S.LINK_PERS AND P.LINK_KATEG = S.LINK_KATEG
WHERE
	link_up = @link

--У кого нет дохода, но есть стаж
SELECT LINK_PERS INTO #TAB FROM dbo.SZV4_SVEDENIA WHERE LINK_UP = @link GROUP BY LINK_PERS HAVING SUM(sum_doh) = 0 AND SUM(sum_nak) = 0
--	
DELETE FROM dbo.SZV4_SVEDENIA 
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 AND LINK_KATEG NOT IN( @LINK_NR, @LINK_OZOI)

DELETE FROM dbo.SZV4_SVEDENIA
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 
	AND NOT EXISTS (SELECT LINK_PERS FROM #TAB T WHERE T.LINK_PERS = dbo.SZV4_SVEDENIA.LINK_PERS)

---- РАСПРЕДЕЛЕНИЕ ПЕРЕЧИСЛЕННОЙ СУММЫ ПО ФИЗЛИЦАМ
EXEC [dbo].SA_SZV4_PACHKA_RASPIL @link

---СВЕДЕНИЯ О СТАЖЕ
----------------------------------------------------------------------------
CREATE TABLE #PERIODY (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] int, NUM_STAKE NUMERIC(5,2))

--/*Стаж сотрудников*/
INSERT INTO 
	#PERIODY (link_face, LINK_KATEG, date1, date2, type)
SELECT 	DISTINCT
	PERS_LINK, LINK_KATEG,
	CASE WHEN S.DATE_BEG < (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
		THEN (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
		THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
		ELSE S.DATE_END
	END,	
	0
FROM
	#PERSON B
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
	INNER JOIN dbo.EMPL E ON S.LINK_PERS = E.PERS_LINK AND E.DEP_LINK = @DEP_LINK
	INNER JOIN dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
	LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
WHERE
	S.LINK_UP = @link
	AND
	P.DATE_BEGIN <= @PeriodEnd
	AND
	coalesce(U.DIS_DATE,'20990101') >= @PeriodBegin

/*Стаж договорников*/
Select DISTINCT
	link_face = DGH.PERS_LINK, LINK_KATEG,
	date1 = CASE WHEN S.DATE_BEG < (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
			THEN (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
	date2 = CASE WHEN S.DATE_END > (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
			THEN (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
	[type] = 0
INTO #DGH	
FROM
	#PERSON B
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
	INNER JOIN dbo.SALARY_REESTR_DGH DGH ON S.LINK_PERS = DGH.PERS_LINK
WHERE 
	S.LINK_UP = @link
	AND
	DGH.DEP_LINK = @DEP_LINK
	and
	DGH.DATE1 <= @PeriodEnd
	and
	coalesce(DGH.DATE2,'20990101') >= @PeriodBegin

--
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
SELECT link_face, LINK_KATEG, date1, date2, [type] FROM #DGH A
WHERE NOT EXISTS (SELECT * FROM #PERIODY B WHERE A.link_face = B.link_face AND A.LINK_KATEG = B.LINK_KATEG AND A.date1 BETWEEN B.DATE1 AND B.DATE2 AND A.date2 BETWEEN B.DATE1 AND B.DATE2)

-- Периоды в сведениях впишем в периоды работы
SELECT LINK_FACE, DB = MIN(DATE1), DE = MAX(DATE2)
INTO #WORK
FROM #PERIODY
GROUP BY LINK_FACE

UPDATE S SET 
	S.DATE_BEG = CASE WHEN W.DB < S.DATE_BEG THEN S.DATE_BEG ELSE W.DB END,
	S.DATE_END = CASE WHEN W.DE > S.DATE_END THEN S.DATE_END ELSE W.DE END
FROM 
	dbo.SZV4_SVEDENIA S INNER JOIN #WORK W ON S.LINK_PERS = W.LINK_FACE
WHERE 
	S.LINK_UP = @link

--
CREATE TABLE #ADD_TYPE (
	[type] INT IDENTITY(1,1),
	[TERR_USL_TRUD] int NULL ,
	[TERR_RK] numeric(3, 2) NULL ,
	[OSOB_USL_TRUD] int NULL ,
	[COD_POS_SPISOK] int NULL ,
	[COD_POS_SPISOK2] int NULL ,
	[USL_DOSROCH_PENS] int NULL ,
	[STAVKA_PED_MED] numeric(3, 2) NULL
)	
--Новые типы
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)
FROM dbo.staff
WHERE ISNULL(TERR_USL_TRUD,0) <> 0 OR ISNULL(TERR_RK,0) <> 0 OR ISNULL(OSOB_USL_TRUD,0) <> 0 OR ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0 OR ISNULL(USL_DOSROCH_PENS,0) <> 0 OR ISNULL(STAVKA_PED_MED,0) <> 0

DECLARE @MAX_TYPE INT
SET @MAX_TYPE = ISNULL((SELECT MAX(type) FROM #ADD_TYPE),0)

--Периоды работы на должности c параметрами для персучета
INSERT INTO 
	#PERIODY (link_face, LINK_KATEG, date1, date2, [type], NUM_STAKE)
SELECT DISTINCT 
	link_face = E.PERS_LINK, S.LINK_KATEG,
	date1 = CASE WHEN S.DATE_BEG < (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
				THEN (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
				ELSE S.DATE_BEG
			END,
	date2 = CASE WHEN 
					(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
						THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
						ELSE S.DATE_END
					END)
						> (case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
				THEN 
					(case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
				ELSE 
					(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
						THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
						ELSE S.DATE_END
					END)
			END,	
	ISNULL(T.[type],0),
	ISNULL(im.NUM_STAKE,0)
FROM 
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
	INNER JOIN dbo.sa_item_move im ON im.EMPL_LINK = e.link
	inner join dbo.staff_head sh on sh.link = STAFF_LINK
	inner join dbo.staff st on st.link_up = sh.link
	LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
	left join #ADD_TYPE T on ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0)
where 
	S.LINK_UP = @link
	AND
	im.DATE_BEGIN <= @PeriodEnd and im.DATE_END3 >= @PeriodBegin
	and 
	st.DATE_BEGIN <= @PeriodEnd and st.DATE_END >= @PeriodBegin
	AND
	T.[TYPE] IS NOT NULL
	AND
	COALESCE(U.DIS_DATE,'20990101') >= @PeriodBegin
order by
	E.PERS_LINK

---**************************************

SET @MAX_TYPE = @MAX_TYPE + 1
DECLARE @TMP_TYPE INT
SET @TMP_TYPE = @MAX_TYPE

/*Перерыв - отпуска без кодов (для корр. льготных периодов)*/
INSERT INTO 
	#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
Select DISTINCT 
	E.pers_link, LINK_KATEG,
	CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		THEN (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@TMP_TYPE
FROM 
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
	inner join dbo.item_vacation iv on E.link = iv.EMPL_LINK 
	inner join dbo.orders o on iv.order_link=o.link
	-- Только отпуск, помеченный как "Не включать в льготный стаж", --Не административный (Для него свой код)
	INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1 AND NO_SAL <> 1
	left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and ISNULL(ivb.active,0) = 1
--	LEFT JOIN #PERIODY P ON P.link_face = P.LINK AND P.LINK_KATEG = S.LINK_KATEG AND P.[TYPE] = @TMP_TYPE
where
	S.LINK_UP = @link
	AND 	
	E.DEP_LINK = @DEP_LINK
	and
	iv.active = 1 
	and
	iv.date_begin <= @PeriodEnd
	and
	ISNULL(ISNULL(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
	and -- Не по уходу за ребенком (Для него свой код)
	IV.type_link not in (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7)
	--AND
	--P.link_face IS NOT NULL AND 

/*Перерыв - командировки без кодов (для корр. льготных периодов)*/	
INSERT INTO 
	#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
SELECT DISTINCT
	E.pers_link, LINK_KATEG,
	CASE WHEN S.DATE_BEG < (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
		THEN (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
		THEN (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@TMP_TYPE
FROM 
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
	inner join dbo.item_travel T on E.link = T.EMPL_LINK
	left join dbo.ITEM_TRAVEL_LONG ITL on ITL.TRAVEL_LINK = T.LINK and ISNULL(ITL.ACTIVE,0) = 1	
WHERE
	S.LINK_UP = @link
	AND 	
	E.DEP_LINK = @DEP_LINK
	AND 
	T.ACTIVE = 1 
	AND 
	T.DATE_BEGIN <= @PeriodEnd
	AND 
	ISNULL(ISNULL(ITL.NEW_DATE_END,T.date_end),'20990101') >= @PeriodBegin

/*Перерыв - Больничный по переменности и родам ДЕКРЕТ*/
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
SELECT 
	E.PERS_LINK, LINK_KATEG, 
	CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
		THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
		THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@MAX_TYPE + 1
FROM 
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
	inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
	INNER JOIN dbo.NETRUD N ON N.LINK = [TYPE] AND N.DEKRET = 1
WHERE 
	S.LINK_UP = @link
	AND	
	E.DEP_LINK = @DEP_LINK
	and
	D.date1 <= @PeriodEnd
	and
	coalesce(D.date2,'20990101') >= @PeriodBegin

/*Перерыв - Больничный ВРНЕТРУД*/
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
SELECT 
	E.PERS_LINK, LINK_KATEG, 
	CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
		THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
		THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@MAX_TYPE + 3
FROM 
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
	inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
WHERE
	S.LINK_UP = @link
	AND	 
	E.DEP_LINK = @DEP_LINK
	and
	D.date1 <= @PeriodEnd
	and
	coalesce(D.date2,'20990101') >= @PeriodBegin
	and
	[TYPE] not in (select LINK from dbo.NETRUD where DEKRET = 1)

/*Перерыв - Уход за ребенком до 1,5 и до 3 лет*/
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
Select E.pers_link, LINK_KATEG,
	CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@MAX_TYPE + 2
FROM
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
	inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
	INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7) VV ON VV.LINK = type_link
	left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
where 
	S.LINK_UP = @link
	AND		
	E.DEP_LINK = @DEP_LINK
	and
	iv.active = 1 
	and
	iv.date_begin <= @PeriodEnd
	and
	coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

/*Перерыв - Отпуск без сохранения содержания АДМИНИСТР*/
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
Select E.pers_link, LINK_KATEG,
	CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
		ELSE S.DATE_BEG
	END,
	CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
		ELSE S.DATE_END
	END,
	@MAX_TYPE + 4
FROM
	#PERSON P
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
	INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
	inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
	INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
	left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
where
	S.LINK_UP = @link
	AND		 	
	E.DEP_LINK = @DEP_LINK
	and
	iv.active = 1 
	and
	iv.date_begin <= @PeriodEnd
	and
	coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

--------------------------------------------------------------------------

-- 2. Выстроим последовательность периодов с учетом их пересечений и приоритетов по полю type.
--- Предполагается, что на первом шаге однотипные периоды уже нормализованы, т.е. следующие подряд и вложенные объединены
CREATE TABLE #PERIODY3 (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] INT, orders int, i int, NUM_STAKE NUMERIC(5,2), TYPE_ADD INT)


--Все промежутки заполняются типом -1  т.е. несуществующими днями
INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, [type])
SELECT DISTINCT link_face, LINK_KATEG, @PeriodBegin, @PeriodEnd, [type] = -1  FROM #PERIODY

CREATE TABLE #DAYS (ID INT IDENTITY(1,1), LINK_FACE INT, LINK_KATEG INT, [DATE] DATETIME, [TYPE] INT, NUM INT, NUM_STAKE NUMERIC(5,2), [TYPE_ADD] INT)

INSERT INTO #DAYS (LINK_FACE, LINK_KATEG, [DATE], [TYPE], NUM, NUM_STAKE, [TYPE_ADD])
SELECT P.LINK_FACE, P.LINK_KATEG, [DATE], [TYPE] = MAX([TYPE]), 0, NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), [TYPE_ADD] = MAX(CASE WHEN [TYPE] < @MAX_TYPE THEN [TYPE] ELSE 0 END)
FROM 
	#PERIODY P
	INNER JOIN dbo.days_ex(@PeriodBegin, @PeriodEnd) D ON 1=1
WHERE
	D.[DATE] BETWEEN P.DATE1 AND P.DATE2
GROUP BY
	P.LINK_FACE, P.LINK_KATEG, [date] 	
ORDER BY	
	P.LINK_FACE, P.LINK_KATEG, [date]

--Пронумеровать группы
DECLARE 
	@ID INT, @ID1 INT, @ID2 INT, @LINK_FACE INT, @LINK_KATEG INT, @TYPE INT, @NUM INT,
	@LINK_FACE1 INT, @LINK_KATEG1 INT, @TYPE1 INT

--Убрать временные периоды, которые заводились для корректировки льготных периодов
UPDATE #DAYS SET [type] = 0 WHERE [type] = @TMP_TYPE

--	
SELECT TOP 1 @ID1 = 0, @ID2 = 0, @NUM = 0, @LINK_FACE1 = LINK_FACE, @LINK_KATEG1 =LINK_KATEG, @TYPE1 = [TYPE]
FROM #DAYS
order by ID
--
DECLARE @Cur1 CURSOR
SET @Cur1 = CURSOR FORWARD_ONLY
FOR SELECT ID, LINK_FACE, LINK_KATEG, [TYPE] from #DAYS order by ID
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		IF NOT (@LINK_FACE = @LINK_FACE1 AND @LINK_KATEG = @LINK_KATEG1 AND @TYPE = @TYPE1)
		BEGIN
			
			SELECT @NUM = @NUM + 1, @LINK_FACE1 = @LINK_FACE, @LINK_KATEG1 = @LINK_KATEG, @TYPE1 = @TYPE
			UPDATE #DAYS SET NUM = @NUM WHERE ID BETWEEN @ID1 AND @ID-1
			SELECT @ID1 = @ID 

		END

	END

	FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
END

CLOSE @Cur1
DEALLOCATE @Cur1
--
UPDATE #DAYS SET NUM = @NUM+1 WHERE ID >= @ID1

--
INSERT INTO #PERIODY3 (link_face, LINK_KATEG, date1, date2, [type], orders, i, NUM_STAKE, TYPE_ADD)
SELECT LINK_FACE, LINK_KATEG, DATE_BEG =  MIN([DATE]), DATE_END = MAX([DATE]), [TYPE], 0, 0, NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), TYPE_ADD
FROM #DAYS	
GROUP BY LINK_FACE, LINK_KATEG, NUM, [TYPE], TYPE_ADD
ORDER BY LINK_FACE, LINK_KATEG, DATE_BEG, DATE_END

--Удаляем временные промежутки
DELETE FROM #PERIODY3 WHERE [TYPE] = -1

/*пронумеруем периоды*/
DECLARE @uslovie INT
set @uslovie = 1
while @uslovie > 0
begin
	update #PERIODY3 set orders = @uslovie 
	from #PERIODY3 as tt
	where 	coalesce(orders,0) = 0
		and date1 = (select min(t.date1) from #PERIODY3 t where coalesce(orders,0) = 0 and t.link_face = tt.link_face AND T.LINK_KATEG = TT.LINK_KATEG)

	if @@rowcount > 0
		set @uslovie = @uslovie + 1
	else
		set @uslovie = 0
end

----------------------------------------------------------------------------
insert into dbo.SZV4_STAZH (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k)
Select S.link, P.orders, P.date1, P.date2, 
	ter_usl = spr1.CODE, 
	ter_koef = TERR_RK, 
	osob_usl = spr2.CODE, 
	osob_k1 = spr6.CODE, 
	osob_k2 = spr7.CODE,
	osob_k3 = NULL,
	is_osnov = NULL, 
	is_dop = (case P.[type] when @MAX_TYPE + 1 then 'ДЕКРЕТ' when @MAX_TYPE + 2 then 'ДЕТИ' when @MAX_TYPE + 3 then 'ВРНЕТРУД' when @MAX_TYPE + 4 then 'АДМИНИСТР' else '' end), 
	is_dop_m = NULL, 
	is_dop_d = NULL, 
	ud_osnov = spr5.CODE, 
	ud_dop_m = NULL, 
	ud_dop_d = NULL, 
	ud_dop_k = STAVKA_PED_MED * NUM_STAKE
from
	#PERSON B 
	INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
	inner join #PERIODY3 P on S.link_pers = P.link_face AND S.LINK_KATEG = P.LINK_KATEG
	LEFT JOIN #ADD_TYPE T on 
		T.[TYPE] = P.[TYPE] -- Период со льготным стажем по приоритету
		OR 
		(P.[TYPE] = (@MAX_TYPE + 3) AND T.[TYPE] = P.[TYPE_ADD]) -- Период ВРНЕТРУД по приоритету + льготный период
		OR 
		(P.[TYPE] = (@MAX_TYPE + 1) AND T.[TYPE] = P.[TYPE_ADD]) -- Период ДЕКРЕТ по приоритету + льготный период		
	LEFT JOIN dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.LINK = T.TERR_USL_TRUD
	LEFT JOIN dbo.szv4_spr spr2 on spr2.spr_code = 'OSOB_USL_TRUDA' and spr2.LINK = T.OSOB_USL_TRUD
	--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
	--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
	left join dbo.szv4_spr spr5 on spr5.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5.LINK = T.USL_DOSROCH_PENS
	left join dbo.szv4_spr spr6 on spr6.SPR_CODE LIKE 'SPISOK%' and spr6.LINK = T.COD_POS_SPISOK
	left join dbo.szv4_spr spr7 on spr7.SPR_CODE LIKE 'SPISOK%' and spr7.LINK = T.COD_POS_SPISOK2
	--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3
where
	S.link_up = @link
order by
	S.link, P.orders

--------------------------------------------------------------------------
exec dbo.SZV4_NUMERATOR @link




GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_CALC_Buffer2] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_SAVE]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_SAVE]
END

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
-- Коды ошибок
--  0 -- Успешный импорт.
-- -1 -- Организации с таким кодом бюджетополучателя не существует
-- -2 -- Отсутствует код бюджета
-- -3 -- Нет доступа к организации
-- -4 -- Не найден бюджет с таким кодом
-- -5 -- Организация(и) не стоит(ят) в данном бюджете
-- -6 -- Нет прав для удаления старого отчета.
-- -7 -- Отчет уже существует! Перезаписать существующий отчет на импортируемый (ДАННЫЕ СУЩЕСТВУЮЩЕГО ОТЧЕТА ПОТЕРЯЮТСЯ) 
-- -8 -- Ошибка в dbo.[I_REPORT_SAVE_FORM].
-- -9 -- Отчет имеет статус "Утвержден". Измените статус отчета перед импортом.
-- -10 -- Отчет имеет статус "Включен в свод". Измените статус отчета перед импортом.
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_SAVE]
  @iLSF             INT OUTPUT,
  @iLINK_SAVED_FORM INT = NULL,  
  @bWEB             BIT = 1,-- с тонкого клиента
  @iRepeatRequest   INT = NULL, -- FOR WEB only повторный запуск 0 - Да, 1 - Нет  
  @tIsAppend        TINYINT = 0, -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
  @tMode            TINYINT = 0 -- Режим работы: 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON
DECLARE @lvcTmp          VARCHAR(8000),
        @lvcResult       VARCHAR(8000),
        @liError         INT,
        @lcCODE_FORM     CHAR(20),   
        @lvcKBP          VARCHAR(100),
        @lvcVB           VARCHAR(10),
        @ldBEGIN_DATE    DATETIME,
        @ltPERIOD_TYPE   TINYINT,
        @lvcATRIBUTS     VARCHAR(500),
        @ltPERIOD_NUMBER TINYINT,
        @lbIsEmptyVB     BIT,
		  @ltIsRO			 TINYINT,

        @liLINK_FORM         INT,
        @lvcLINK_SAVED_FORM  VARCHAR(50),
        @liLINK_ORGANIZATION INT,
        @liLINK_BUDG         INT,
        @liMaxOrders         INT,
        @liLINK_BUDG_EMPTY   INT,
        @ltPERIODIC          TINYINT,
        @ltIS_SVOD           TINYINT,
        @lvcCODE_TASK        VARCHAR(50),

        @lvcBUDG_NAME        VARCHAR(250),
        @lvcDEP_NAME         VARCHAR(254),		
        
        @lvcCODE_ATR         VARCHAR(50),
        @lvcSTR_VAL          VARCHAR(1000),
        @lcYear              CHAR(4),
		  @ltRO_NEW_REPORT	  TINYINT,
        
        @tADEMode            TINYINT,
		@iLinkTree			int

SET @tADEMode = 0		  
IF OBJECT_ID('tempdb..#tabImportOptions') IS NOT NULL
BEGIN
   SELECT @tADEMode = [VALUE_INT]
   FROM #tabImportOptions
   WHERE [OPTION] = 'ADE_MODE'
END

DECLARE @tabDepartments TABLE ([LINK] INT,
                               [NAME] VARCHAR(8000))                              

EXEC dbo.[RA_ERRORS_LOG_CLEAR] @@PROCID

SELECT @liLINK_FORM     = [A].[LINK_FORM],
       @lcCODE_FORM     = [B].[CODE],
   	 @lvcKBP          = [A].[KBP],
       @lvcVB           = [A].[VB],
       @ldBEGIN_DATE    = [A].[DT],
       @ltPERIOD_TYPE   = ISNULL([A].[PRD],0),
       @lvcATRIBUTS     = [A].[ATRIBUTS],
       @ltPERIOD_NUMBER = 0
FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
JOIN dbo.[REPORT_FORMS]              [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

if @iRepeatRequest > 0 -- повторный запуск
begin
	if object_id('tempdb..#tmpImportWithReport') is NOT NULL
	begin
		select @lvcKBP = D.budg, @lvcVB = B.outcode, @iLinkTree = T.Link
		from dbo.report_svod_tree T join dbo.departments D on T.link_report_org = D.link
			left join dbo.kl_budg_type B on T.link_report_budg = B.link
			join #tmpImportWithReport T1 on T1.link = T.link
	end
end

SELECT @lvcVB = ISNULL(@lvcVB,''),
       @lbIsEmptyVB = 0

SELECT @lbIsEmptyVB = 1
FROM dbo.[RA_VIEW_EMPTY_BUDGET] 
WHERE @lvcVB IN ([OUTCODE],'','--')      

SELECT @lvcBUDG_NAME = [NAME]
FROM dbo.[KL_BUDG_TYPE]
WHERE [OUTCODE] = @lvcVB

INSERT @tabDepartments([LINK],[NAME])
SELECT [LINK], [NAME]
FROM dbo.[DEPARTMENTS]
WHERE [BUDG] = @lvcKBP

IF @@ROWCOUNT < 1
BEGIN  
   EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-1 -- Организации с таким кодом бюджетополучателя не существует
   RETURN -1
END

SELECT @lvcCODE_TASK = [CODE_TASK]
FROM dbo.[USER_INFO]

IF @lvcVB = ''
BEGIN
/*
   select * into ##aaa from @tabDepartments   
   select * from ##aaa
*/   
   
   DELETE @tabDepartments
   WHERE [LINK] NOT IN (SELECT [LINK_ORG]
                        FROM dbo.[RO_SVOD_TREE]
                        WHERE [LINK_REPORT_BUDG] = 0)

                                                            
   IF NOT EXISTS(SELECT *  
                 FROM @tabDepartments)
   BEGIN  
		EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
		SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))	
			
		IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
		BEGIN
		INSERT #t_RepeatRequest ([RES],[bExcess])
			VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 3)
		END

      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-2 -- Отсутствует код бюджета
      RETURN -1
   END
END   
   
SELECT @ltPERIODIC  = [PERIODIC]
FROM dbo.[REPORT_FORMS] 
WHERE [LINK_FORM] = @liLINK_FORM

IF (@bWEB = 1 AND @tMode=0) OR (ISNULL(IS_MEMBER('Свод-КС - ограниченый доступ к организациям'),0)=1)
BEGIN
   DELETE @tabDepartments
   WHERE [LINK] NOT IN (SELECT [LINK_ORG]
                        FROM dbo.[RO_SVOD_ORG_ACCESS]())
                        
   IF NOT EXISTS(SELECT *
                 FROM @tabDepartments)
   BEGIN
		EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
		SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))	
			
		IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
		BEGIN
		INSERT #t_RepeatRequest ([RES],[bExcess])
			VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 3)
		END

      SELECT @lvcTmp = 'Нет доступа к организации: ' + [NAME]
      FROM dbo.[DEPARTMENTS]
      WHERE [LINK] = @liLINK_ORGANIZATION
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-3,@lvcTmp -- Нет доступа к организации
      RETURN -1    
   END
END

IF @tMode = 1 OR
   @lbIsEmptyVB = 0 OR -- ISNULL(@lvcVB,'') NOT IN ('','--')
   EXISTS(SELECT *
          FROM dbo.[RO_SVOD_TREE] [A]
          JOIN dbo.[KL_BUDG_TYPE] [B] ON [B].[LINK] = [A].[LINK_REPORT_BUDG]
          JOIN @tabDepartments    [C] ON [C].[LINK] = [A].[LINK_REPORT_ORG]
          WHERE [B].[OUTCODE] = @lvcVB)
BEGIN
/*
   SELECT @liLINK_BUDG = [LINK], 
          @lvcResult = 'Бюджет : ' + [NAME]
   FROM dbo.[KL_BUDG_TYPE]
   WHERE [OUTCODE] = @lvcVB  
*/
   IF @tMode =1 
   BEGIN
      SELECT @liLINK_BUDG = [LINK], 
             @lvcResult = 'Бюджет : ' + [NAME]
      FROM dbo.[KL_BUDG_TYPE]
      WHERE [OUTCODE] = @lvcVB
   END
   ELSE BEGIN
      SELECT @liLINK_BUDG = [B].[LINK], 
             @lvcResult = 'Бюджет : ' + [B].[NAME]
      FROM dbo.[RO_SVOD_TREE] [A]
      JOIN dbo.[KL_BUDG_TYPE] [B] ON [B].[LINK] = [A].[LINK_REPORT_BUDG]
      JOIN @tabDepartments    [C] ON [C].[LINK] = [A].[LINK_REPORT_ORG]
      WHERE [B].[OUTCODE] = @lvcVB
   END

   IF @liLINK_BUDG IS NULL
   BEGIN
		EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
		SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))	
			
		IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
		BEGIN
		INSERT #t_RepeatRequest ([RES],[bExcess])
			VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 3)
		END

      SET @lvcTmp = 'Нет бюджета с кодом ' + RTRIM(@lvcVB)
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-4,@lvcTmp -- Не найден бюджет с таким кодом
      RETURN -1 
   END

   IF @tMode = 1
   BEGIN
      SELECT @liLINK_ORGANIZATION = [LINK]
      FROM dbo.[DEPARTMENTS]
      WHERE [BUDG] = @lvcKBP
   END
   ELSE BEGIN
      SELECT @liLINK_ORGANIZATION = [C].[LINK]
      FROM dbo.[RO_SVOD_TREE] [A]
      JOIN dbo.[KL_BUDG_TYPE] [B] ON [B].[LINK] = [A].[LINK_REPORT_BUDG]
      JOIN @tabDepartments    [C] ON [C].[LINK] = [A].[LINK_REPORT_ORG]
      WHERE [B].[OUTCODE] = @lvcVB    
   END

   IF @liLINK_ORGANIZATION IS NULL
   BEGIN
      IF (SELECT COUNT(*)
          FROM @tabDepartments)>1
      BEGIN         
         SET @lvcTmp = 'Организации '         
         SELECT @lvcTmp = @lvcTmp + [NAME] + ','
         FROM @tabDepartments
         SET @lvcTmp = ISNULL(LEFT(@lvcTmp,LEN(@lvcTmp)-1),'') + ' не стоят '
         
--         exec xa_watchi '@lvcTmp',@lvcTmp 
      END
      ELSE BEGIN
         SET @lvcTmp = 'Организация ' 
         SELECT @lvcTmp = @lvcTmp + [NAME]
         FROM @tabDepartments
         SET @lvcTmp = @lvcTmp + ' не стоит '
      END
      
      --exec xa_watchi '@lvcTmp',@lvcTmp 
      --exec xa_watchs
      
      SET @lvcTmp = @lvcTmp + 'в бюджете ' + RTRIM(@lvcBUDG_NAME)
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-5,@lvcTmp -- Организация(и) не стоит(ят) в данном бюджете.
      RETURN -1
   END
END
ELSE BEGIN -- @lbIsEmptyVB = 1
   SELECT TOP 1 @liLINK_ORGANIZATION = [LINK]
   FROM @tabDepartments
   ORDER BY [LINK]

   SET @liLINK_BUDG = dbo.[RO_SVOD_BUDG_FOR_ORG](@liLINK_ORGANIZATION)
   
   IF @liLINK_BUDG IS NULL AND 
      NOT EXISTS(SELECT * 
                 FROM dbo.[RO_SVOD_TREE] 
                 WHERE [LINK_ORG] IS NOT NULL AND 
                       [LINK_ORG] = @liLINK_ORGANIZATION)
   BEGIN -- добавляем организацию в неопределенный бюджет
      SELECT @liLINK_BUDG_EMPTY = [LINK] 
      FROM dbo.[RO_SVOD_TREE]
      WHERE [LINK_SELF] = NULL AND 
            [CODE_BUDG] = '--'
            
      SELECT @liLINK_BUDG = [LINK]
      FROM [KL_BUDG_TYPE]
      WHERE [CODE] = '--'
      
      IF @liLINK_BUDG_EMPTY IS NULL
      BEGIN
         SET @liMaxOrders = ISNULL((SELECT  MAX([ORDERS])
                                    FROM dbo.[REPORT_SVOD_TREE] 
                                    WHERE [LINK_SELF] IS NULL), 0) + 1
         
         EXEC dbo.[RO_SAVE_SVOD_TREE] @liLINK_BUDG_EMPTY OUTPUT, 
                                     NULL, 
                                     @liLINK_BUDG, 
                                     0, 
                                     NULL, 
                                     @liMaxOrders
      END

      IF NOT EXISTS(SELECT * 
                    FROM dbo.[RO_SVOD_TREE]
                    WHERE [LINK_ORG] = @liLINK_ORGANIZATION AND 
                          [LINK_SELF] = @liLINK_BUDG_EMPTY)
      BEGIN
         SET @liMaxOrders = ISNULL((SELECT MAX([ORDERS]) 
                                    FROM dbo.[REPORT_SVOD_TREE]
                                    WHERE [LINK_SELF] = @liLINK_BUDG_EMPTY), 0) + 1
         EXEC dbo.[RO_SAVE_SVOD_TREE] NULL, 
                                     @liLINK_ORGANIZATION, 
                                     NULL, 
                                     1, 
                                     @liLINK_BUDG_EMPTY, 
                                     @liMaxOrders
      END

      SELECT @lvcResult = 'Бюджет : ' + [NAME]
      FROM dbo.[KL_BUDG_TYPE]
      WHERE [CODE] = '--'
   END
   ELSE BEGIN
      SELECT @lvcResult = 'Бюджет : ' + [NAME]
      FROM dbo.[KL_BUDG_TYPE]
      WHERE [LINK] = @liLINK_BUDG
   END
END

SELECT @lvcResult = ISNULL(RTRIM(@lvcResult),'Бюджет : <отсутствует>') + CHAR(13) + 'Организация : ' + [NAME]
FROM dbo.[DEPARTMENTS]
WHERE [LINK] = @liLINK_ORGANIZATION

-- определяем Свод это или Отчет:
SELECT @ltIS_SVOD = CASE
                       WHEN EXISTS(SELECT * 
                                   FROM dbo.[RO_SVOD_TREE] 
                                   WHERE [LINK_REPORT_BUDG] = @liLINK_BUDG         AND 
                                         [LINK_REPORT_ORG]  = @liLINK_ORGANIZATION AND 
                                         [CHILDRENS]        = 1) -- нет потомков
                       THEN 0
                       ELSE 1
                    END,
       @lvcResult = 'Код формы : ' + RTRIM(@lcCODE_FORM) + CHAR(13) + @lvcResult

IF @ltPERIOD_TYPE = 0
BEGIN
  SELECT @ldBEGIN_DATE = @ldBEGIN_DATE - 1,
         @ltPERIOD_TYPE = CASE 
                             WHEN MONTH(@ldBEGIN_DATE) = 12 AND @ltPERIODIC & 1 = 1 THEN 1
                             WHEN (MONTH(@ldBEGIN_DATE) = 3 OR MONTH(@ldBEGIN_DATE) = 6 OR MONTH(@ldBEGIN_DATE) = 9 OR MONTH(@ldBEGIN_DATE) = 12) and @ltPERIODIC & 2 = 2 THEN 2
                             WHEN @ltPERIODIC & 4 = 4 THEN 4 
                             ELSE 0 
                          END
  IF @ltPERIOD_TYPE = 0
  BEGIN
    SET @ltPERIOD_TYPE = CASE 
                            WHEN @ltPERIODIC & 1 = 1 THEN 1 
                            WHEN @ltPERIODIC & 2 = 2 THEN 2 
                            ELSE 4 
                         END
  END
  SET @ltPERIOD_NUMBER = CASE @ltPERIOD_TYPE 
                            WHEN 1 THEN 1 
                            WHEN 2 then CONVERT(INT, MONTH(@ldBEGIN_DATE) - 1)/3 + 1 
                            ELSE MONTH(@ldBEGIN_DATE) 
                         END
END
ELSE BEGIN
   IF @ltPERIOD_NUMBER = 0
   BEGIN
      SELECT @ldBEGIN_DATE    = @ldBEGIN_DATE - 1,
             @ltPERIOD_NUMBER = CASE @ltPERIOD_TYPE
                                   WHEN 1 THEN 1
                                   WHEN 2 THEN CONVERT(INT, MONTH(@ldBEGIN_DATE) - 1)/3 + 1
                                   ELSE MONTH(@ldBEGIN_DATE)
                                END
   END
   ELSE BEGIN
      IF @ltPERIOD_TYPE=1 
      BEGIN
         SET  @ldBEGIN_DATE = convert(char(4),year(@ldBEGIN_DATE)) + '1231'
      END
      ELSE BEGIN
         IF @ltPERIOD_TYPE=2
         BEGIN
            SELECT @ldBEGIN_DATE = CONVERT(CHAR(4),YEAR(@ldBEGIN_DATE)) + RIGHT('00' + LTRIM(RTRIM(CONVERT(CHAR(2),(@ltPERIOD_NUMBER-1)*3+1))),2) + '01',
                   @ldBEGIN_DATE = DATEADD(MONTH, 3, @ldBEGIN_DATE)
         END
         ELSE BEGIN
            SELECT @ldBEGIN_DATE = CONVERT(CHAR(4),year(@ldBEGIN_DATE)) + RIGHT('00' + LTRIM(RTRIM(CONVERT(CHAR(2),@ltPERIOD_NUMBER))),2) + '01',
                   @ldBEGIN_DATE = DATEADD(MONTH, 1, @ldBEGIN_DATE)
         END
         SET  @ldBEGIN_DATE = DATEADD(DAY, -1, @ldBEGIN_DATE)
      END
   END
END

SELECT @lcYear = CONVERT(CHAR(4),YEAR(@ldBEGIN_DATE)),
       @lvcResult = @lvcResult + CHAR(13) + 'Отчетная дата : ' + (CASE @ltPERIOD_TYPE 
                                                WHEN 1 THEN  + @lcYear + ' год'
                                                WHEN 2 THEN CONVERT(CHAR(1),@ltPERIOD_NUMBER) + ' квартал ' + @lcYear + ' года'
                                                WHEN 4 THEN CONVERT(CHAR(2),@ltPERIOD_NUMBER) + ' месяц ' + @lcYear + ' года'
                                             END)

IF ((@iRepeatRequest > 0 and object_id('tempdb..#tmpImportWithReport') is NULL ) OR (@tADEMode = 1)) -- перезаписать существующие отчеты
BEGIN
	IF EXISTS(SELECT * 
             FROM dbo.[REPORT_SAVED_FORMS]
             WHERE [LINK_FORM]         = @liLINK_FORM         AND 
                   [BEGIN_DATE]        = @ldBEGIN_DATE        AND
                   [PERIOD_TYPE]       = @ltPERIOD_TYPE       AND
                   [PERIOD_NUMBER]     = @ltPERIOD_NUMBER     AND 
                   [LINK_ORGANIZATION] = @liLINK_ORGANIZATION AND
--                   [IsSvod]            = @ltIS_SVOD           AND 
                   isnull([LINK_TYPE_SVOD],0)    = isnull(@liLINK_BUDG,0)         AND 
                   dbo.[RN_GET_ATR_VAL]([LINK_SAVED_FORM],   
                                        0,
                                        1) = @lvcAtributs     AND
                   dbo.[RO_ACCESS_SAVED_FORM]([LINK_SAVED_FORM], @bWEB) & 2 = 0)
   BEGIN -- нет прав удалить отчеты
      INSERT #t_RepeatRequest([RES],[bExcess])
      VALUES ('Результат', 1)

      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-6 -- Нет прав для удаления старого отчета.
      RETURN -1 --Ошибка сохранения заголовка формы
   END
   IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
   BEGIN
      INSERT #t_RepeatRequest([RES], bExcess)
      VALUES ('Результат', 0)
   END

   UPDATE dbo.[REPORT_SAVED_FORMS]
   SET [DEL] = 1,
         modify_date  = getdate() 
   WHERE [LINK_FORM]         = @liLINK_FORM         AND 
         [BEGIN_DATE]        = @ldBEGIN_DATE        AND 
         [PERIOD_TYPE]       = @ltPERIOD_TYPE       AND 
         [PERIOD_NUMBER]     = @ltPERIOD_NUMBER     AND 
         [LINK_ORGANIZATION] = @liLINK_ORGANIZATION AND 
--         [IsSvod]            = @ltIS_SVOD           AND 
         isnull([LINK_TYPE_SVOD],0)    = isnull(@liLINK_BUDG,0)         AND 
         dbo.[RN_GET_ATR_VAL]([LINK_SAVED_FORM],   
                              0,
                              1) = @lvcAtributs     AND   
         dbo.[RO_ACCESS_SAVED_FORM]([LINK_SAVED_FORM],@bWEB) & 2 > 0
         
   update SO
   set sid = SUSER_SID(),
         hostname = HOST_NAME(),
         date = GETDATE()
   from report_saved_form_owner SO
            JOIN report_saved_forms RSF ON SO.[LSF] = rsf.[Link_Saved_Form] 
   WHERE RSF.[LINK_FORM]         = @liLINK_FORM         AND 
         RSF.[BEGIN_DATE]        = @ldBEGIN_DATE        AND 
         RSF.[PERIOD_TYPE]       = @ltPERIOD_TYPE       AND 
         RSF.[PERIOD_NUMBER]     = @ltPERIOD_NUMBER     AND 
         RSF.[LINK_ORGANIZATION] = @liLINK_ORGANIZATION AND 
--         [IsSvod]            = @ltIS_SVOD           AND 
         isnull(RSF.[LINK_TYPE_SVOD],0)    = isnull(@liLINK_BUDG,0)         AND 
         dbo.[RN_GET_ATR_VAL](RSF.[LINK_SAVED_FORM],   
                              0,
                              1) = @lvcAtributs     AND   
         dbo.[RO_ACCESS_SAVED_FORM](RSF.[LINK_SAVED_FORM],@bWEB) & 2 > 0


   insert report_saved_form_owner (LSF, sid, hostname, date)
   SELECT RSF.link_saved_form, SUSER_SID(), HOST_NAME(),GETDATE()
   from report_saved_forms RSF 
            left join report_saved_form_owner SO ON SO.[LSF] = rsf.[Link_Saved_Form] 
   WHERE RSF.[LINK_FORM]         = @liLINK_FORM         AND 
         RSF.[BEGIN_DATE]        = @ldBEGIN_DATE        AND 
         RSF.[PERIOD_TYPE]       = @ltPERIOD_TYPE       AND 
         RSF.[PERIOD_NUMBER]     = @ltPERIOD_NUMBER     AND 
         RSF.[LINK_ORGANIZATION] = @liLINK_ORGANIZATION AND 
--         [IsSvod]            = @ltIS_SVOD           AND 
         isnull(RSF.[LINK_TYPE_SVOD],0)    = isnull(@liLINK_BUDG,0)         AND 
         dbo.[RN_GET_ATR_VAL](RSF.[LINK_SAVED_FORM],   
                              0,
                              1) = @lvcAtributs     AND   
         dbo.[RO_ACCESS_SAVED_FORM](RSF.[LINK_SAVED_FORM],@bWEB) & 2 > 0
            AND SO.[LSF] IS NULL 
         

/*
   DELETE dbo.[REPORT_SAVED_FORMS]
   WHERE [LINK_FORM]         = @liLINK_FORM         AND 
         [BEGIN_DATE]        = @ldBEGIN_DATE        AND 
         [PERIOD_TYPE]       = @ltPERIOD_TYPE       AND 
         [PERIOD_NUMBER]     = @ltPERIOD_NUMBER     AND 
         [LINK_ORGANIZATION] = @liLINK_ORGANIZATION AND 
--         [IsSvod]            = @ltIS_SVOD           AND 
         isnull([LINK_TYPE_SVOD],0)    = isnull(@liLINK_BUDG,0)         AND 
         dbo.[RN_GET_ATR_VAL]([LINK_SAVED_FORM],   
                              0,
                              1) = @lvcAtributs     AND   
         dbo.[RO_ACCESS_SAVED_FORM]([LINK_SAVED_FORM],@bWEB) & 2 > 0*/
END

if dbo.ReportObjectAccessByLink(@liLINK_FORM) & 2  = 0 
begin
      EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-12 -- Нет прав для создания старого отчета.
      RETURN -1 --Ошибка сохранения заголовка формы
end

IF ISNULL(@lvcATRIBUTS,'') = '' 
BEGIN
   SET @lvcATRIBUTS=dbo.[RN_GET_ATR_VAL](0,@liLINK_FORM,1)
END

SELECT @iLSF = dbo.[RA_GET_LAST_LSF](@liLINK_FORM,
				                         @ltPERIOD_NUMBER,
						                   @ltPERIOD_TYPE,
								             @ldBEGIN_DATE,
											    @liLINK_ORGANIZATION, 
												 @liLINK_BUDG,                       
												 @lvcATRIBUTS),
		 @ltRO_NEW_REPORT = dbo.[RO_NEW_REPORT](0,  
															 @liLINK_FORM,
															 @ltPERIOD_NUMBER,
															 @ltPERIOD_TYPE,
															 @ldBEGIN_DATE,
															 @liLINK_ORGANIZATION, 
															 @liLINK_BUDG, 
															 @ltIS_SVOD, 
															 @lvcATRIBUTS) 

/*
Режимы ADE
0  - выкл.
1 - Если отчет существует, перезаписываем его
2 - Если отчет существует, создаем новую версию отчета
3 - Если отчет существует, не принимаем новый отчет
*/
IF @iLSF IS NOT NULL AND 
	(@tIsAppend = 1 OR (@ltRO_NEW_REPORT=1 AND @tADEMode = 0) OR (@tADEMode = 3)) AND
   @tMode = 0 
BEGIN
	SET @ltIsRO = 0

	SELECT @ltIsRO = [IsRO]
	FROM dbo.[REPORT_SAVED_FORMS]
	WHERE [LINK_SAVED_FORM] = @iLSF
  
	IF @ltIsRO = 4
	BEGIN
		EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-9 -- Отчет имеет статус "Утвержден". Измените статус отчета перед импортом.
      RETURN -1 
	END

	IF @ltIsRO = 2
	BEGIN
		EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-10 -- Отчет имеет статус "Включен в свод". Измените статус отчета перед импортом.
      RETURN -1 
	END
   
   IF @tIsAppend = 0 
   BEGIN
      IF @tADEMode = 3
      BEGIN
         EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-11 -- Отчет уже существует. Перезапись запрещена.
         RETURN -1
      END
      ELSE BEGIN
         IF @ltRO_NEW_REPORT = 1 BEGIN
            EXEC dbo.[RA_SAVE_IMPORT_SAVED_FORMS] @iLINK_SAVED_FORM OUTPUT
            SET @lvcLINK_SAVED_FORM = RTRIM(CAST(@iLINK_SAVED_FORM AS VARCHAR(50)))
                   
            IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
            BEGIN
               INSERT #t_RepeatRequest ([RES],[bExcess])
               VALUES ('Результат @ ' + @lvcLINK_SAVED_FORM + ' # Да @ -' + @lvcLINK_SAVED_FORM + ' # Нет', 2)
            END
            EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-7 -- Запрос на перезапись старого отчета.
            RETURN -1
         END
      END
   END
END
ELSE BEGIN
	SET @iLSF = NULL
END

IF @iLSF IS NULL
BEGIN  

   EXEC @liError = dbo.[I_REPORT_SAVE_FORM]  @iLSF OUTPUT,
                                             @liLINK_FORM,
                                             DEFAULT,
                                             @ldBEGIN_DATE,
                                             @ltPERIOD_TYPE,
                                             @ltPERIOD_NUMBER,
                                             @liLINK_ORGANIZATION,
                                             @ltIS_SVOD,
                                             DEFAULT,
                                             DEFAULT,
                                             DEFAULT,
                                             DEFAULT,
                                             DEFAULT,
                                             DEFAULT,
                                             DEFAULT,
                                             @liLINK_BUDG,
                                             DEFAULT,
                                             1,
                                             @tMode,
                                             @lvcATRIBUTS
               
   IF @liError <> 0
   BEGIN
      IF @liError = 11000
      BEGIN
         EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-6 -- Нет прав для удаления старого отчета.
      END 
      ELSE BEGIN
         EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,-8 -- Ошибка в dbo.[I_REPORT_SAVE_FORM].
      END

      RETURN -1 
   END  
  
   DECLARE curAtributs CURSOR LOCAL FORWARD_ONLY STATIC FOR
      SELECT [CODE_ATR],
             [STR_VAL] 
      FROM dbo.[REPORT_IMPORT_ATRIBUTS]
      WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

   OPEN curAtributs

   FETCH NEXT
   FROM curAtributs
   INTO @lvcCODE_ATR,
        @lvcSTR_VAL

   WHILE @@FETCH_STATUS=0
   BEGIN
      EXEC dbo.[RN_SAVE_ATRIBUT_VALUES] @iLSF,
                                        @lvcCODE_ATR,
                                        @lvcSTR_VAL
      FETCH NEXT
      FROM curAtributs
      INTO @lvcCODE_ATR,
           @lvcSTR_VAL
   END

   CLOSE curAtributs
   DEALLOCATE curAtributs
END

SELECT @lvcResult = 'Успешный импорт формы:' + CHAR(13) + @lvcResult + CHAR(13) + 
                    'Атрибуты : ' + RTRIM(LTRIM([ATR])) + CHAR(13) + 
                    'Версия : ' + CAST([VERSION] AS CHAR(4))
FROM dbo.[REPORT_SAVED_FORMS]
WHERE [LINK_SAVED_FORM] = @iLSF

EXEC dbo.[RA_ERRORS_LOG_ADD] @@PROCID,0,@lvcResult -- Статусная строка успешного импорта.
delete dbo.Buffer
where sid = suser_sid() and ID = 'IMPORT_REPORT_WITH_TREE'
RETURN 0

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_SAVE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

xd_context 'RA_IMPORT_FORM_SAVE'
RA_IMPORT_FORM_SAVE

sp_help ra_update_errors

exec ra_update_errors 'RA_IMPORT_FORM_SAVE',0,'Успешный импорт'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE',-1,'Организации с таким кодом бюджетополучателя не существует'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -2 , 'Отсутствует код бюджета'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -3 , 'Нет доступа к организации'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -4 , 'Не найден бюджет с таким кодом'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -5 , 'Организация(и) не стоит(ят) в данном бюджете'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -6 , 'Нет прав для удаления старого отчета'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -7 , 'Отчет уже существует! Перезаписать существующий отчет на импортируемый (ДАННЫЕ СУЩЕСТВУЮЩЕГО ОТЧЕТА ПОТЕРЯЮТСЯ) '
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -8 , 'Ошибка в dbo.[I_REPORT_SAVE_FORM]',1

exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -9 , 'Отчет имеет статус "Утвержден". Измените статус отчета перед импортом.'
exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -10 , 'Отчет имеет статус "Включен в свод". Измените статус отчета перед импортом.'

exec ra_update_errors 'RA_IMPORT_FORM_SAVE', -11 , 'Отчет уже существует. Перезапись запрещена.'


sp_helptext ra_update_errors 

-- -9 -- Отчет имеет статус "Утвержден". Измените статус отчета перед импортом.
-- -10 -- Отчет имеет статус "Включен в свод". Измените статус отчета перед импортом.



select * from report_errors
declare @i int
exec @i=ra_update_errors 'RA_IMPORT_FORM_SAVE', -5 , 'Организация(и) не стоит(ят) в данном бюджете'
select @i
*/


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[X_DOCUMENT_GET_MAX_NUMBER]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_DOCUMENT_GET_MAX_NUMBER]

GO





/*
© Кейсистемс (Keysystems), 2005
*/





CREATE         PROCEDURE dbo.X_DOCUMENT_GET_MAX_NUMBER
	@varKSchrDocument 	varchar(30),
	@varKSMaxNum		varchar(30) output,
	@intDepLink		int = NULL
AS
Declare @varKSYear datetime,
	@varKSdbegin datetime,
	@varKSdend datetime,
	@intNastrDocNumZB	TINYINT,	-- 1 - Сквозная нумерация документа
	@intNastrDocNumPeriod	TINYINT,	-- 1 - Нумерация документа с начала года, 2 с начала месяца
	@intF0504501_NUM_NO_RKO	TINYINT

-- Проверка настроек -- 
SET @intNastrDocNumZB = ISNULL (dbo.SA_GET_OPTION_BY_CODE ('XK_NASTR_DOC_NUMBER_ZB'), 0)
IF @intNastrDocNumZB = 1 AND EXISTS (SELECT * FROM dbo.S_OBJECTS SO, dbo.DOC_NASTR NASTR 
					WHERE SO.CODE = @varKSchrDocument
						AND NASTR.LINK = SO.LINK
						AND NASTR.AN_ORG = 0)
	SET @intDepLink = NULL

SET @intNastrDocNumPeriod = ISNULL (dbo.SA_GET_OPTION_BY_CODE ('XK_NASTR_DOC_NUM_PERIOD'), 1)
IF @intNastrDocNumPeriod = 0 
	select @intNastrDocNumPeriod = Isnull(AN_PERIOD,1)
	from dbo.XD_DOC_NASTR 
	where CODE = @varKSchrDocument 

Select @varKSYear = WORKDATE from dbo.USER_INFO
if @intNastrDocNumPeriod = 2
	Select @varKSdbegin = dbo.DateBeginOfMonth(@varKSYear), @varKSdend = dbo.DateEndOfMonth(@varKSYear)
else
	Select @varKSdbegin = dbo.DateBeginOfYear(@varKSYear), @varKSdend = dbo.DateEndOfYear(@varKSYear)

IF @varKSchrDocument = 'DOCUMENTS_RKO' OR @varKSchrDocument = 'DOCUMENTS_F0504501'
BEGIN
	SET @intF0504501_NUM_NO_RKO = ISNULL (dbo.XK_GET_NASTR_INT ('NASTR_F317_NUM_NO_KO'), 0)

	SET @varKSMaxNum = (SELECT right(MAX(REPLACE(SPACE(25-len(RTRIM(number)))+RTRIM(number), ' ','0')), 25)
	FROM dbo.G_PROV G
	INNER JOIN dbo.S_OBJECTS SO ON (G.OBJECT = SO.LINK)
	WHERE (SO.CODE = 'DOCUMENTS_RKO' OR SO.CODE = 'DOCUMENTS_F0504501')
		AND (@intF0504501_NUM_NO_RKO = 1 AND SO.CODE = @varKSchrDocument
			OR @intF0504501_NUM_NO_RKO = 0)
		AND (@intDepLink IS NULL OR G.DEP = @intDepLink)
		AND G.[DATE] BETWEEN @varKSdbegin AND @varKSdend
		AND dbo.CheckIsNumeric (NUMBER) = 1
		AND NUMBER not LIKE '%.%')
END
ELSE
   SET @varKSMaxNum = (SELECT right(MAX(REPLACE(SPACE(30-len(RTRIM(number)))+RTRIM(number), ' ','0')), 30)
	FROM dbo.G_PROV G INNER JOIN dbo.s_objects so ON G.OBJECT = so.link
	WHERE so.CODE = @varKSchrDocument AND G.DATE BETWEEN @varKSdbegin AND @varKSdend 
		AND (@intDepLink IS NULL OR G.DEP = @intDepLink)
		AND dbo.CheckIsNumeric (NUMBER) = 1
		AND NUMBER not LIKE '%.%')
		

SET @varKSMaxNum = ISNULL(@varKSMaxNum, REPLICATE('0', 30))


GO


GRANT EXECUTE ON dbo.[X_DOCUMENT_GET_MAX_NUMBER] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_SAVE_DOC_TABLE_MZ_NDS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_SAVE_DOC_TABLE_MZ_NDS]

GO
CREATE PROCEDURE dbo.BK_SAVE_DOC_TABLE_MZ_NDS
	@intLINK_ROW	INT = NULL OUTPUT,
	@varKSpLINK_UP	INT,
	@varKSpORDERS	INT,

	@INV_TYPE VARCHAR(30),
	@INV 	INT,
	@PRICE NUMERIC(19, 4) = 0,
	@AKCIZ NUMERIC (19, 4) = 0,
	@NUM_TD VARCHAR(30) = '',
	@QTY NUMERIC(19, 4) = 0,
	@SUMMA NUMERIC(19, 4) = 0,
	@STAVKA_NDS NUMERIC(5, 2) = 0,
	@SUMMA_NDS NUMERIC(19, 4) = 0,
	@SUMMA_ALL NUMERIC(19, 4) = 0,
	@EKR INT = NULL,
	@FIN_SOURCE CHAR(1)= '',
	@NO_NDS	TINYINT = 0,
	@COUNTRY_LINK	INT = NULL,
	@TNDS_LINK	INT = NULL

AS
BEGIN
	DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,

		@intOBJ_TABLE INT

	SELECT @intOBJ_TABLE = LINK FROM dbo.S_OBJECTS WITH (NOLOCK) WHERE CODE = 'DOC_TABLE_MZ_NDS'

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	EXECUTE @varKSERROR = dbo.X_UPDATE_OUT_TABLE_ROW @intLINK_ROW OUTPUT, @varKSpLINK_UP,
			@intOBJ_TABLE, @varKSpORDERS

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	EXECUTE @varKSERROR = dbo.XK_UPDATE_OUT_TABLE_MZ_SUMMA
			@intLINK_ROW,
			@INV_TYPE, @INV,
			@PRICE, @AKCIZ, @NUM_TD, @QTY, @SUMMA, @STAVKA_NDS,
			@SUMMA_NDS, @SUMMA_ALL, @EKR, @FIN_SOURCE, @NO_NDS,
			@COUNTRY_LINK,
			@TNDS_LINK

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0
END


GO


GRANT EXECUTE ON dbo.[BK_SAVE_DOC_TABLE_MZ_NDS] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
SET ANSI_WARNINGS OFF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_ANALITICS_OBTAIN_COL_VAL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_ANALITICS_OBTAIN_COL_VAL]
GO

CREATE PROCEDURE [dbo].[RT_ANALITICS_OBTAIN_COL_VAL]
	@nPeriod_Type int,
	@nPeriod_Date_Start datetime,
	@nPeriod_Number_Start int,
	@nPeriod_Date_Stop datetime,
	@nPeriod_Number_Stop int,
	@nStatus int,
	@nFormVersion int = null
AS

-- нормализация даты
declare @cDate varchar(8)
set @cDate = cast(year(@nPeriod_Date_Start) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Start) end as varchar),2) + '01'
set @nPeriod_Date_Start =  dateadd(dd,-1,dateadd(mm,1,@cDate))
set @cDate = cast(year(@nPeriod_Date_Stop) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Stop) end as varchar),2) + '01'
set @nPeriod_Date_Stop =  dateadd(dd,-1,dateadd(mm,1,@cDate))

--
--declare @cDate varchar(8)
--set @cDate = cast(year(@nPeriod_Date_Start) as varchar(4)) + right('00'+cast(month(@nPeriod_Date_Start) as varchar),2) + '01'
--set @nPeriod_Date_Start =  dateadd(dd,-1,dateadd(mm,1,@cDate))
--set @cDate = cast(year(@nPeriod_Date_Stop) as varchar(4)) + right('00'+cast(month(@nPeriod_Date_Stop) as varchar),2) + '01'
--set @nPeriod_Date_Stop =  dateadd(dd,-1,dateadd(mm,1,@cDate))

print @nPeriod_Date_Start
print @nPeriod_Date_Stop
---------------------------------------------------------------
-- создаём таблицу с периодами
exec DropTempTable '#analitics_period'
create table #analitics_period (nn int, period_type int, period_number int, period_date datetime)
create table #analitics_period_copy (period_type int, period_number int, period_date datetime)

declare @cSqlStr varchar(8000)

set @cSqlStr = ''
if exists(select * from #analitics_periods)
	set @cSqlStr = 'insert into #analitics_period (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_periods'
else 
	set @cSqlStr = 'exec dbo.RT_ANALITICS_GET_PERIODS '+convert(varchar,@nPeriod_Date_Start,112)+', '+convert(varchar,@nPeriod_Date_Stop,112)+', '+cast(@nPeriod_Type as varchar)+', ''#analitics_period'''

execute(@cSqlStr)
--select * from #analitics_period

--  необходимо получить таблицу, примерно следующего вида:
--  period_type, period_date, period_number, link_form, link_table, link_col
--  линки формы будут получены по коду формы, по имени или ордеру таблицы, по имени или ордеру колонки

create table #analitics_period_links (period_type int, period_date datetime, period_number int, link_form int, link_table int, link_col int, link_col_base int, col_type tinyint, keyflag tinyint, tab_type int, dictionary varchar(254), field varchar(254))

declare	@this_link_form int,
		@this_link_table int,
		@nthis_table_order int,
		@cthis_table_name varchar(254),
		@this_link_col int,
		@nthis_col_order int,
		@cthis_col_name varchar(254),
		@this_link_col_type tinyint,
		@new_link_form int,
		@new_link_table int,
		@new_link_col int,
		@new_link_col_type tinyint,
		@cCodeForm varchar(50),
		@lpt int,
		@lpn int,
		@lpd datetime

while exists(select * from #analitics_links) begin -- цикл по отмеченным формам (потому что может быть отмечена более чем одна форма)
	select top 1 @this_link_form = link_f, @this_link_table = link_t, @this_link_col = link_c, @this_link_col_type = col_type from #analitics_links
	-- заполняем таблицу #analitics_period_links. каждому периоду будет соответствовать акуальная в том периоде форма
	select @nthis_table_order = orders, @cthis_table_name = [name] from dbo.report_tables where link_table = @this_link_table
	select @nthis_col_order = orders, @cthis_col_name = [name] from dbo.report_coloumns where link_col = @this_link_col

	-- код формы
	select @cCodeForm = rf0.code from dbo.report_forms as rf0 (nolock) where rf0.link_form = @this_link_form -- линк формы ищется по коду формы вне зависимости от даты

	-- цикл по периодам 
	insert into #analitics_period_copy (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_period

	while exists(select * from #analitics_period_copy) begin
		select top 1 @lpt = period_type, @lpn = period_number, @lpd = period_date from #analitics_period_copy
		-- линк формы в новом периоде
		set @new_link_form = null
		select top 1 @new_link_form = rsf.link_form
		--select rsf.period_type, rsf.begin_date, rsf.period_number, rsf.link_form
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = (select top 1 rf.link_form from dbo.report_forms as rf (nolock) where rf.code = (@cCodeForm) and rsf.begin_date between rf.start_date and isnull(rf.end_date,'20501231')) -- линк формы ищется по коду формы
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd

		-- линк таблицы в новом периоде
		set @new_link_table = null
		select top 1 @new_link_table = rt0.link_table
		from
			dbo.report_tables as rt0 (nolock)
		where
			rt0.link_form = @new_link_form
			and rt0.[name] = @cthis_table_name
		-- если не нашли таблицу по имени, ищем её по ордеру
		if @new_link_table is null begin
			select top 1 @new_link_table = rt0.link_table
			from
				dbo.report_tables as rt0 (nolock)
			where
				rt0.link_form = @new_link_form
				and rt0.orders = @nthis_table_order
		end

		-- линк колонки в новом периоде
		-- существует вероятность, что наименования колонок будут дублироваться в пределах одной формы. Поэтому если дублирование имеет место, переходим к поиску колонки по ордеру
		if (select count(*) from dbo.report_coloumns as rc0 (nolock) where rc0.link_table = @new_link_table and rtrim(rc0.[name]) = rtrim(@cthis_col_name)) = 1 begin
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
				rc0.link_table = @new_link_table
				and rc0.[name] = @cthis_col_name
			--print 'теперь линк колонки =' + cast(@new_link_col as varchar)
		end
		else begin
			-- если не нашли колонку, или колонок с этим именем оказалось несколько, ищем её по ордеру проверяя тип
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
			rc0.link_table = @new_link_table
			and rc0.orders = @nthis_col_order
			and rc0.col_type = @this_link_col_type
		end
		insert into #analitics_period_links (period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, col_type, keyflag, tab_type)
		select distinct
			rsf.period_type,
			rsf.begin_date,
			rsf.period_number,
			rsf.link_form,
			[link_table] = @new_link_table,
			[link_col] = @new_link_col,
			link_col_base = @this_link_col,
			col_type = @this_link_col_type,
			null,
			(select val_type from dbo.report_tables where link_table = @new_link_table)
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = @new_link_form
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd
		
		delete from #analitics_period_copy where period_type = @lpt and period_number = @lpn and period_date = @lpd
	end
	delete from #analitics_links where link_c = @this_link_col
end
update #analitics_period_links
set keyflag = (case when apl.link_col = (select a.link_code_col from dbo.report_tables as a where a.link_table = apl.link_table) then 1 else 0 end)
from #analitics_period_links as apl

--select * from #analitics_period_links
----
declare @period_type int,
		@period_date datetime,
		@period_number int,
		@link_form int,
		@link_table int,
		@lnLink_Col int,
		@lnLink_Col_another int,
		@lcDictionary varchar(8000),
		@lcField varchar(8000),
		@lcCol varchar(254),
		@lcFieldStr varchar (254),
		@lcColStr varchar (254),
		@lnPos int,
		@lnPosField int,
		@nFound int,
		@cStrExec varchar(8000)

declare the_cursor cursor local dynamic for
select period_type, period_date, period_number, link_form, link_table, link_col, dictionary, field
from #analitics_period_links where col_type = 1
for update of dictionary, field

open the_cursor

fetch next from the_cursor INTO @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col, @lcDictionary, @lcField

while @@fetch_status = 0 begin
	------------------------------------------------------------------------------------------------------------------------------------------------
	select @lcCol = 'COL'+rtrim(cast(orders as varchar)) from dbo.report_coloumns where link_col = @lnLink_Col

	set	@lcDictionary = ''
	set	@lcField = ''
	set	@lcFieldStr = ''
	set	@lcColStr = ''
	set @nFound = 0

	if exists(select * from dbo.report_coloumns as rc where rc.link_col = @lnLink_Col and len(isnull(rc.Dictionary,'')) > 0) begin -- справочник для колонки есть
		select @lcColStr = rtrim(Dictionary_Columns_List),@lcFieldStr = rtrim(Dictionary_Fields_List),@lcDictionary = dictionary from dbo.report_coloumns where link_col = @lnLink_Col -- справочник нашли
		while len(@lcColStr)>0 and @nFound = 0 begin
			set @lnPos = charindex(',',@lcColStr)
			if @lnPos = 0 begin -- запятая в @lcColStr не найдена
				if charindex(@lcCol,@lcColStr) > 0 begin -- если колонка найдена, берём имя поля справочника
					set @lcField = ltrim(rtrim(@lcFieldStr))
					set @nFound = 1
				end
				else begin
					set @lcColStr = ''
				end
			end
			else begin -- запятая в @lcColStr найдена
				if charindex(@lcCol,substring(@lcColStr,1,@lnPos-1)) > 0 begin -- если колонка найдена, берём имя поля справочника
					set @lnPosField = charindex(',',@lcFieldStr)
					if @lnPosField > 0 begin
						set @lcField = substring(@lcFieldStr,1,@lnPosField-1)
						set @nFound = 1
					end
					else begin
						set @lcField = ''
					end
				end
				set @lcColStr = substring(@lcColStr,@lnPos+1,len(@lcColStr)-@lnPos)
				set @lcFieldStr = substring(@lcFieldStr,charindex(',',@lcFieldStr)+1,len(@lcFieldStr)-charindex(',',@lcFieldStr))
			end
		end
	end
	else begin -- справочника для колонки нет. будем пытаться найти хоть какой-нибудь справочник в котором упоминается искомая колонка @lcCol
		set @lnLink_Col_another = null
		select top 1 @lnLink_Col_another = rc.link_col, @lcColStr = rtrim(rc.Dictionary_Columns_List),@lcFieldStr = rtrim(rc.Dictionary_Fields_List),@lcDictionary = rc.dictionary
		from dbo.report_coloumns as rc
		where charindex(@lcCol, rc.Dictionary_Columns_List) > 0
			and rc.link_table = (select rc1.link_table from dbo.report_coloumns as rc1 where rc1.link_col = @lnLink_Col)
		if @lnLink_Col_another is not null begin -- нашли
			while len(@lcColStr)>0 and @nFound = 0 begin
				set @lnPos = charindex(',',@lcColStr)
				if @lnPos = 0 begin -- запятая в @lcColStr не найдена
					if charindex(@lcCol,@lcColStr) > 0 begin -- если колонка найдена, берём имя поля справочника
						set @lcField = ltrim(rtrim(@lcFieldStr))
						set @nFound = 1
					end
					else begin
						set @lcColStr = ''
					end
				end
				else begin -- запятая в @lcColStr найдена
					if charindex(@lcCol,substring(@lcColStr,1,@lnPos-1)) > 0 begin -- если колонка найдена, берём имя поля справочника
						set @lnPosField = charindex(',',@lcFieldStr)
						if @lnPosField > 0 begin
							set @lcField = substring(@lcFieldStr,1,@lnPosField-1)
							set @nFound = 1
						end
						else begin
							set @lcField = ''
						end
					end
					set @lcColStr = substring(@lcColStr,@lnPos+1,len(@lcColStr)-@lnPos)
					set @lcFieldStr = substring(@lcFieldStr,charindex(',',@lcFieldStr)+1,len(@lcFieldStr)-charindex(',',@lcFieldStr))
				end
			end
		end
	end
	update #analitics_period_links
	set Dictionary = @lcDictionary, 
         Field = @lcField
	where current of the_cursor
	
	fetch next from the_cursor into @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col, @lcDictionary, @lcField
	------------------------------------------------------------------------------------------------------------------------------------------------
end

close the_cursor
deallocate the_cursor
--
--select * from #analitics_period_links
--return
--
exec DropTempTable '#tree_link'
create table #tree_link (link int)
insert into #tree_link (link)
select t.link
from dbo.report_svod_tree t
where t.link in (
    select cast((left(ltrim(f.[value]),charindex('@@',ltrim(f.[value]))-1)) as int) from #analitics_filters as f where f.code = 'DEP' or f.code = 'NAME_DEP'
)
-- Создание таблицы сохранённых форм
exec DropTempTable '#sf'
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)
-- предполагается, что к этому моменту существует таблица #analitics_filters, содержащая среди прочего код аналитического признака CODE и текстовое значение VALUE
insert into #sf
select distinct
	rsf.link_saved_form,
	rsf.link_form,
	rsf.period_type,
	rsf.period_number,
	rsf.begin_date,
	rsf.link_organization,
	[btype] = (select [name] from dbo.BI_DICTION_BUDG_TYPE (nolock) where link = rsf.link_type_svod),
rsf.link_type_svod
from report_saved_forms as rsf (nolock)
	inner join (select distinct period_type, period_date, period_number, link_form from #analitics_period_links) as apl
	on
		apl.link_form = rsf.link_form
		and apl.period_date = rsf.begin_date
      AND rsf.del = 0
		and apl.period_type = rsf.period_type
		and apl.period_number = rsf.period_number
    left join dbo.report_svod_tree as rst
    on 
        rsf.link_organization = rst.link_report_org
        and rsf.link_type_svod = rst.link_report_budg
where
	rsf.version =
		case
			when @nFormVersion < 0 or @nFormVersion is null
			then(
				select top 1 version
	 			from 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 lrsf.atr_code = rsf.atr_code
				order by  version desc
			)
			else @nFormVersion
		end		
	and rsf.IsSvod in (
case when @nStatus&0x10 = 0x10 then 1 else -1 end,
		case when @nStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (
case when @nStatus&0x01 = 0x01 then 0 else -1 end,
		case when @nStatus&0x02 = 0x02 then 1 else -1 end,
		case when @nStatus&0x04 = 0x04 then 2 else -1 end,
		case when @nStatus&0x08 = 0x08 then 3 else -1 end,
		case when @nStatus&0x40 = 0x40 then 4 else -1 end,
		case when @nStatus&0x80 = 0x80 then 5 else -1 end)
--	and (
--		rsf.link_organization in (select link from #organizationen_link)
--		or not exists(select * from #analitics_filters where code = 'DEP' or code = 'NAME_DEP' or code = 'BUDG')
--	)
    and (
        rst.link in (select link from #tree_link)
        or not exists(select * from #tree_link)
    )
    and (
		rsf.link_type_svod in (
			select b.link from dbo.kl_budg_type as b (nolock) where b.code in (select rtrim(f.[value]) from #analitics_filters as f where f.code = 'BUD_TYPE')
		)
		or not exists(select * from #analitics_filters where code = 'BUD_TYPE')
	)
	and (
		rsf.link_saved_form in (
			select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = f.code and (rav.str_val = f.[value] /*or rav.int_val = cast(f.[value] as int)*/) where f.type = 2
--			case
--				when exists(select * from #analitics_filters where [type] = 2 and code in (select rav.code_atr from dbo.report_atribut_values as rav where rav.link_saved_form = rsf.link_saved_form))
--				then (select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = f.code and (rav.str_val = f.[value] /*or rav.int_val = cast(f.[value] as int)*/) where f.type = 2)
--				else 0
--			end
		)
		or not exists(select * from #analitics_filters where [type] = 2 and code in (select rav.code_atr from dbo.report_atribut_values as rav where rav.link_saved_form = rsf.link_saved_form))
	)
-- 
--select distinct link_sf from #sf
--return
--

exec DropTempTable '#report_static_table'
create table #report_static_table (link_sf int, link_table int, link_col int, link_row int, str_val varchar(8000), summa numeric(20,4), del tinyint)
create index ixx_stat on #report_static_table (Link_sf, link_table, Link_col, link_row)

exec DropTempTable '#report_dynamic_table'
create table #report_dynamic_table (link_sf int, link_table int, link_col int, code_row varchar(50), str_val varchar(8000), summa numeric(20,4), del tinyint)
create index ixx_din on #report_dynamic_table (Link_sf, link_table, Link_col, code_row)

exec DropTempTable '#return_table'
create table #return_table (nn int identity(1,1), code varchar(254), [name] varchar(254), from_spr tinyint default(0))

exec DropTempTable '#data'
create table #data (code varchar(254))
create index ixx_data on #data (code)

declare the_cursor cursor local static for
select period_type, period_date, period_number, link_form, link_table, link_col, dictionary, field from #analitics_period_links where col_type = 1

open the_cursor
fetch next from the_cursor INTO @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col, @lcDictionary, @lcField
while @@fetch_status = 0 begin
	set @cStrExec = ''
	if len(isnull(@lcDictionary,''))>0  -- у колонки есть справочнег
		and exists(select * from syscolumns where id = object_id ('dbo.'+ltrim(rtrim(@lcDictionary))) and name = 'name') begin -- у справочнега есть поле NAME
			-- создадим копию справочника с урезанными значениями
			exec DropTempTable '#tmp_spr'
			create table #tmp_spr (code varchar(254), [name] varchar(254))
			set @cStrExec = 'insert into #tmp_spr (code,[name]) select left(rtrim(ltrim(A.'+ltrim(rtrim(@lcField))+')),254) as code, left(rtrim(ltrim(A.name)),254) as name from dbo.'+ltrim(rtrim(@lcDictionary))+' as A'
			execute(@cStrExec)

         if (select link_code_col from dbo.report_tables where link_table = @link_table) = @lnLink_Col -- ключевой столбец
         begin
            insert #data
            select distinct rd.code_row from
             #sf as sf join dbo.report_dinamics_all as rd 
            		     
                      on sf.link_sf = rd.link_sf
                     inner join #analitics_period_links as apl
                        on apl.period_type = @period_type
                        and apl.period_date = @period_date
                        and apl.period_number =@period_number
                        and apl.link_form = @link_form
                        and apl.link_table = @link_table
                        and sf.period_type = apl.period_type
                        and sf.period_number = apl.period_number
                        and sf.begin_date = apl.period_date
                        and sf.link_form = apl.link_form
                        and rd.link_col = apl.link_col
         end
         else begin
            insert #data
            select distinct left(rd.str_val,254) from
               #sf as sf join dbo.report_dinamics_all as rd 
            		     
                      on sf.link_sf = rd.link_sf
                     inner join #analitics_period_links as apl
                        on apl.period_type = @period_type
                        and apl.period_date = @period_date
                        and apl.period_number =@period_number
                        and apl.link_form = @link_form
                        and apl.link_table = @link_table
                        and apl.link_col = @lnLink_Col
                        and sf.period_type = apl.period_type
                        and sf.period_number = apl.period_number
                        and sf.begin_date = apl.period_date
                        and sf.link_form = apl.link_form
                        and rd.link_col = apl.link_col
         end

         insert into #return_table (code,[name], from_spr) 
         select 
            coalesce(D.code, A.code,''),
            (case 
               when (select distinct count(B.name) from #tmp_spr as B where B.code =  case when max(D.code) is NULL then max(A.code)  else max(D.code)  end) = 1 
               then (select B.name from #tmp_spr as B where B.code = case when max(D.code) is NULL then max(A.code)  else max(D.code)  end) 
               else ''
            end) as name,
            case when max(D.code) is NULL then 1 when max(A.code) is NULL then 2 else 3 end
         from #data D  
            full join #tmp_spr A on A.code = D.code
            left join #return_table R on R.code = A.Code
         where R.code is NULL and len(coalesce(D.code, A.code,''))>0
          group by coalesce(D.code, A.code,'') 

         truncate table #data


	--		execute(@cStrExec)
			exec DropTempTable '#tmp_spr'
		end
--		else begin -- поля NAME у справочнега, увы, нет
--			set @cStrExec = 'insert into #return_table (code,[name]) select '+ltrim(rtrim(@lcField))+' as code, null as name from dbo.'+ltrim(rtrim(@lcDictionary))+' where '+ltrim(rtrim(@lcField))+' not in (select code from #return_table) and len(isnull('+ltrim(rtrim(@lcField))+',''''))>0 '
--			execute(@cStrExec)
--		end
--	end
	else begin -- справочника нет... чё делатьqm драть данные прямиком из отчётов...
		-- если форма 14-я то report_static_table не заполняем
		if not exists (select * from dbo.report_forms where left(ltrim(code),7) = '0503074' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = @lnLink_Col))) begin
			set @cStrExec = '
	insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa, del)
	select sf.link_sf, apl.link_table, rsu.link_col, rsu.link_row, rs.str_val, rsu.summa, 0
	from #sf as sf
		inner join dbo.report_summa_All as rsu 
			on sf.link_sf = rsu.link_saved_form
		left join dbo.report_string_all as rs 
			on sf.link_sf = rs.link_saved_form
			and rs.link_col = rsu.link_col
			and rs.link_row = rsu.link_row
	-- 	inner join dbo.report_formula as rf (nolock)
	-- 		on rsu.link_col = rf.link_col
	-- 		and rsu.link_row = rf.link_row
		inner join #analitics_period_links as apl
			on apl.period_type = '+cast(@period_type as varchar)+'
			and apl.period_date = '''+cast(@period_date as varchar)+'''
			and apl.period_number = '+cast(@period_number as varchar)+'
			and apl.link_form = '+cast(@link_form as varchar)+'
			and apl.link_table = '+cast(@link_table as varchar)+'
			--and apl.link_col = '+cast(@lnLink_Col as varchar)+'
			
			and	sf.period_type = apl.period_type
			and sf.period_number = apl.period_number
			and sf.begin_date = apl.period_date
			and sf.link_form = apl.link_form
			and apl.link_col = rsu.link_col
	'
			execute(@cStrExec)
			set @cStrExec = '
	insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa, del)
	select sf.link_sf, apl.link_table, rf.link_col, rf.link_row, rf.formula, 0.0, 0
	from #sf as sf
		inner join #report_static_table as rst
			on sf.link_sf = rst.link_sf
		inner join #analitics_period_links as apl
			on apl.period_type = '+cast(@period_type as varchar)+'
			and apl.period_date = '''+cast(@period_date as varchar)+'''
			and apl.period_number = '+cast(@period_number as varchar)+'
			and apl.link_form = '+cast(@link_form as varchar)+'
			and apl.link_table = '+cast(@link_table as varchar)+'
			--and apl.link_col = '+cast(@lnLink_Col as varchar)+'

			and sf.period_type = apl.period_type
			and sf.period_number = apl.period_number
			and sf.begin_date = apl.period_date
			and sf.link_form = apl.link_form
			and apl.link_col <> rst.link_col
		inner join dbo.report_formula as rf (nolock)
			on rf.link_col = apl.link_col
			and rf.link_row = rst.link_row
	'
			execute(@cStrExec)
			set @cStrExec = '
	insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa, del)
	select sf.link_sf, apl.link_table, rs.link_col, rs.link_row, rs.str_val, 0.0, 0
	from #sf as sf
		inner join #report_static_table as rst
			on sf.link_sf = rst.link_sf
		inner join #analitics_period_links as apl
			on apl.period_type = '+cast(@period_type as varchar)+'
			and apl.period_date = '''+cast(@period_date as varchar)+'''
			and apl.period_number = '+cast(@period_number as varchar)+'
			and apl.link_form = '+cast(@link_form as varchar)+'
			and apl.link_table = '+cast(@link_table as varchar)+'
			--and apl.link_col = '+cast(@lnLink_Col as varchar)+'

			and sf.period_type = apl.period_type
			and sf.period_number = apl.period_number
			and sf.begin_date = apl.period_date
			and sf.link_form = apl.link_form
			and apl.link_col <> rst.link_col
		inner join dbo.report_string as rs (nolock)
			on rs.link_saved_form = rst.link_sf
            and rs.link_col = apl.link_col
			and rs.link_row = rst.link_row
	'
			execute(@cStrExec)

--			set @cStrExec = 'create nonclustered index iixy on #report_static_table (link_col,link_row)'
--			execute(@cStrExec)
		end

		set @cStrExec = 'insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa, del)
select sf.link_sf, apl.link_table, rd.link_col, rd.code_row, rd.str_val, rd.float_val, 0
from #sf as sf
	inner join dbo.report_dinamics_all as rd 
		on sf.link_sf = rd.link_sf
	inner join #analitics_period_links as apl
		on apl.period_type = '+cast(@period_type as varchar)+'
		and apl.period_date = '''+cast(@period_date as varchar)+'''
		and apl.period_number = '+cast(@period_number as varchar)+'
		and apl.link_form = '+cast(@link_form as varchar)+'
		and apl.link_table = '+cast(@link_table as varchar)+'
		--and apl.link_col = '+cast(@lnLink_Col as varchar)+'

		and sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rd.link_col = apl.link_col
'
		execute(@cStrExec)
		set @cStrExec = '
insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa, del)
select distinct sf.link_sf, apl.link_table, rt.link_code_col, rdt.code_row, rdt.code_row, 0.0, 0
from #sf as sf
	inner join #report_dynamic_table as rdt
		on sf.link_sf = rdt.link_sf
	inner join dbo.report_coloumns as rc (nolock)
		on rc.link_col = rdt.link_col
	inner join dbo.report_tables as rt (nolock)
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on apl.period_type = '+cast(@period_type as varchar)+'
		and apl.period_date = '''+cast(@period_date as varchar)+'''
		and apl.period_number = '+cast(@period_number as varchar)+'
		and apl.link_form = '+cast(@link_form as varchar)+'
		and apl.link_table = '+cast(@link_table as varchar)+'
		--and apl.link_col = '+cast(@lnLink_Col as varchar)+'

		and sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rt.link_code_col = apl.link_col
'
		execute(@cStrExec)

		set @cStrExec = '
insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa, del)
select distinct sf.link_sf, apl.link_table, rf.link_col, rdt.code_row, rf.formula, 0.0, 0
from #sf as sf
	inner join #report_dynamic_table as rdt
		on sf.link_sf = rdt.link_sf
	inner join dbo.report_coloumns as rc
		on rc.link_col = rdt.link_col
	inner join dbo.report_tables as rt
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on apl.period_type = '+cast(@period_type as varchar)+'
		and apl.period_date = '''+cast(@period_date as varchar)+'''
		and apl.period_number = '+cast(@period_number as varchar)+'
		and apl.link_form = '+cast(@link_form as varchar)+'
		and apl.link_table = '+cast(@link_table as varchar)+'
		--and apl.link_col = '+cast(@lnLink_Col as varchar)+'

		and sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join dbo.report_formula as rf
		on rf.link_col = apl.link_col
		and exists (select * from dbo.report_forms where left(code,7) = ''0503074'' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = rf.link_col and orders = 1)))
		and rf.link_row = [dbo].[RT_BIND14](rt.link_table, rdt.code_row)

'
		execute(@cStrExec)

		--create nonclustered index iiixy on #report_dynamic_table (code_row)

		insert into #return_table (code,[name])
		select distinct left(ltrim(rst.str_val),254) as code, null as [name]
		from #sf as sf
		inner join #report_static_table as rst
			on sf.link_sf = rst.link_sf
		where sf.period_type = @period_type	
		and sf.begin_date = @period_date
		and sf.period_number = @period_number
		and sf.link_form = @link_form
		and rst.link_col = @lnLink_Col
		and rst.str_val not in (select code from #return_table)
		and len(isnull(rst.str_val,''))>0

		insert into #return_table (code,[name])
		select distinct left(ltrim(dbo.RT_BOK14(rdt.str_val)),254) as code, null as [name]
		from #sf as sf
		inner join #report_dynamic_table as rdt
			on sf.link_sf = rdt.link_sf
		where sf.period_type = @period_type	
		and sf.begin_date = @period_date
		and sf.period_number = @period_number
		and sf.link_form = @link_form
		and rdt.link_col = @lnLink_Col
		and rdt.str_val not in (select code from #return_table)
		and len(isnull(rdt.str_val,''))>0

--		if not exists (select * from dbo.report_forms where left(ltrim(code),7) = '0503074' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = @lnLink_Col))) begin
--			set @cStrExec = 'drop index #report_static_table.iixy'
--			execute(@cStrExec)
--		end

		--drop index #report_dynamic_table.iiixy

	end
	fetch next from the_cursor into @period_type,@period_date,@period_number,@link_form,@link_table,@lnLink_Col, @lcDictionary, @lcField
end
close the_cursor
deallocate the_cursor

if col_length('tempdb..#tmpFilter', 'from_spr') is NULL
begin
   alter table #tmpFilter add from_spr tinyint default(0)
end

set @cStrExec = 'insert into #tmpFilter(link,checked,code,[name],from_spr)
select rt.nn as link, max((case when tmp.code is not null then 1 else 0 end)) as checked, REPLACE(rt.code,'''''''',''"''), REPLACE(right(ltrim(rt.[name]),254),'''''''',''''), from_spr
from #return_table as rt
left join #analitics_filters as tmp
	on rt.code = tmp.[value]
	and tmp.[type] = 1
group by rt.nn, REPLACE(rt.code,'''''''',''"''), REPLACE(right(ltrim(rt.[name]),254),'''''''',''''), from_spr'

EXECUTE(@cStrExec)

---------------------------------------------------------------------------------------------------------------------------------------------------------
exec DropTempTable '#tree_link'
exec DropTempTable '#report_static_table'
exec DropTempTable '#report_dynamic_table'
exec DropTempTable '#analitics_links'
exec DropTempTable '#analitics_period_links'
exec DropTempTable '#return_table'
exec DropTempTable '#sf'
exec DropTempTable '#analitics_period'
---------------------------------------------------------------------------------------------------------------------------------------------------------
GO
grant execute on [dbo].[RT_ANALITICS_OBTAIN_COL_VAL] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_PERC_CALC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_PERC_CALC]

GO

CREATE PROCEDURE [dbo].SA_N_PERC_CALC 
/*Расчет начисления процентом*/
@LINK_DOC INT
AS

DECLARE

	--ЗА КАКОЙ ПЕРИОД
	@DATE_DOC DATETIME,
	@PERIOD_BEG DATETIME,
	@PERIOD_END DATETIME,
	--ЧТО РАССЧИТЫВАТЬ
	@LINK_PAY INT,
	@IS_WAY_CALC TINYINT,
	--ПО КАКОМУ ИСТОЧНИКУ
	@LINK_SFIN INT,
	--ДРУГИЕ ОПЦИИ
	@ROUND_MODE TINYINT,
	@IS_LINK_SFIN_ONLY TINYINT,
	@IS_OLD_SUM TINYINT,
	@LINK_REGION_PAY INT,
	@LINK_NORTH_PAY INT,
	@LINK_DEP INT,
	@MIN_VAL NUMERIC(18,2)

--ИНИЦИАЛИЗАЦИЯ
SELECT 
	@DATE_DOC = DBO.DATEENDOFMONTH(S.DATE),
	@LINK_DEP = LINK_DEP,
	@LINK_PAY = LINK_PAY,
	@PERIOD_BEG = DATE1,
	@PERIOD_END = DATE2,
	@LINK_SFIN = ISNULL(LINK_KBK,-1),
	@ROUND_MODE = round_mode,
	@IS_LINK_SFIN_ONLY = BASE_KBK,
	@IS_OLD_SUM = isOLD_SUM,
	@IS_WAY_CALC = FLAG_WT,
	@LINK_REGION_PAY = LINK_PAY1,
	@LINK_NORTH_PAY = LINK_PAY2,
	@MIN_VAL = ISNULL(MIN_VAL,0)
FROM 
	dbo.SDOC S INNER JOIN dbo.SDOC_APER SD ON S.LINK = SD.LINK_UP
WHERE
	S.LINK = @LINK_DOC

UPDATE T
SET 
	T.DAYS_N = 0,
	T.HOURS_N = 0,
	T.DAYS = 0,
	T.HOURS = 0,
	T.REGSUM = 0,
	T.NORTHSUM = 0,
	T.SUMMA_BASE = 0,
	T.SUMMA_ALL = 0,
	T.SUMMA_OLD = 0,
	T.SUMMA = 0
FROM
	DBO.SDOC_APER_TABLE T 
WHERE
	T.LINK_UP = @LINK_DOC

--КОМУ РАССЧИТЫВАТЬ
CREATE TABLE #ISMIN (LINK_EMPL INT, LINK_SOVM INT, LINK_TW INT)
CREATE TABLE #SA_EMPLS_W (LINK_EMPL INT, LINK INT, LINK_TYPE INT)

INSERT INTO #SA_EMPLS_W (LINK_EMPL, LINK, LINK_TYPE)
SELECT LINK_EMPL, LINK, LINK_TYPE FORM FROM DBO.SA_EMPLS_W_FN(DEFAULT,@PERIOD_END,DEFAULT,@LINK_DEP)

IF @IS_WAY_CALC = 1
	INSERT INTO #ISMIN(LINK_EMPL, LINK_SOVM)
	SELECT DISTINCT T.LINK_EMPL, T.LINK_SOVM
	FROM DBO.SDOC_APER_TABLE T
	WHERE T.LINK_UP = @LINK_DOC
ELSE
	INSERT INTO #ISMIN(LINK_EMPL, LINK_SOVM)
	SELECT DISTINCT T.LINK_EMPL, T.LINK_SOVM
	FROM 
		DBO.SDOC_APER_TABLE T
		INNER JOIN #SA_EMPLS_W E ON T.LINK_EMPL = E.LINK_EMPL AND T.LINK_SOVM = E.LINK
		INNER JOIN DBO.TABEL_NASTR2 N2 ON N2.LINK = E.LINK_TYPE
	WHERE
		T.LINK_UP = @LINK_DOC
		AND
		N2.isMin = 1	
	

UPDATE T
SET 
	T.PERC = 0
FROM
	DBO.SDOC_APER_TABLE T 
WHERE
	T.LINK_UP = @LINK_DOC
	AND
	NOT EXISTS (SELECT * FROM #ISMIN M WHERE M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM)

--ПРОСТАВЛЯЕТСЯ ВРЕМЯ
CREATE TABLE #NORM_DH (LINK_EMPL INT, LINK_SOVM INT, [DAYS] NUMERIC(18,2), [HOURS] NUMERIC(18,2))
INSERT INTO #NORM_DH (LINK_EMPL, LINK_SOVM, [DAYS], [HOURS])
SELECT LINK_EMPL, LINK_SOVM, [DAYS], [HOURS] FROM DBO.SA_GET_EMPLS_NORM_DH (DEFAULT, DEFAULT, @PERIOD_BEG, @PERIOD_END)

CREATE TABLE #WORK_DH (LINK_EMPL INT, LINK_SOVM INT, [DAYS] NUMERIC(18,2), [HOURS] NUMERIC(18,2))
INSERT INTO #WORK_DH (LINK_EMPL, LINK_SOVM, [DAYS], [HOURS])
SELECT LINK_EMPL, LINK_SOVM, [DAYS], [HOURS] FROM DBO.SA_GET_EMPLS_WORK_DH (DEFAULT, DEFAULT, DEFAULT, @PERIOD_BEG, @PERIOD_END, DEFAULT)


UPDATE T
SET 
	T.DAYS_N = ISNULL(N.DAYS,0),
	T.HOURS_N = ISNULL(N.HOURS,0),
	T.DAYS = ISNULL(W.DAYS,0),
	T.HOURS = ISNULL(W.HOURS,0)
FROM
	DBO.SDOC_APER_TABLE T 
	INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
	LEFT JOIN #NORM_DH N ON N.LINK_EMPL = T.LINK_EMPL AND N.LINK_SOVM = T.LINK_SOVM
	LEFT JOIN #WORK_DH W ON W.LINK_EMPL = T.LINK_EMPL AND W.LINK_SOVM = T.LINK_SOVM
WHERE
	T.LINK_UP = @LINK_DOC

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

--ПРОСТАВЛЯЕТСЯ БАЗОВАЯ СУММА
CREATE TABLE #BASE_P (PAY_LINK INT)
INSERT INTO #BASE_P (PAY_LINK) SELECT PAY_LINK FROM dbo.group_pays(@LINK_PAY)

SELECT 
	T.LINK_EMPL, 
	T.LINK_SOVM, 
	LINK_SFIN = (CASE WHEN @LINK_SFIN > 0 THEN @LINK_SFIN ELSE J.LINK_VKR END),
	SUMMA_BASE = SUM(J.SUMMA)
INTO 
	#BASE
FROM 
	DBO.SDOC_APER_TABLE T
	INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_EMPL = T.LINK_EMPL AND T.LINK_SOVM = ISNULL(J.LINK_SOVM,0)
	INNER JOIN #BASE_P B ON J.LINK_PAYS = B.PAY_LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON J.LINK_DOC = R.LINK_UP
WHERE
	T.LINK_UP = @LINK_DOC
	AND
	(CASE WHEN ISNULL(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN J.PERIOD_BEGIN ELSE J.DATE_BEGIN END) >=@PERIOD_BEG 
	AND 
	(CASE WHEN ISNULL(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN J.PERIOD_END ELSE J.DATE_END END) <=@PERIOD_END
	AND
	(
		--ПРОПОРЦИОНАЛЬНО ИСТОЧНИКАМ
		@LINK_SFIN = -1 AND J.LINK_VKR = ISNULL(T.LINK_SFIN,@LINK_SFIN)
		OR --СУММА СОБИРАЕТСЯ ПО ВСЕМ ИСТОЧНИКАМ
		@LINK_SFIN > 0 AND @IS_LINK_SFIN_ONLY = 0
		OR --СУММА СОБИРАЕТСЯ ПО ЗАДАННОМУ ИСТОЧНИКУ
		@LINK_SFIN > 0 AND @IS_LINK_SFIN_ONLY = 1 AND J.LINK_VKR = @LINK_SFIN
	)
GROUP BY
	T.LINK_EMPL, T.LINK_SOVM, (CASE WHEN @LINK_SFIN > 0 THEN @LINK_SFIN ELSE J.LINK_VKR END)

-- РАССЧЕТ БАЗОВОЙ СУММЫ
DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

UPDATE T
SET 
	T.SUMMA_BASE = ISNULL(B.SUMMA_BASE,0),
	T.SUMMA_OLD = ISNULL(O.SUMMA,0) --НАЧИСЛЕННО
FROM
	DBO.SDOC_APER_TABLE T
	INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
	INNER JOIN #BASE B ON B.LINK_EMPL = T.LINK_EMPL AND B.LINK_SOVM = T.LINK_SOVM AND B.LINK_SFIN = T.LINK_SFIN
	LEFT JOIN 
	(
	SELECT 
		J.LINK_EMPL, 
		LINK_SOVM = ISNULL(J.LINK_SOVM,0),
		LINK_SFIN = (CASE WHEN @LINK_SFIN > 0 THEN @LINK_SFIN ELSE J.LINK_VKR END),
		SUMMA = SUM(J.SUMMA)
	FROM
		DBO.SDOC_APER_TABLE T1 
		INNER JOIN #ISMIN M ON M.LINK_EMPL = T1.LINK_EMPL AND M.LINK_SOVM = T1.LINK_SOVM
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_EMPL = T1.LINK_EMPL AND T1.LINK_SOVM = ISNULL(J.LINK_SOVM,0)
	WHERE
		T1.LINK_UP = @LINK_DOC
		AND
		@IS_OLD_SUM = 1
		AND
		J.LINK_PAYS = @LINK_PAY
		AND --Учитывается сумма, начисленная в этом периоде
		J.PERIOD_BEGIN >=@PERIOD_BEG AND J.PERIOD_END <=@PERIOD_END
		AND --начисленная за этот период
		J.DATE_BEGIN >=@PERIOD_BEG AND J.DATE_END <=@PERIOD_END		
		AND
		(
			--ПРОПОРЦИОНАЛЬНО ИСТОЧНИКАМ
			@LINK_SFIN = -1 AND J.LINK_VKR = ISNULL(T1.LINK_SFIN,@LINK_SFIN)
			OR --СУММА СОБИРАЕТСЯ ПО ВСЕМ ИСТОЧНИКАМ
			@LINK_SFIN > 0 AND @IS_LINK_SFIN_ONLY = 0
			OR --СУММА СОБИРАЕТСЯ ПО ЗАДАННОМУ ИСТОЧНИКУ
			@LINK_SFIN > 0 AND @IS_LINK_SFIN_ONLY = 1 AND J.LINK_VKR = @LINK_SFIN
		)
	GROUP BY
		J.LINK_EMPL, ISNULL(J.LINK_SOVM,0), (CASE WHEN @LINK_SFIN > 0 THEN @LINK_SFIN ELSE J.LINK_VKR END)
	) O ON O.LINK_EMPL = T.LINK_EMPL AND O.LINK_SOVM = T.LINK_SOVM AND O.LINK_SFIN = T.LINK_SFIN
WHERE
	T.LINK_UP = @LINK_DOC

------------ Для расчета доплаты до минимального предварительный расчет общей суммы для объединенных видов работ
--надбавку до МРОТ не распределяем по отрицательным суммам
SELECT T1.LINK_EMPL, T1.LINK_SOVM, LINK_TYPE = ISNULL(N2.LINK_SELF,E.LINK_TYPE), 
	U =  (CASE WHEN ISNULL(N2.LINK_SELF,0) > 0 THEN 1 ELSE 0 END),
	SUM(SUMMA_BASE) AS SUMMA_BASE
	--SUM(CASE WHEN SUMMA_BASE > 0 THEN SUMMA_BASE ELSE 0 END) AS SUMMA_BASE
INTO #TMP
FROM DBO.SDOC_APER_TABLE T1
	INNER JOIN #SA_EMPLS_W E ON T1.LINK_EMPL = E.link_empl AND T1.LINK_SOVM = E.LINK 
	INNER JOIN DBO.TABEL_NASTR2 N2 ON N2.LINK = E.LINK_TYPE AND isMin = 1
WHERE T1.LINK_UP = @LINK_DOC
GROUP BY T1.LINK_EMPL, T1.LINK_SOVM, ISNULL(N2.LINK_SELF,E.LINK_TYPE), (CASE WHEN ISNULL(N2.LINK_SELF,0) > 0 THEN 1 ELSE 0 END)

SELECT  
	A.LINK_EMPL, A.LINK_SOVM, LINK_EMPL1= B.LINK_EMPL, LINK_SOVM1 = B.LINK_SOVM
INTO
	#UNION_W	
FROM 
	#TMP A INNER JOIN #TMP B ON B.LINK_EMPL = A.LINK_EMPL AND B.LINK_TYPE = A.LINK_TYPE
WHERE 
	A.U = 0 AND B.U = 1
--
UPDATE T
SET [DAYS] = T2.[DAYS], 
	[HOURS] = T2.[HOURS],
	[DAYS_N] = T2.[DAYS_N], 
	[HOURS_N] = T2.[HOURS_N]
FROM 
	dbo.SDOC_APER_TABLE T INNER JOIN #UNION_W U ON T.LINK_EMPL = U.LINK_EMPL1 AND T.LINK_SOVM = U.LINK_SOVM1
	INNER JOIN dbo.SDOC_APER_TABLE T2 ON T.LINK_UP = T2.LINK_UP AND T2.LINK_EMPL = U.LINK_EMPL AND T2.LINK_SOVM = U.LINK_SOVM
WHERE T.LINK_UP = @LINK_DOC

UPDATE #TMP
SET U = 1 WHERE LINK_TYPE IN (SELECT LINK_TYPE FROM #TMP WHERE U = 1)

--
SELECT 
	A.LINK_EMPL, A.LINK_SOVM, SUMMA_BASE = ISNULL(B.SUMMA_BASE,A.SUMMA_BASE)
INTO #TMP2
FROM 
	#TMP A
	LEFT JOIN (SELECT LINK_EMPL, LINK_TYPE, SUM(SUMMA_BASE) AS SUMMA_BASE
			FROM #TMP 
			WHERE U = 1
			GROUP BY LINK_EMPL, LINK_TYPE) B ON A.LINK_EMPL = B.LINK_EMPL AND A.LINK_TYPE = B.LINK_TYPE

--РАСЧЕТ СУММЫ НАЧИСЛЕНИЯ
CREATE TABLE #EMPLS_W_LITE (LINK_EMPL INT,  LINK_SOVM INT, NUM_STAKE NUMERIC(5,2), SYST_PAY TINYINT)
INSERT INTO #EMPLS_W_LITE (LINK_EMPL,  LINK_SOVM, NUM_STAKE, SYST_PAY) 
SELECT LINK_EMPL,  LINK_SOVM, NUM_STAKE, SYST_PAY FROM DBO.SA_EMPLS_W_LITE_FN(DEFAULT,@PERIOD_END,DEFAULT)

--Расчет только доплаты до минимального
IF @IS_WAY_CALC = 2
	UPDATE T
	SET 
		T.PERC = 		
		CASE WHEN 
				@MIN_VAL --СУММА ПРОПОРЦИОНАЛЬНО ОТРАБОТАННОМУ ВРЕМЕНИ
				* ISNULL(E.NUM_STAKE,0)
				* (CASE WHEN ISNULL(T2.SUMMA_BASE,0) > 0 THEN ISNULL(T.SUMMA_BASE,0) / ISNULL(T2.SUMMA_BASE,0) ELSE 0 END)
				* CASE WHEN E.SYST_PAY = 1 THEN 
							(CASE WHEN ISNULL(T.DAYS_N,0) > 0 THEN 
								CONVERT(NUMERIC(18,6),ISNULL(T.DAYS,0)) / T.DAYS_N 
							ELSE 0 END)
						ELSE (CASE WHEN ISNULL(T.HOURS_N,0) > 0 THEN 
							DBO.NUM_TO_MINUTES(ISNULL(T.HOURS,0),@ISMINUTES) / DBO.NUM_TO_MINUTES(T.HOURS_N,@ISMINUTES) 
						ELSE 0 END) 
					END
				- ISNULL(T.SUMMA_BASE,0) > 0 AND ISNULL(T.SUMMA_BASE,0) >= 0
			THEN (
				@MIN_VAL--СУММА ПРОПОРЦИОНАЛЬНО ОТРАБОТАННОМУ ВРЕМЕНИ
				* ISNULL(E.NUM_STAKE,0)
				* (CASE WHEN ISNULL(T2.SUMMA_BASE,0) > 0 THEN ISNULL(T.SUMMA_BASE,0) / ISNULL(T2.SUMMA_BASE,0) ELSE 0 END)
				* CASE WHEN E.SYST_PAY = 1 THEN 
							(CASE WHEN ISNULL(T.DAYS_N,0) > 0 THEN 
								CONVERT(NUMERIC(18,6),ISNULL(T.DAYS,0)) / T.DAYS_N 
							ELSE 0 END)
					ELSE (CASE WHEN ISNULL(T.HOURS_N,0) > 0 THEN 
							DBO.NUM_TO_MINUTES(ISNULL(T.HOURS,0),@ISMINUTES) / DBO.NUM_TO_MINUTES(T.HOURS_N,@ISMINUTES) 
						ELSE 0 END) 
				END
				 - ISNULL(T.SUMMA_BASE,0)) / ISNULL(T.SUMMA_BASE,0) * 100
			ELSE 0
			END,

		T.SUMMA_ALL = 
		CASE WHEN 
				@MIN_VAL --СУММА ПРОПОРЦИОНАЛЬНО ОТРАБОТАННОМУ ВРЕМЕНИ
				* ISNULL(E.NUM_STAKE,0)
				* (CASE WHEN ISNULL(T2.SUMMA_BASE,0) > 0 THEN ISNULL(T.SUMMA_BASE,0) / ISNULL(T2.SUMMA_BASE,0) ELSE 0 END)
				* CASE WHEN E.SYST_PAY = 1 THEN 
							(CASE WHEN ISNULL(T.DAYS_N,0) > 0 THEN 
								CONVERT(NUMERIC(18,6),ISNULL(T.DAYS,0)) / T.DAYS_N 
							ELSE 0 END)
						ELSE (CASE WHEN ISNULL(T.HOURS_N,0) > 0 THEN 
							DBO.NUM_TO_MINUTES(ISNULL(T.HOURS,0),@ISMINUTES) / DBO.NUM_TO_MINUTES(T.HOURS_N,@ISMINUTES) 
						ELSE 0 END) 
					END
				- ISNULL(T.SUMMA_BASE,0) > 0
			THEN 
				@MIN_VAL --СУММА ПРОПОРЦИОНАЛЬНО ОТРАБОТАННОМУ ВРЕМЕНИ
				* ISNULL(E.NUM_STAKE,0)
				* (CASE WHEN ISNULL(T2.SUMMA_BASE,0) > 0 THEN ISNULL(T.SUMMA_BASE,0) / ISNULL(T2.SUMMA_BASE,0) ELSE 0 END)
				* CASE WHEN E.SYST_PAY = 1 THEN 
							(CASE WHEN ISNULL(T.DAYS_N,0) > 0 THEN 
								CONVERT(NUMERIC(18,6),ISNULL(T.DAYS,0)) / T.DAYS_N 
							ELSE 0 END)
						ELSE 
							(CASE WHEN ISNULL(T.HOURS_N,0) > 0 THEN 
								 DBO.NUM_TO_MINUTES(ISNULL(T.HOURS,0),@ISMINUTES) / DBO.NUM_TO_MINUTES(T.HOURS_N,@ISMINUTES) 
							ELSE 0 END) 
					END
					 - ISNULL(T.SUMMA_BASE,0)
		ELSE 0
		END
	FROM
		DBO.SDOC_APER_TABLE T
		INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
		INNER JOIN #EMPLS_W_LITE E ON E.LINK_EMPL = T.LINK_EMPL AND E.LINK_SOVM = T.LINK_SOVM
		INNER JOIN #TMP2 T2 ON T.LINK_EMPL = T2.LINK_EMPL AND T.LINK_SOVM = T2.LINK_SOVM 
	WHERE
		T.LINK_UP = @LINK_DOC AND @IS_WAY_CALC = 2
		AND ISNULL(T.SUMMA_BASE,0) > 0

--Расчёт для всех прочих
IF @IS_WAY_CALC IN (1,3,4)
	UPDATE T
	SET 
		T.PERC = 		
			CASE @IS_WAY_CALC
				WHEN 1 THEN
					ISNULL(T.PERC,0)
				WHEN 3 THEN
					DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,1) --Районный
				WHEN 4 THEN
					DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,2) --Северный
				ELSE 0								
			END,
		T.SUMMA_ALL =
			ISNULL(T.SUMMA_BASE,0)
			* 
			CASE @IS_WAY_CALC
				WHEN 1 THEN
					ISNULL(T.PERC,0) / 100
				WHEN 3 THEN
					DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,1) / 100 --Районный
				WHEN 4 THEN
					DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,2) / 100 --Северный
				ELSE 0								
			END	
	FROM
		DBO.SDOC_APER_TABLE T
	WHERE
		T.LINK_UP = @LINK_DOC AND @IS_WAY_CALC IN (1,3,4)

--ОКРУГЛЕНИЕ
DECLARE @PART NUMERIC(18,2)
SET @PART = (CASE @ROUND_MODE 
				WHEN 1 THEN 0 --Не округлять
				WHEN 2 THEN 0.10 --Округлять до 10 копеек				
				WHEN 3 THEN 1 --Округлять до 1 рубля
				WHEN 4 THEN 5 --Округлять до 5 рублей
				WHEN 5 THEN 10 --Округлять до 10 рублей
				WHEN 6 THEN 50 --Округлять до 50 рублей
				WHEN 7 THEN 100 --Округлять до 100 рублей
				WHEN 8 THEN 1000 --Округлять до 1000 рублей
				WHEN 9 THEN 10000 --Округлять до 10000 рублей
				ELSE 0 --Не округлять
			END)

--ОКОНЧАТЕЛЬНАЯ СУММА
UPDATE DBO.SDOC_APER_TABLE
SET
	SUMMA = dbo.SA_ROUND( ISNULL(SUMMA_ALL,0) - ISNULL(SUMMA_OLD,0), @PART, 1) -- НАЧИСЛИТЬ СЕЙЧАС	
WHERE
	LINK_UP = @LINK_DOC

--ОБНОВИТЬ ИТОГ ПО РАСЧЕТУ
UPDATE DBO.SDOC
	SET SUMMA_T = ISNULL((SELECT SUM(SUMMA) FROM DBO.SDOC_APER_TABLE T WHERE T.LINK_UP = @LINK_DOC),0)
WHERE
	LINK = @LINK_DOC

--ОПРЕДЕЛИТЬ РАЙОННЫЙ
IF @LINK_REGION_PAY > 0

	UPDATE T
	SET
		REGION = DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,1)
	FROM
		DBO.SDOC_APER_TABLE T
		INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
	WHERE
		LINK_UP = @LINK_DOC

--ОПРЕДЕЛИТЬ СЕВЕРНЫЙ
IF @LINK_NORTH_PAY > 0

	UPDATE T
	SET
		NORTH = DBO.SA_GET_REGION(T.LINK_EMPL,@PERIOD_END,2)
	FROM
		DBO.SDOC_APER_TABLE T
		INNER JOIN #ISMIN M ON M.LINK_EMPL = T.LINK_EMPL AND M.LINK_SOVM = T.LINK_SOVM
	WHERE
		LINK_UP = @LINK_DOC

--РАСЧЕТ СУММЫ РАЙОННОГО
IF EXISTS(SELECT PAY_LINK from dbo.group_pays(@LINK_REGION_PAY) WHERE PAY_LINK = @LINK_PAY)

	UPDATE DBO.SDOC_APER_TABLE
	SET
		REGSUM = ISNULL(SUMMA,0) * ISNULL(REGION,0) / 100
	WHERE
		LINK_UP = @LINK_DOC

--РАСЧЕТ СУММЫ СЕВЕРНОГО
IF EXISTS(SELECT PAY_LINK from dbo.group_pays(@LINK_NORTH_PAY) WHERE PAY_LINK = @LINK_PAY)

	UPDATE DBO.SDOC_APER_TABLE
	SET
		NORTHSUM = ISNULL(SUMMA,0) * ISNULL(NORTH,0) / 100
	WHERE
		LINK_UP = @LINK_DOC

--SELECT * FROM DBO.SDOC_APER_TABLE
--	WHERE
--		LINK_UP = @LINK_DOC

RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_N_PERC_CALC] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_373]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_373]
END
GO



/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_373]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

SET NOCOUNT ON

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
      UPDATE #FileExportReport
      SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
      WHERE TXT = 'ТБ=02'      

      IF EXISTS(SELECT * FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                     and orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                     AND LEFT([TXT],1) <>'#'
                     AND dbo.[RA_GETWORDNUM]([TXT],1, '|') >= '470')
      BEGIN
          -- данные есть, можно искать 470
		  UPDATE #FileExportReport
		  SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
		  WHERE orders = (SELECT MIN(orders)
						  FROM #FileExportReport
						 WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
										 AND dbo.[RA_GETWORDNUM]([TXT],1, '|') >= '470')
      END
      ELSE
		  BEGIN
			  -- данных нет, или есть данные только первой половины
			  UPDATE #FileExportReport
			  SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
			  WHERE orders = (SELECT MIN(orders)
							  FROM #FileExportReport
							 WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
											 AND [TXT]= '#')
                                    
		  END


      UPDATE  #FileExportReport
      SET TXT = '***' + SUBSTRING(TXT, CHARINDEX('|', TXT), 8000)
      WHERE TXT LIKE '%|88888|888|888|88888888|%'                                   

      UPDATE  #FileExportReport
      SET TXT = '***' + SUBSTRING(TXT, CHARINDEX('|', TXT), 8000)
      WHERE TXT LIKE '%|99999|999|999|99999999|%'                                   

      -- завяжемся на то что итоги есть всегда
      IF EXISTS(SELECT * FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                     AND dbo.[RA_GETWORDNUM]([TXT],3, '|') ='99999')
      BEGIN 
		  UPDATE #FileExportReport
		  SET [TXT] = '#<LN>#@<LN>ТБ=04<LN>#$<LN>' + [TXT]
		  WHERE orders = (SELECT MIN(orders)
						  FROM #FileExportReport
						 WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
								AND dbo.[RA_GETWORDNUM]([TXT],3, '|') >= '3' and dbo.[RA_GETWORDNUM]([TXT],3, '|') not in ('88888'))
      END
      ELSE
         BEGIN
            -- данных по пассиву нет
		  UPDATE #FileExportReport
		  SET [TXT] = '#<LN>#@<LN>ТБ=04<LN>#$<LN>' + [TXT]
			  WHERE orders = (SELECT MIN(orders)
							  FROM #FileExportReport
							 WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
											 AND [TXT]= '#')
        END       
      
      
      UPDATE  #FileExportReport
      SET TXT = REPLACE(REPLACE(REPLACE(TXT, '|8|88888|888|888|88888888|', '|*|*****|***|***|********|'),'|1|88888|888|888|88888888|', '|*|*****|***|***|********|') ,'|2|88888|888|888|88888888|', '|*|*****|***|***|********|')
      WHERE TXT LIKE '%|88888|888|888|88888888|%'                                   

      UPDATE  #FileExportReport
      SET TXT = REPLACE(REPLACE(REPLACE(TXT, '|9|99999|999|999|99999999|', '|*|*****|***|***|********|'), '|1|99999|999|999|99999999|', '|*|*****|***|***|********|'), '|2|99999|999|999|99999999|', '|*|*****|***|***|********|')
      WHERE TXT LIKE '%|99999|999|999|99999999|%'                                   

      UPDATE  #FileExportReport
      SET TXT = REPLACE(TXT, '|-|-|', '|***|********|')
      WHERE RTRIM(TXT) LIKE '%|-|-|%|-|'                                   
                            
END



GO
GRANT ALL ON dbo.RO_EXPORT_FORM_373 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.[KO_REP_GRAPH_KVALIF_EXAMEN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KO_REP_GRAPH_KVALIF_EXAMEN]

GO

CREATE PROCEDURE dbo.KO_REP_GRAPH_KVALIF_EXAMEN
	@nSel_Spr1 int
AS

declare @DEP_LINK int

IF @DEP_LINK IS NULL
	EXEC dbo.xd_whats_zb @DEP_LINK OUTPUT

CREATE TABLE #EMPL (LINK INT, FIO VARCHAR(254), POST_NAME VARCHAR(254))
INSERT INTO #EMPL(LINK, FIO, POST_NAME)
SELECT LINK, FIO, POST_NAME FROM dbo.KU_EMPL_PLACING WHERE DEP_LINK = @DEP_LINK

CREATE TABLE #MAIN_EMPL(MAIN_POST VARCHAR(254),MAIN_NAME VARCHAR(254))
INSERT INTO #MAIN_EMPL (MAIN_POST,MAIN_NAME)
SELECT TOP 1 POST_NAME, FACE_NAME
FROM dbo.DICTIONARY_OTV_FACE F	INNER JOIN dbo.KU_EMPL_PLACING E ON E.LINK = F.FACE_LINK
WHERE F.DEP_LINK  = @DEP_LINK	AND [NAME] = 'Руководитель'

SELECT
	ATG.EMPL_LINK	,
	[FIO]  = KUEP.FIO,
	[POST] = KUEP.POST_NAME,
	[DATA_EXAM] = ATG.DATE_TIME,
    [MAIN_POST]=MAIN_POST,
    [MAIN_NAME]=MAIN_NAME    
FROM
	dbo.ATTESTAT_GRAPHICS H
	INNER JOIN dbo.ATTESTAT_GRAPHICS_TABLE ATG ON H.LINK = ATG.ATT_GRAPH_LINK
	INNER JOIN #EMPL KUEP ON ATG.EMPL_LINK = KUEP.LINK
	LEFT JOIN #MAIN_EMPL NE ON 1=1
where
	H.DEP_LINK = @DEP_LINK


GO


GRANT EXECUTE ON dbo.[KO_REP_GRAPH_KVALIF_EXAMEN] TO PUBLIC

GO


--Расширенные свойства--


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_SPR_FORM_BUFFER]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_SPR_FORM_BUFFER]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011
   create table #IMPORT_FROM_BUFFER ( Code varchar(50), Dict varchar(50)

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_SPR_FORM_BUFFER]
AS
SET NOCOUNT ON

IF OBJECT_ID('tempdb..#IMPORT_FROM_BUFFER') IS NULL
   RETURN -1

DECLARE @link int, @vcCode VARCHAR(50), @ilink_self int, @vcDict VARCHAR(100), @bchildrens BIT , @vcName VARCHAR(254), @vcCode_Str VARCHAR(254), @iproperty INT , @vcadd_info VARCHAR(8000), @vcLong_Name VARCHAR(8000),
    @dBegin_date DATETIME , @dEnd_date DATETIME, @dBegin_date_Old DATETIME , @dEnd_date_Old DATETIME    
   
DECLARE cur CURSOR LOCAL STATIC FOR    
SELECT K.link, I.Code, K.link_self , I.Dict, K.childrens, K.Name, K.Long_Name, K.Code_Str, K.property , K.add_info, I.begin_date, I.end_date 
FROM  #IMPORT_FROM_BUFFER I
      JOIN dbo.report_kbk K ON K.code_form = I.Dict AND K.Code = I.Code  
 
OPEN cur
 
FETCH NEXT FROM cur INTO @link, @vcCode, @ilink_self , @vcDict, @bchildrens, @vcName, @vcLong_Name, @vcCode_Str, @iproperty , @vcadd_info, @dBegin_date, @dEnd_date 

WHILE @@FETCH_STATUS = 0
BEGIN
   SELECT @dBegin_Date_Old = begin_date, @dEnd_Date_Old = end_date
   FROM dbo.report_kbk
   WHERE link = @link
   
   SET @dBegin_Date = CASE WHEN ISNULL(@dBegin_Date, '19000101') >ISNULL(@dBegin_Date_Old, '19000101') THEN ISNULL(@dBegin_Date_Old, '19000101') ELSE ISNULL(@dBegin_Date, '19000101') END
   SET @dEnd_Date = CASE WHEN ISNULL(@dEnd_Date, '30000101') >ISNULL(@dEnd_Date_Old, '30000101') THEN ISNULL(@dEnd_Date, '30000101') ELSE ISNULL(@dEnd_Date_Old, '30000101') END
   EXEC dbo.[RN_SAVE_REPORT_KBK] @link, @vcCode, @iLink_self, @vcName, @vcDict, @bchildrens, @vcCode_Str, @iproperty, @vcAdd_info, @vcLong_Name, @dBegin_date, @dEnd_date 
   
   FETCH NEXT FROM cur INTO @link, @vcCode, @ilink_self , @vcDict, @bchildrens, @vcName, @vcLong_Name, @vcCode_Str, @iproperty , @vcadd_info, @dBegin_date, @dEnd_date 
END    

CLOSE cur
DEALLOCATE cur

INSERT dbo.report_kbk (Code, link_self, code_Form, childrens, NAME, ImageIndex, Code_str, PROPERTY, add_info, begin_date, end_date)
SELECT Code, 0, Dict, 0, '', 0, '', 0, '', begin_date, end_date 
FROM  #IMPORT_FROM_BUFFER I
WHERE NOT EXISTS(SELECT * FROM dbo.report_kbk K WHERE code_form = I.Dict AND K.code = I.Code) 

IF @@ROWCOUNT > 0
BEGIN
   EXEC dbo.[RO_KBK_CASHE_UPDATE] 
END     

DELETE K 
FROM dbo.REPORT_KBK K
WHERE K.Code_Form = 'BUFFER_IMPORT' and EXISTS(SELECT TOP 1 * FROM #IMPORT_FROM_BUFFER I WHERE K.Code = I.Code AND K.code_str = I.Dict)

GO
GRANT ALL ON dbo.[RO_IMPORT_SPR_FORM_BUFFER] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RT_DICTION_RRO_NORM_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RT_DICTION_RRO_NORM_SAVE]
GO
/*
c Кейсистемс (Keysystems), 2008
*/
CREATE  PROCEDURE dbo.[RT_DICTION_RRO_NORM_SAVE]
	@varKSintLINK	int	OUTPUT,
	@varKScTYPE varchar(254) = NULL,
	@varKScDATE varchar(254) = NULL,
	@varKScNUMB varchar(254) = NULL,
	@varKScNAME varchar(8000) = NULL,
	@varKScN_DB varchar(254) = NULL,
	@varKScN_DE varchar(254) = NULL, 
	@varKScWHOSE    varchar(1)   = NULL,
	@varKSiLinkDep int = NULL,
   @varKSbIs_Sub  bit = 1,
   @varKSbIs_MO   bit = 1,
   @varKScN1   VARCHAR(254) = '', -- номер абзаца
   @varKScN2   VARCHAR(254) = '', -- номер подпункта
   @varKScN3   VARCHAR(254) = '', -- номер пункта
   @varKScN4   VARCHAR(254) = '', -- номер части
   @varKScN5   VARCHAR(254) = ''  -- номер статьи
AS

DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int,
	@link int,
	@looks_like_error int,
   @cOldName varchar(8000),
    @D_BE   varchar(100),
   @Type  varchar(8000),
   @Numb varchar(1000),
   @Date varchar(100),
   @N_DB varchar(100),
   @N_DE varchar(100),
   @Name varchar(8000),
   @update_data tinyint,
   @LF int
   
   select @LF = link_form from dbo.report_forms where code = 'RRO'

   if @varKScWHOSE = 'f'
      select @cOldName = Name from dbo.RT_VIEW_RRO_NORM_F_1 where link = @varKSintLINK
   else
      if @varKScWHOSE = 's'
         select @cOldName = Name from dbo.RT_VIEW_RRO_NORM_S_1 where link = @varKSintLINK
      else
         select @cOldName = Name from dbo.RT_VIEW_RRO_NORM_L_1 where link = @varKSintLINK

   declare @t_Col table (Link_Col int, Link_Table int, OrderCol tinyint, OrderTable tinyint)
   declare @t_String_To_Change table (LSF int, Code_Row varchar(50))

   insert @t_Col (Link_Col, Link_Table, OrderCol, OrderTable)
   select RC.Link_Col, RC.Link_Table, RC.orders, RT.orders
   from dbo.report_coloumns RC join dbo.report_tables RT on RC.Link_Table = RT.Link_Table
   where RT.link_form = @LF and ((isnull(@varKSbIs_Sub, 1) = 1 and RT.orders = 1) or (isnull(@varKSbIs_MO, 1) = 1 and RT.orders = 2))

	if len(@varKScTYPE)=0 or len(@varKScNUMB)=0 or len(@varKScNAME)=0 begin
		return 5
	end
	if  len(replace(@varKScN_DB,'.','')) < 8
		set @varKScN_DB = '' 
	else 
		set @varKScN_DB = convert(varchar(10), convert(datetime, @varKScN_DB), 104)
	

	if len(replace(@varKScN_DE,'.','')) < 8
		set @varKScN_DE = '' 
	else 
		set @varKScN_DE = convert(varchar(10), convert(datetime, @varKScN_DE), 104)

	set @varKScDATE = convert(varchar(10), convert(datetime, @varKScDATE), 104)
	
	if exists(
				select * 
				from dbo.REPORT_DICTION_RRO_NORM 
				where 
					rtrim([TYPE]) = rtrim(@varKScTYPE) 
				and rtrim([DATE]) = rtrim(@varKScDATE) 
				and rtrim([NUMB]) = rtrim(@varKScNUMB) 
				and rtrim([WHOSE]) = rtrim(@varKScWHOSE)
            and [N_ABZ] = ISNULL(@varKScN1, '')
            AND [N_POD] = ISNULL(@varKScN2, '')
            AND [N_PUN] = ISNULL(@varKScN3, '')
            AND [N_CHA] = ISNULL(@varKScN4, '')
            AND [N_STA] = ISNULL(@varKScN5, '')) 
				and (@varKSintLINK is null  OR @varKSintLINK = 0) or (len(rtrim(ltrim(@varKScTYPE))+rtrim(ltrim(@varKScDATE))+rtrim(ltrim(@varKScNUMB)))=0)
		set @looks_like_error = 1
	else
		set @looks_like_error = 0

	IF @looks_like_error = 1
		RETURN 8

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT -1 -- Время ожидания разблокировки ресурсов 3 сек.
BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.


	IF (@varKSintLINK is null  OR @varKSintLINK = 0) 
	BEGIN
		insert into REPORT_DICTION_RRO_NORM ([TYPE],[DATE],[NUMB],[NAME],[N_DB],[N_DE],[WHOSE], [LINK_DEPARTMENT], Is_Sub, Is_MO, [N_ABZ], [N_POD], [N_PUN], [N_CHA], [N_STA])
			VALUES (ltrim(rtrim(@varKScTYPE)),ltrim(rtrim(@varKScDATE)),ltrim(rtrim(@varKScNUMB)),ltrim(rtrim(@varKScNAME)),ltrim(rtrim(@varKScN_DB)),ltrim(rtrim(@varKScN_DE)),ltrim(rtrim(@varKScWHOSE)), @varKSiLinkDep, isnull(@varKSbIs_Sub,1), isnull(@varKSbIs_MO, 1),
                  RTRIM(ISNULL(@varKScN1, '')), RTRIM(ISNULL(@varKScN2, '')), RTRIM(ISNULL(@varKScN3, '')), RTRIM(ISNULL(@varKScN4, '')), RTRIM(ISNULL(@varKScN5, '')))
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
          ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
            COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE REPORT_DICTION_RRO_NORM
		SET [TYPE] = ltrim(rtrim(@varKScTYPE)),
			[DATE] = ltrim(rtrim(@varKScDATE)),
			[NUMB] = ltrim(rtrim(@varKScNUMB)),
			[NAME] = ltrim(rtrim(@varKScNAME)),
			[N_DB] = ltrim(rtrim(@varKScN_DB)),
			[N_DE] = ltrim(rtrim(@varKScN_DE)),
			[WHOSE] = ltrim(rtrim(@varKScWHOSE)),
			[LINK_DEPARTMENT] = @varKSiLinkDep,
         [Is_Sub] = @varKSbIs_Sub,
         [Is_MO] = @varKSbIs_Mo,
         [N_ABZ] = RTRIM(ISNULL(@varKScN1, '')),
         [N_POD] = RTRIM(ISNULL(@varKScN2, '')),
         [N_PUN] = RTRIM(ISNULL(@varKScN3, '')),
         [N_CHA] = RTRIM(ISNULL(@varKScN4, '')),
         [N_STA] = RTRIM(ISNULL(@varKScN5, ''))
		WHERE LINK = @varKSintLINK
      
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
          ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
            COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
          ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
            COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
			RETURN 2
		END
	END

set @update_data = 1
--IF @@TRANCOUNT > @varKStrancount
--   set @update_data = 1

COMMIT TRAN
IF @update_data = 1 begin
	update dbo.REPORT_DICTION_RRO_NORM
	set [N_DB] = case when len(replace([N_DB],'.','')) < 8 then '' else [N_DB] end,
		[N_DE] = case when len(replace([N_DE],'.','')) < 8 then '' else [N_DE] end
	where rtrim([WHOSE]) = rtrim(@varKScWHOSE)

   if isnull(@cOldName, '') <> '' -- заменяем во всех отчетах РРО на соответсвующие поля
   begin
     if @varKScWHOSE = 'f' 
      begin
        insert @t_String_To_Change(LSF, Code_Row)
        select RD.Link_SF, RD.Code_Row
        from dbo.report_dinamics RD join @t_Col C on RD.Link_Col = C.Link_Col
            join dbo.report_saved_forms RSF on RD.link_sf = RSF.link_saved_form and RSF.link_form = @LF
        where C.OrderCol = 11 and Str_Val = @cOldName
        
        select @Name = [Name], @D_BE = D_BE, @Type = [Type], @Numb = Numb, @Date = Date, @N_DB = N_DB,@N_DE = isnull(N_DE, '')  from [dbo].[RT_VIEW_RRO_NORM_F_1] where Link = @varKSintLINK
         update RD1
         set Str_Val = @Name
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 11
         update RD1
         set Str_Val = @D_BE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 17 
         update RD1
         set Str_Val = @Type
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 18
         update RD1
         set Str_Val = @Numb
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 19
         update RD1
         set Str_Val = @Date
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 20
         update RD1
         set Str_Val = @N_DB
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 21
         update RD1
         set Str_Val = @N_DE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 22
      end
      if @varKScWHOSE = 's' 
      begin
        insert @t_String_To_Change(LSF, Code_Row)
        select RD.Link_SF, RD.Code_Row
        from dbo.report_dinamics RD join @t_Col C on RD.Link_Col = C.Link_Col
            join dbo.report_saved_forms RSF on RD.link_sf = RSF.link_saved_form and RSF.link_form = @LF
        where C.OrderCol = 23 and Str_Val = @cOldName

         select @Name = [Name], @D_BE = D_BE, @Type = [Type], @Numb = Numb, @Date = Date, @N_DB = N_DB,@N_DE = isnull(N_DE, '')  from [dbo].[RT_VIEW_RRO_NORM_S_1] where Link = @varKSintLINK
         update RD1
         set Str_Val = @Name
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 23
         update RD1
         set Str_Val = @D_BE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 29
         update RD1
         set Str_Val = @Type
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 30
         update RD1
         set Str_Val = @Numb
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 31
         update RD1
         set Str_Val = @Date
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 32
         update RD1
         set Str_Val = @N_DB
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 33
         update RD1
         set Str_Val = @N_DE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 34
      end
      if @varKScWHOSE = 'l' 
      begin
        insert @t_String_To_Change(LSF, Code_Row)
        select RD.Link_SF, RD.Code_Row
        from dbo.report_dinamics RD join @t_Col C on RD.Link_Col = C.Link_Col
            join dbo.report_saved_forms RSF on RD.link_sf = RSF.link_saved_form and RSF.link_form = @LF
        where C.OrderCol = 35 and Str_Val = @cOldName

         select @Name = [Name], @D_BE = D_BE, @Type = [Type], @Numb = Numb, @Date = Date, @N_DB = N_DB,@N_DE = isnull(N_DE, '')  from [dbo].[RT_VIEW_RRO_NORM_L_1] where Link = @varKSintLINK
         update RD1
         set Str_Val = @Name
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 35
         update RD1
         set Str_Val = @D_BE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 41
         update RD1
         set Str_Val = @Type
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 42
         update RD1
         set Str_Val = @Numb
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 43
         update RD1
         set Str_Val = @Date
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 44
         update RD1
         set Str_Val = @N_DB
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 45
         update RD1
         set Str_Val = @N_DE
         from dbo.report_dinamics RD1 join @t_String_To_Change S on RD1.Link_SF = S.LSF and RD1.Code_Row = S.Code_Row
               join @t_Col C on RD1.Link_Col = C.Link_Col
         where C.OrderCol = 46
      end
   end

end
RETURN 0


GO


GRANT EXECUTE ON dbo.[RT_DICTION_RRO_NORM_SAVE] 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_DELETE_EXPORT_MODEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_DELETE_EXPORT_MODEL]
GO





/*
© Кейсистемс (Keysystems), 2005
*/


CREATE  PROCEDURE dbo.BB_DELETE_EXPORT_MODEL
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = 'Блок экспорта ' + CODE + ' ' + NAME FROM dbo.EXPORT_MODELS
	WITH (UPDLOCK) WHERE LINK_MODEL= @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.EXPORT_MODELS WHERE LINK_MODEL = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'BB_EXPORT_MODELS'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'EXPORT_MODELS', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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))	
	

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,2), [OBJECT] INT,
					BASE_YEAR NUMERIC(18,2), SUMMA_YEAR NUMERIC(18,2), SUMMA_OLD NUMERIC(18,2), SUMMA NUMERIC(18,2))

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 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	


--3) РАНЕЕ НАЧИСЛЕННЫЕ ДОХОДЫ,ВЗНОСЫ И НАЛОГИ
CREATE TABLE #OLD (PERS_LINK INT, LINK_DOG INT, LINK INT, SUMMA_D NUMERIC(18,2), SUMMA_N NUMERIC(18,2))

INSERT INTO #OLD (PERS_LINK, LINK_DOG, LINK, SUMMA_D, SUMMA_N)
SELECT
	J.PERS_LINK,
	D.LINK_DOG,
	P.LINK,
	SUMMA_D = SUM(J.SUMMA_BASE),
	SUMMA_N = SUM(J.SUMMA)
FROM 
	dbo.PAYS P 
	INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
	INNER JOIN dbo.SDOC_DGH_TABLE D ON D.LINK_UP = J.LINK_DOC AND J.PERS_LINK = D.PERS_LINK	
WHERE 
	J.LINK_DEP = @DEP_LINK
	AND
	D.[OBJECT] = 1	
	AND
	(
		P.[OBJECT] = 2 AND P.WAY_CALC IN (4,5,6)
		OR
		P.[OBJECT] = 3 AND EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK)
	)	
	AND
	YEAR(J.PERIOD_BEGIN) = YEAR(@varKSDateE)
	AND
	MONTH(J.PERIOD_BEGIN) <= MONTH(@varKSDateE)
	AND 
	EXISTS (SELECT * FROM #DGH D WHERE D.PERS_LINK = J.PERS_LINK)
GROUP BY
	J.PERS_LINK,
	D.LINK_DOG,
	P.LINK

--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


--Определенеи налога с начала года
UPDATE T SET 
	T.SUMMA_YEAR = 
		CASE WHEN P.OBJECT = 2 THEN
			ROUND(T.BASE_YEAR * 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

--Определенеи налога за месяц
UPDATE T SET 
	T.SUMMA = T.SUMMA_YEAR - T.SUMMA_OLD
FROM 
	#TAX T
	

DECLARE @Cur1 CURSOR
DECLARE @ID INT, @OBJECT INT, @OBJECT2 INT, @NEXT INT
SELECT @NEXT = 0, @OBJECT2 = 0
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT ID, OBJECT FROM #TAX ORDER BY ID

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		IF @OBJECT <> @OBJECT2 BEGIN
			SET @NEXT = 1
			SET @OBJECT2 = @OBJECT
		END			
		ELSE
			SET @NEXT = @NEXT + 1
		
		UPDATE #TAX SET ORDERS = @NEXT WHERE ID = @ID

	END

	FETCH NEXT FROM @Cur1 INTO @ID, @OBJECT
END

CLOSE @Cur1
DEALLOCATE @Cur1
		

SELECT
	T.ORDERS,
	D.LINK, D.PERS_LINK, D.FIO, D.LINK_VKR, D.NAME_VKR, D.LINK_EKR, D.CODE_EKR,
	LINK_PAY = P.LINK, CODE_PAY = P.CODE, NAME_PAY = P.NAME, P.[OBJECT],
	T.BASE_YEAR, T.SUMMA_BASE, 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
ORDER BY
	P.OBJECT, D.FIO	

RETURN 0
	
GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_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].[XD_FORM_BO_MASS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[XD_FORM_BO_MASS]
GO

CREATE  PROCEDURE XD_FORM_BO_MASS
	@varKSparDate1 datetime,
	@varKSparDate2 datetime
AS 
DECLARE @Curs CURSOR,	
		@CurLink int,
		@cNumber varchar(25),
		@cName varchar(100),
		@cDate varchar(10),
		@iDepLink int
set @iDepLink = dbo.BK_GetDepZB()		

create table #tProtocol(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

SET @Curs = CURSOR FORWARD_ONLY FOR 
SELECT DISTINCT G.LINK  FROM G_PROV G,G_PROV1 G1,G_PROV2 G2 
WHERE (@iDepLink is null or @iDepLink is not null and @iDepLink = G.DEP) /*and 
G.LINK NOT IN
(SELECT LINK_G_PROV FROM OSNOV WHERE LINK IN (SELECT LINK_DOC FROM JURN_BO) 
	AND TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1))*/
AND G.LINK = G1.LINK_UP AND G1.LINK = G2.LINK_UP AND G2.ECON_OPER IN (SELECT LINK FROM XD_XOZ_OPER WHERE BO = 1 or DO = 1)
AND G.DATE_PROV IS NOT NULL AND G.DATE_PROV BETWEEN @varKSparDate1 AND @varKSparDate2
/*AND G2.LINK NOT IN (SELECT LINK_UP FROM G_PROV_AP WHERE AP1 IN
(SELECT LINK FROM OSNOV WHERE TYPE_LINK IN (SELECT LINK FROM OSNOV_VID WHERE TYPE = 1 AND OBJECT IN ('FINANS_CONTRACT','FINANS_CONTRACT_CHANGE')))) */

OPEN @Curs
FETCH FROM @Curs INTO @CurLink
WHILE @@FETCH_STATUS = 0
BEGIN
	insert into #tProtocol (txt, NEW_ROW, nSTATUS, nTAB) EXEC XD_FORM_BO @CurLink 
	print @CurLink
	FETCH FROM @Curs INTO @CurLink
END
CLOSE @Curs
DEALLOCATE @Curs

select txt, NEW_ROW, nSTATUS, nTAB from #tProtocol
drop table #tProtocol
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RB_CALC_0503125G_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RB_CALC_0503125G_NEW]
GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RB_CALC_0503125G_NEW
@iLSF int,
@table int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						PPP varchar(3), 
						OKATO varchar(11), 
						EL_BUDG varchar(2), 
						KBK varchar(17), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 PPP varchar(3), 
						 OKATO varchar(11), 
						 EL_BUDG varchar(2), 
						 KBK varchar(17), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9), 
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(20))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
print @iLinkCalcForm
if @iLinkCalcForm is null 
BEGIN
	exec RT_CALC_0503125G @iLSF, @table
	RETURN 0
END

set @iLinkColDt = (select RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = @table and RT.orders = @table
					where @table = 2 and RC.Export_Order = 9 or @table <> 2 and RC.Export_Order = 7)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)


-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/

--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)

---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			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, -- ОКАТО
			EL_BUDG = case when TMP.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(KBK.CODE,'.',''),''), --KBK
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	FROM dbo.G_PROV G
	INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and (SO.CODE = 'NOTICE_LINK_DEP_RECEIVER' or SO.CODE = 'NOTICE_LINK_DEP_SENDER') AND GPDA.DEPARTMENT <> G.Dep), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
			
			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			PPP = case when R.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			OKATO = case when R.Mask_KBK like '%ОКАТО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when R.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(K.CODE,'.',''),''), --KBK
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, summa_db, summa_kr, KORR_ACC, D_ND)
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND
union
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND



if @table in (1,3) 
	SELECT 
--	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
--	[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,14), -- КБК
	[COL7] = SUMMA_DB, -- сумма дебет
	[COL8] = SUMMA_KR, -- сумма кредит
	[COL9] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL10] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL11]= LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL12]= RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP

else 
	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,4), -- РзПр
	[COL7] = substring(rtrim(KBK),8,7), -- ЦСР
	[COL8] = substring(rtrim(KBK),15,3),-- ВР
	[COL9] = SUMMA_DB, -- сумма дебет
	[COL10] = SUMMA_KR, -- сумма кредит
	[COL11] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL12] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL13] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL14] = RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP



GO
GRANT EXECUTE ON dbo.[RB_CALC_0503125G_NEW] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
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_CHECK_KS_INSIDE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_KS_INSIDE]
GO

/*
c Кейсистемс (Keysystems), 2009.10.21
*/
CREATE     PROCEDURE dbo.RO_CHECK_KS_INSIDE 
	@LSF int = NULL,  -- сохраненная форма
	@varKStableName varchar(100) = '', -- таблица с линками отчетов
	@cTables varchar(1000) = '', --для какой таблицы формы будем проводить проверку (если '' - то для всех)
	@iDown int=0, --проверка по ветке
	@varKScGroup varchar(250)='', --группа кс,
	@cProgressTable varchar(254) = '', -- имя таблицы, куда будем записывать состояние о проверке и проценты
	@tmpTable varchar(100) = '', --временная таблица для протокола
	@typeProtokol tinyint = 0, -- тип протокола (если @tmpTable пустно): 
							-- 0 - автоматический выбор (если меньше 10000 строк, то html, иначе грид),
							-- 1 - грид всегда
							-- 2 - html всегда
	@varKSiTypeRules INT = 0,	-- 0 - обычная проверка без консолидации, 4 - только проверка консолидации, -1 - все правила
	@varKSiNotAllRules	tinyint =  0 -- 0 - обычная проверка, 1 - показать из чего получилась ячейка, 2 - проверка не всех правила
AS

------------------------------------------------------------------------------
-- правила:
create table #t_Rules (Link_Rule 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_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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 default (0) )

create table #t_KS_difficalt (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(250), 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 default (0) )

-- записываем результат левой и правой частей:
create table #t_Result([Value] float, Link_Rule int, part tinyint, algorithm tinyint, orderCol int, CodeRow varchar(50), corderCol varchar(10))
-- будущий протокол (туда же пишут хранимки):
create table #Res (orders int,ord int IDENTITY (1, 1) NOT NULL, res varchar(8000) default '',cKod varchar(8000) default '',cDoc varchar(8000) default '',cTable varchar(100) default '',cCol varchar(100) default '',cValue varchar(100) default '', cPeriod varchar(30) default '', cBudg varchar(254) default '', cGroup varchar(1000))
-- список отчетов:
create table #ListForms (lsf int, linkForm int, codeForm char(20), cbudg varchar(254), cOrg varchar(254), cperiod varchar(100), modify_date datetime, email varchar(254))
-- результат хранимок (хотя в будущем этого не надо)
create table #tmp (Value float)
-- результат сравнения левой и правой частей
create table #t_Result_sr (Link_Rule int, CodeRow varchar(254), orderCol int, error tinyint, LeftPart numeric(20,4), RightPart numeric(20,4), Str_Rule varchar(8000), Comment varchar(2000), OrderRule int, sign_sr char(2))
-- для протокола операнды
create table #t_Res_summand (Link_Rule int, OrderRow int, [sign] char(2), cOrderTable varchar(254), cOrderCol varchar(10), Code_Row varchar(250), Filter_desc varchar(200), part tinyint, [Value] numeric(20,4), orderCol tinyint default 0, CodeRow varchar(254) default '', px_Comment varchar(1000) default '')
-- линки отчетов, которые нужно проверить
create table #t_LSF (lsf int)
-- для размножения сложных правил
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(250), 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_rules_group_ks (link int)
-- таблицы для проверки справочной информации
declare @table_ks table (Link_Table int, Orders tinyint)
-- Дерево КБК 
create table #TreeKBK (Link int, Link_Self int, Code_Row varchar(50), Link_Table int, Calc tinyint, cOrderTable varchar(300))
CREATE INDEX #IX_tree_kbk ON #TreeKBK (Link_Self)
CREATE INDEX #IX_tree_kbk1 ON #TreeKBK (Link)
CREATE INDEX #IX_tree_kbk2 ON #TreeKBK (Link_Table, Code_Row)
create table #TreeExclude (Code VARCHAR(50), Link_COl INT)
declare @t_TreeKBK_cols table(Link_Table int, Cols varchar(100))

-- для ускорения, чтобы уменьшить количество записей и не обращаться к постоянным таблицам
create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len int, Col_Type tinyint, OrderCol int, cOrderCol varchar(10))
create table #t_Rows_Static(Link_Row int primary key, Code varchar(50), Link_Table int, orders int, Dop_Col varchar(1000))
create table #report_dinamics(Link_SF int, Code_Row varchar(50), 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(50), summa float)
create table #t_Factor (Link_Rule int, OrderRow int, [sign] char(2), part tinyint, factor float)
create table #t_Tables (Link_Table int, orders tinyint, Name varchar(254), Val_Type tinyint, Dop_Col int)
create table #t_Pr_Form(Form varchar (1000), Period varchar(1000), Org varchar(1000), Budg varchar(1000))

Create index #IX_REPORT_SUMMA on #t_summa (link_col,link_row)
Create index #IX_report_dinamics on #report_dinamics (link_sf,link_col,code_row)


declare @cOrg varchar(254), @cBudg varchar(254), @LinkRule int, @ExecStr varchar(8000), @IsSvod tinyint, @atr_code varchar(254), @i int, @maxOrderRow int, @round tinyint, @modifyDate datetime, @orderProtokol int, @liError int, @cGroup varchar(1000)
declare @nprecision float, @lsf_tmp int, @strProgressExec varchar(1000), @LinkSF int, @LinkF int, @codeForm varchar(20), @time_begin datetime, @time_end datetime, @cPeriod varchar(100), @linkProtokol int, @orderTable tinyint, @ord int, @CountError int
declare @Statistics INT, @cDataDesc VARCHAR(1000), @cStr VARCHAR(254), @region VARCHAR(250), @countLSF INT, @orderLSF INT
DECLARE @CodeRow VARCHAR(50), @nvExecStr NVARCHAR(4000), @dBeginDate DATETIME 

select @Statistics = Val_Int from dbo.report_options where razdel = 'statistics' and code = 'mode'
set @nprecision = 0.005

set @time_begin = getdate()


if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение данных отчетов'', percents = 3'
    execute(@strProgressExec)
end

if @cTables = '-1'
	set @cTables = ''


if @varKScGroup <> ''
begin
	insert  #t_rules_group_ks(link)
	select link_rule from report_control_group (NOLOCK) where link_group_ks=(select top 1 link_group_ks from  report_group_ks (NOLOCK) where name=@varKScGroup and type=4)
	Create index #ix_rules_group_ks on #t_rules_group_ks (link)
	
	SET @varKSiTypeRules = -1 -- значит берем выбранные правила 
end

----------------------------------------------------------------------------------------
-- для протокола HTML
CREATE TABLE #ks_protokol_HTML ([order] Integer, [type] Integer, [html] VarChar(8000))
CREATE TABLE #ks_protokol_HTML_Table ([order] Integer, [type] Integer, [html] VarChar(8000))
exec HTMLReport @nMode = 0, @cWorkTableName = '#ks_protokol_HTML', @cRepHeader = 'Протокол проверки контрольных соотношений'

------------------------------------------------------------------------------------
-- получение отчетов
insert #t_LSF (lsf)
SELECT link FROM [dbo].[BufferGetTableByID]('report_saved_forms_check_ks')
EXEC dbo.[BufferClear] 'report_saved_forms_check_ks'


if RTRIM(ISNULL(@varKStableName,'')) <> '' and (select object_id('tempdb..' + @varKStableName)) is NOT NULL
begin
  set @ExecStr = 'insert #t_LSF (lsf) select * from ' + @varKStableName + ' drop table ' + @varKStableName
  execute(@ExecStr)
  delete #t_LSF where lsf not in (select Link_Saved_Form from dbo.report_Saved_Forms)
END   
IF @LSF IS NULL
begin
   if not exists(select top 1 * from #t_LSF)
   begin
     insert #Res (res) values ('Не выбран ни один отчет для проверки!')
     select isnull(res,'') res,isnull(cdoc,'') cdoc,isnull(ctable,'') ctable,isnull(ckod,'') ckod,isnull(ccol,'') ccol,isnull(cvalue,'') value from #Res order by orders,ord
     return 0
   END
  IF @iDown=1
    begin
        select -lsf as lsf into #LF_TMP from #t_LSF
        While exists(select * from #LF_TMP where lsf<0)
            begin
               select top 1 @lsf_tmp=-lsf  from #LF_TMP where lsf<0
               INSERT #LF_TMP exec dbo.RN_GET_SVOD_FORMS @lsf_tmp,default,default,default,default,default,default,default,default,1,1
               delete  #LF_TMP where lsf=-@lsf_tmp
            end
        INSERT #t_LSF (lsf)
        SELECT lsf from #LF_TMP A where not exists(select * from #t_LSF where lsf=A.lsf)
		drop table #LF_TMP
    end 
  IF @iDown=2
    begin
        select lsf as lsf into #LF_TMP2 from #t_LSF
        While exists(select * from #LF_TMP2 where lsf>0)
            begin
               select top 1 @lsf_tmp=lsf  from #LF_TMP2 where lsf>0
               INSERT #LF_TMP2 exec dbo.RN_GET_SVOD_FORMS @lsf_tmp,default,default,default,default,default,default,default,default,1,1
               update #LF_TMP2 set lsf=-lsf   where lsf=@lsf_tmp
            end
        INSERT #t_LSF (lsf)
        SELECT -lsf from #LF_TMP2 A where not exists(select * from #t_LSF where lsf=-A.lsf)
		drop table #LF_TMP2
    end 
end

if (@LSF is not null) and exists(select top 1 * from report_saved_forms where link_saved_form = @LSF)
begin
  insert #t_LSF (lsf) values (@LSF)
end

insert #ListForms (lsf, linkForm, codeForm, cbudg, cOrg, cperiod, modify_date, email)
select RSF.link_saved_form, RSF.Link_Form, RF.code, B.Name, D.Name, 
		case RSF.Period_Type when 1 then LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' год' 
				when 2 then LTRIM(STR(Period_Number)) + ' квартал ' + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				when 4 then case Period_Number 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   + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				end, modify_date, '' as email
from report_saved_forms RSF (NOLOCK)  
		left join report_forms RF (NOLOCK) on RF.Link_Form = RSF.Link_Form
		left join kl_budg_type B (NOLOCk) on B.link = RSF.link_type_Svod
		left join departments D (NOLOCK) on D.link = RSF.Link_Organization
where RSF.link_saved_form in (select lsf from #t_LSF)

exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))

-- для ускорения протокола
declare @t table (orders int)
	insert @t values(1)
	insert @t values(3)
	insert @t values(6)
	insert @t values(7)
	insert @t values(8)

insert #res (cDoc, cTable)
select '<B> <FONT Size = 4><COUNTERROR>', '<B> <FONT Size = 4><RUNTIME>' 

exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = '', @cDataTableName  = '#res',
	@cShowFields  = '<field name=''cDoc'' ALIGN="center"></field><field name=''cTable'' ALIGN="center"></field>'
, @cFieldsDesc  = 'Количество ошибок|Время выполнения'

delete #res
set @CountError = 0

SELECT @countLSF = COUNT(*) FROM #ListForms
SET @orderLSF = 0

while exists(select top 1 * from #ListForms)
BEGIN
   SET @orderLSF = @orderLSF + 1
	delete @t_temp
	truncate table #t_KS
	truncate table #t_Rules
	truncate table #t_Result_sr
	truncate table #t_Summa
	truncate table #report_dinamics
	truncate table #t_Col
	truncate table #t_Rows_Static
	truncate table #t_Res_summand
	truncate table #t_Result	
	truncate table #t_Factor
	truncate table #t_Tables
	truncate table #t_Pr_Form
	truncate table #Res
   truncate table #TreeKBK
   truncate table #TreeExclude  
   TRUNCATE TABLE #ks_protokol_HTML_Table  
   truncate table #t_KS_difficalt

	set @liError = 0
	select top 1 @LinkSF = LF.lsf, @LinkF = LF.LinkForm, @codeForm = LF.codeForm, @cBudg = LF.cBudg, @cOrg = LF.cOrg, @cPeriod = LF.cPeriod, @modifyDate = LF.modify_date, @cGroup = LF.cOrg + ' EMAIL=<' + rtrim(LF.email) + '>'  ,
            @dBeginDate = rsf.Begin_date
   from #ListForms LF
         JOIN dbo.[REPORT_SAVED_FORMS] rsf ON LF.[lsf] = rsf.[Link_Saved_Form]
         JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization] 
   order by codeForm, d.code
   
	delete #ListForms where lsf = @LinkSF

	exec dbo.ro_get_tree_kbk @LinkF, @cTables, @LinkSF -- грузим дерево КБК

	insert @t_TreeKBK_cols (Link_Table, Cols)
	select Link_Table, isnull(dbo.rn_get_formula_code_row_f(Link_Table,'KBK='),'')
	from report_tables where Link_Form = @LinkF

   UPDATE @t_TreeKBK_cols
   SET cols = ''
   WHERE cols LIKE '%(%' AND (cols NOT LIKE '%' + RTRIM(@region) + '%' OR @region = '') 

	set @orderProtokol = isnull((select max(ord) from #Res), 0)
--	insert #t_Pr_Form(Form, Period, Org, Budg)
--	values ('<B> <FONT Size = 4>' + @codeForm, '<B><FONT Size = 4>' + @cPeriod, '<B><FONT Size = 4>' + @cOrg, '<B><FONT Size = 4>' + isnull(@cBudg, ''))

--	exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = '', @cDataTableName  = '#t_Pr_Form',
--		@cShowFields  = '<field name=''Form''  ALIGN="center"></field><field name=''Period'' ALIGN="center"></field><field name=''Org'' WRAP=''1''></field><field name=''Budg'' WRAP=''1''></field>'
--	, @cFieldsDesc  = 'Код формы|Период|Организация|Бюджет'

	-------------------------------------------------------------------------------------------------------
	-- получение данных 
	if @cTables = '' 
	begin
		insert #t_Tables (Link_Table, orders, Name, Val_Type, Dop_Col)
		select Link_Table, orders, Name, Val_Type, (select top 1 Link_Col from report_coloumns RC where RT.Link_Table = RC.Link_Table and IsEdited = 0 and RT.Link_Code_Col <> RC.Link_Col and RC.Val_len < 50 and Col_type = 1)
		from report_tables RT 
		where Link_Form = @LinkF 

		update RT
		set Dop_Col = (select top 1 Link_Col from report_coloumns RC join report_tables T on RC.Link_Table = T.Link_Table and RC.link_col <> T.link_code_col where RT.Link_Table = RC.Link_Table and IsEdited = 0  and Col_type = 1)
		from #t_Tables RT
		where Dop_Col is NULL

	end 
	else
	begin
		set @execstr='insert #t_Tables (Link_Table, orders, Name, Val_Type)
				 select Link_Table, orders, Name, Val_Type from report_tables (NOLOCK) where Link_Form = ' + STR(@LinkF) + ' and Link_Table in ('+@cTables+')'
		 exec(@execstr) 
	end

	insert #t_Col (Link_Col, Name, Link_Table, Val_Len, Col_Type, OrderCol, cOrderCol)
	select Link_Col, Name, Link_Table, Val_len, Col_Type, orders, '№' + LTRIM(STR(Export_Order))
	from report_coloumns RC (NOLOCK)
	where Link_Table in (select Link_Table from #t_Tables) --and Col_Type = 0

	select @round = max(Val_Len) from #t_Col where Col_Type = 0

	insert #t_Rows_Static(Link_Row, Code, Link_Table, orders, Dop_Col)
	select RR.Link_Row, RR.Code, RR.Link_Table, RR.orders, RF.formula
	from dbo.i_report_rows RR 
			join #t_Tables T on RR.Link_Table = T.Link_Table and T.Val_Type = 0
			left join dbo.report_formula RF on RR.link_row = RF.link_row and RF.Link_Col = T.Dop_Col

	
	insert #t_summa (lsf, link_col, link_row, code, summa)
	select RS.link_saved_form, RS.link_col, RS.link_row, R.code, round(RS.summa, @round)
	from (select * from report_summa_all (NOLOCK) where Link_Saved_Form = @LinkSF)	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, round(RD.float_val,@round), RD.str_val, C.Link_Table
	from report_dinamics_all RD (NOLOCK) inner join #t_Col C on RD.Link_Col = C.Link_Col
	where RD.Link_SF = @LinkSF --and  float_val <> 0 

	if @cProgressTable <>'' BEGIN
      
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Проверка на правильный ввод (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+5)/@countLSF))
		execute(@strProgressExec)
	end

	insert @table_ks(Link_Table, orders)
	select Link_Table, orders
	from #t_Tables

    while Exists(select * from @table_ks) and @varKSiNotAllRules = 0
    begin
          select @orderTable=orders from @table_ks  
          exec dbo.RN_CHECK_DICT @LinkSF, @orderTable
          delete @table_ks where orders=@orderTable  
    end

--	delete #report_dinamics where float_val = 0
--	delete #t_Col where Col_Type = 1

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Получение правил КС (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = '  + str(convert(int, ((@orderLSF-1)*100+15)/@countLSF))
		execute(@strProgressExec)
	end

	------------------------------------------------------------------------------------
	-- получение правил
	insert #t_Rules_region exec dbo.[I_CONTROL_RULES_LIST] @LinkSF, 0

	if @varKSiNotAllRules = 0 or object_id('tempdb..#t_Rules_result') is NULL
	begin
		insert #t_Rules (Link_Rule, algorithm, [sign_sr], cols, [rows], Str_Rule, Comment, OrderRule, IsDoschet) 
		select Ru.Link_Rule, algorithm, sign_sr, 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 (isnull(@cTables,'') <> '' or isDoschet&2=0) 
		AND (@varKSiTypeRules = -1 OR IsDoschet & 4 = @varKSiTypeRules)  -- проверка консолидации
	end
	else -- правила записаны в таблице внешней #t_Rules_Result
	begin
		insert #t_Rules (Link_Rule, algorithm, [sign_sr], cols, [rows], Str_Rule, Comment, OrderRule) 
		select Ru.Link_Rule, algorithm, sign_sr, case when orderCol = 0 then Ru.cols else LTRIM(RTRIM(STR(Res.orderCol))) end, [rows], Str_Rule, Comment, Ru.OrderRule
		from report_control_rules Ru  (NOLOCK) inner join #t_Rules_region R on Ru.Link_Rule = R.Link_Rule
			join #t_Rules_result Res on Ru.Link_Rule = Res.Link_Rule
		where (isnull(@cTables,'') <> '' or isDoschet&2=0) 
		AND (@varKSiTypeRules = -1 OR IsDoschet & 4 = @varKSiTypeRules)  -- проверка консолидации
	end

	truncate table #t_Rules_region

	if @varKScGroup <> ''
		delete #t_Rules where not exists(select * from #t_rules_group_ks G where G.Link = link_rule)

	if not exists(select top 1 * from #t_Rules) and not exists(select top 1 * from #TreeKBK)
	begin
		insert #Res (cDoc, cGroup)
		select 'Нет правил контрольных соотношений', @cGroup
		insert #Res  (res, cDoc, cKod, cTable, cCol, cValue, cBudg)
		values('', '', '', '', '', '', @cGroup)

       SET @cDataDesc = 'Форма: ' + @codeForm + ' Период: ' + @cPeriod + ' Организация: ' + @cOrg + ' Бюджет: ' + isnull(@cBudg, '') 

	     exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = @cDataDesc, @cDataTableName  = '#res',@cShowFields  = 
	   '<field name=''res'' width=''5%'' WRAP=''1''></field>
	    <field name=''cdoc'' width=''40%'' WRAP=''1''></field>
	    <field name=''ctable'' width=''25%'' WRAP=''0''></field>
	    <field name=''ckod'' width=''20%'' WRAP=''1''></field>
	    <field name=''ccol'' width=''5%'' WRAP=''0''></field>
	   <field name=''cvalue'' width=''5%'' WRAP=''0''></field>'
	   , @cFieldsDesc  = 'Формула|Документ|Таблица|Операция и код|Графа|Значение', @cOrderFields = 'ord', @cGroupFields = 'cGroup', @cGroupDesc = '<Org @cGroup>'
      
      INSERT #ks_protokol_HTML ([order], [type], [html])
      SELECT ISNULL((SELECT MAX([ORDER]) FROM  #ks_protokol_HTML WHERE [TYPE] <> 0), 0)+ [order], [type], [html]
      from #ks_protokol_HTML_Table
      ORDER BY [order]      
		continue
	end

	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], cOrderTable, cOrderCol, px_Comment, [property])
	select Ro.Link_Rule, 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, Ru.cols, Ru.[rows], '№' + isnull(ltrim(STR(RT.orders)),'') + ' (' + RTRIM(RT.Name) + ')', cOrderCol, px_Comment, [property]
	from report_control_rows Ro (NOLOCK) inner join #t_Rules Ru on Ro.Link_Rule = Ru.Link_Rule
		left join #t_Tables RT on Ro.Link_Table = RT.Link_Table
		left join #t_Col RC on RC.Link_Col = Ro.Link_Col

   DELETE #t_KS 
   WHERE Link_rule IN (SELECT  r.link_rule  FROM  #t_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))     

	update #t_KS
	set algorithm = 0
	where algorithm = 4	

	IF @cTables<>'' 
	begin
		set @execstr='DELETE FROM #t_KS WHERE Link_Rule in (SELECT Link_Rule FROM #t_KS TK WHERE TK.Link_Table not in ('+@cTables+') AND Tk.Link_Table is not NULL)'
		print @execstr
		exec(@execstr) 
	end 

	update #t_KS
	set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))  + ', ' + LTRIM(STR(@LinkSF))
	where val_type = 2
/*	update #t_KS
	set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
	where val_type = 2
*/

	-- константы для простых правил не будем учитывать, лсф для них не будем смотреть и в конце их прибавим
	insert #t_Factor (Link_Rule, OrderRow, [sign], part, factor)
	select Link_rule, OrderRow, [sign], part, case [sign] when '+' then K.Factor else -K.Factor end
	from #t_KS K
	where Val_Type = 1 and algorithm in (1,2,3,4)

	delete #t_KS
	where Val_Type = 1 and algorithm in (1,2,3,4)

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Размножение правил (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+20)/@countLSF))
		execute(@strProgressExec)
	end

	------------------------------------------------------------------------------------------
	exec dbo.RO_RAZMNOJ_KS_INSIDE -- размножение правил для фильтров и знака '^' и сложных правил
	------------------------------------------------------------------------------------------
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Формирование слагаемых для простых правил (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+25)/@countLSF))
		execute(@strProgressExec)
	end

	-- 	вычисляем правила
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, case when Val_Type <> 1 then coalesce(RS.Code, D.Code_Row, K.Code_Row, K.CodeRow, '') else dbo.rn_convert_number(K.Factor, @round, ' ') end, Filter_desc, part, 
					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, orderCol, CodeRow, REPLACE(px_Comment, '@@', RTRIM(RR.Dop_col))		 
	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 #t_Rows_Static RS on K.Link_Row = RS.Link_Row
		left join #t_Rows_Static RR on K.Link_Row = RR.Link_Row
		left join #report_dinamics D on D.Link_Col = K.Link_Col and D.Code_Row = K.Code_Row
	where algorithm = 1 -- простое правило

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование слагаемых для правил с диапозоном колонок'', percents = ' + str(convert(int, ((@orderLSF-1)*100+30)/@countLSF))
		execute(@strProgressExec)
	end

	delete #t_KS
	where algorithm = 1

	-- правило размножения для диапозона колонок 
	insert #t_Res_summand (Link_Rule, OrderRow, [sign],cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  Link_Rule, OrderRow, [sign], cOrderTable, isnull(RC1.corderCol, RC2.corderCol) as orr, coalesce(S.Code, K.Code_Row, ''), Filter_desc, part, 
					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 
					else 0
				end, isnull(RC1.orderCol, RC2.orderCol), CodeRow, REPLACE(px_Comment, '@@', RTRIM(RR.Dop_col))
	from #t_KS K left join #t_summa S on S.Link_Row = K.Link_Row
		left join #t_Rows_Static RR on K.Link_Row = RR.Link_Row
		left join #t_Col RC1 on S.link_col = RC1.link_col
		left join #report_dinamics D on D.Code_Row = K.Code_Row and D.Link_Table = K.Link_Table
		left join #t_Col RC2 on D.link_col = RC2.link_col
	where algorithm = 2 and (charindex(',' + rtrim(ltrim(str(isnull(RC1.orderCol,RC2.orderCol)))) + ',', ','+REPLACE(cols,' ', '')+',') > 0 or cols = '')
		and isnull(RC1.orderCol, RC2.orderCol) is NOT NULL

	-- дерево кбк
	insert #t_Res_summand (Link_Rule, OrderRow, [sign],cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  -K.Link_Self, 1, '+', K.cOrderTable, RC2.corderCol as orr, coalesce(K.Code_Row, ''), '', 1, 
					isnull(D.float_val, 0), RC2.orderCol, K.cOrderTable, ''
	from #TreeKBK K
	   LEFT JOIN  #TreeKBK K1 ON  K.Link_Self = K1.Link
		left join @t_TreeKBK_cols C on K.Link_Table = C.Link_Table
		left join #t_Col RC2 on RC2.Link_Table = K.Link_Table and (charindex(',' + rtrim(ltrim(str(RC2.orderCol))) + ',', ','+C.cols+',') > 0 or C.cols = '')
		left join #report_dinamics D on D.Code_Row = K.Code_Row and D.Link_Table = K.Link_Table AND D.link_col = RC2.link_col
	where exists(select top 1 * from #TreeKBK K2 where isnull(K.link_self,0) = K2.link)
	      AND NOT EXISTS(SELECT TOP 1 * FROM #TreeExclude E WHERE E.Code = K1.Code_Row AND (E.Link_Col = RC2.Link_Col OR E.Link_Col IS NULL))

	insert #t_Res_summand (Link_Rule, OrderRow, [sign],cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  -Link, 1, '+', cOrderTable, RC2.corderCol as orr, coalesce(K.Code_Row, ''), '', 0, 
				isnull(D.float_val, 0),  RC2.orderCol, cOrderTable, ''
	from #TreeKBK K 
		left join @t_TreeKBK_cols C on K.Link_Table = C.Link_Table
		left join #t_Col RC2 on RC2.Link_Table = K.Link_Table and (charindex(',' + rtrim(ltrim(str(RC2.orderCol))) + ',', ','+C.cols+',') > 0 or C.cols = '')
		left join #report_dinamics D on D.Code_Row = K.Code_Row and D.Link_Table = K.Link_Table AND D.link_col = RC2.link_col
	where calc = 0 AND NOT EXISTS(SELECT TOP 1 * FROM #TreeExclude E WHERE E.Code = K.Code_Row AND (E.Link_Col = RC2.Link_Col OR E.Link_Col IS NULL))


	---------------------
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование слагаемых для правил с диапозоном строк'', percents = ' + str(convert(int, ((@orderLSF-1)*100+35)/@countLSF))
		execute(@strProgressExec)
	end

	-- правило размножения для всех строк 
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, coalesce(RR.Code, D.Code_Row, ''), Filter_desc, part, 
					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 
					else 0
				end, orderCol, coalesce(RR.Code, D.Code_Row, ''), REPLACE(px_Comment, '@@', RTRIM(RR.Dop_col))
	from #t_KS K left join #t_Rows_Static RR on K.Link_Table = RR.Link_Table
		left join #t_summa S on S.Link_Col = K.Link_Col and RR.Link_Row = S.Link_Row
		left join #report_dinamics D on D.Link_Col = K.Link_Col
	where algorithm = 3

	-- диапозон строк 
	while exists(select top 1 * from #t_KS where algorithm  = 4 and Link_Rule > 0) --and (@i < 2)
	begin
		set @i = @i + 1
		select top 1 @LinkRule = Link_Rule,  @ExecStr = 'insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, RR.Code, Filter_desc, part, 
					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 
					else 0
				end, orderCol, RR.Code, REPLACE(px_Comment, ''@@'', RTRIM(RR.Dop_col))
	from (select * from #t_KS where Link_Rule = ' + STR(Link_Rule) + ') K left join #t_Rows_Static RR on K.Link_Table = RR.Link_Table
			left join #t_summa S on S.Link_Col = K.Link_Col and RR.Link_Row = S.Link_Row
	where ' + REPLACE([rows], 'COL(', 'dbo.RO_COL_Static('+ LTRIM(STR(@LinkSF)) + ', K.Link_Table, S.Link_Row,') + '
insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select  Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, RD.Code_Row, Filter_desc, part, 
					case Val_Type 
					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 
					else 0
				end, orderCol, RD.Code_Row, px_Comment
	from (select * from #t_KS where Link_Rule = ' + STR(Link_Rule) + ') K inner  join #report_dinamics RD on RD.Link_Col = K.Link_Col 
	where ' + REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,K.Link_Table, RD.Code_Row,')
		from #t_KS
		where algorithm = 4 and Link_Rule > 0
		
		execute(@ExecStr)
		update #t_KS set Link_Rule = -Link_Rule where Link_Rule = @LinkRule 
	end
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Проверка КС (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+45)/@countLSF))
		execute(@strProgressExec)
	end

	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow)
	select F.Link_Rule, F.OrderRow, F.[sign], '', '', convert(varchar(50), abs(F.factor)), '', F.part, F.factor, S.orderCol, S.CodeRow
	from #t_Factor F left join (select distinct Link_Rule, CodeRow, orderCol from #t_Res_summand) S on F.Link_Rule = S.Link_Rule 

	insert #t_Result ([Value], Link_Rule, part, algorithm, orderCol, CodeRow)	
	select case when isnull(IsDoschet, 0) & 16 = 0 then sum(Value) else abs(sum(Value)) end, S.Link_Rule, S.part, 0, S.orderCol, S.CodeRow
	from #t_Res_summand S left join #t_Rules R on S.Link_Rule = R.Link_Rule 
	group by S.Link_Rule, S.part, S.orderCol, S.CodeRow, R.IsDoschet


--	select * from #t_Res_summand

--	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
--	select abs(K.Link_Rule), K.OrderRow, K.[sign], K.cOrderTable,  case when isnull(K.cOrderCol, '') = '' then isnull(C.corderCol,'') else K.cOrderCol end , case when K.Code_Row = '' and K.Link_Row is NULL then S.CodeRow else case when val_type = 3 then K.Code_Row else R.Code end end, '', K.part, 0, S.orderCol, S.CodeRow, REPLACE(px_Comment, '@@', RTRIM(R.Dop_col))
--	from #t_KS K inner join (select distinct Link_Rule, orderCol, CodeRow from #t_Result) S on abs(K.Link_Rule) = S.Link_Rule 
--		left join #t_Col C on K.Link_Table = C.Link_Table and S.orderCol = C.orderCol
--		left join #t_Rows_Static R on (K.Link_Row = R.Link_Row and K.Link_Row is NOT NULL) or (K.Link_Row is NULL and S.CodeRow = R.Code and K.Link_Table = R.Link_Table)
--	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = abs(K.Link_Rule) and S1.OrderRow = K.OrderRow and isnull(S.CodeRow,'') = isnull(S1.CodeRow,'') and isnull(S.orderCol,0) = isnull(S1.orderCol,0))

--	delete #t_KS
--	where algorithm in (2, 3,4)

	insert #t_KS_difficalt
	select * from #t_KS where algorithm = 0

	set ansi_warnings OFF
    SET ARITHABORT OFF
    SET ARITHIGNORE OFF

	print 'qqq'
	-- хранимки - теперь только одна хранимка в одном правиле!!!
	while exists(select top 1 * from #t_KS where algorithm = 9 and Val_Type = 2 AND Link_Rule > 0)
	begin
		select top 1 @LinkRule = Link_Rule, @nvExecStr = Exec_Proc, @CodeRow = CodeRow
		from #t_KS
		where algorithm = 9 and Val_Type = 2 AND Link_Rule > 0
      

		select @ord = max(ord) from #Res
	
   --	print @ExecStr
   
		insert #tmp 
      exec sp_executesql @nvExecStr, N'@CodeRow varchar(50)', @CodeRow = @CodeRow

      UPDATE #t_ks
      SET VALUE = (select top 1 Value from #tmp)
      WHERE @LinkRule = Link_Rule and Val_Type = 2 AND  @CodeRow = CodeRow

      DELETE #tmp            

		update #Res set cGroup = @cGroup where ord > @ord
		
		UPDATE #t_KS SET Link_Rule = -Link_Rule where Link_Rule = @LinkRule AND  @CodeRow = CodeRow
	END


   --DELETE #t_KS WHERE [algorithm] = 9 AND NOT EXISTS(SELECT * FROM #t_KS K WHERE K.Link_Rule = #t_KS.Link_Rule AND Val_Type IN (0, 3)) 


   UPDATE #t_KS
   SET Link_Rule = ABS(Link_RULE) 

	insert #t_KS_difficalt
	select K.Link_Rule, K.OrderRow, K.val_type, K.[sign], K.Link_Table, K.Link_Col, K.Link_Row, D.Code_Row, K.Factor, K.px, K.Exec_Proc, K.Filter,
            K.Filter_desc, K.Mask, K.part, K.algorithm, K.cols, K.[rows], K.[Value], K.orderCol, D.Code_Row,K.cOrderTable, K.cOrderCol, K.px_Comment, K.[property] 
   from #t_KS K LEFT JOIN (SELECT distinct Link_Table, Code_Row FROM #report_dinamics) D ON K.[Link_Table] = D.[Link_Table] 
   where K.algorithm = 9 AND K.Val_Type = 3 AND K.Code_Row = '' 

	insert #t_KS_difficalt
	select K.Link_Rule, K.OrderRow, K.val_type, K.[sign], K.Link_Table, K.Link_Col, K.Link_Row, '', K.Factor, K.px, K.Exec_Proc, K.Filter,
            K.Filter_desc, K.Mask, K.part, K.algorithm, K.cols, K.[rows], K.[Value], K.orderCol, D.CodeRow,K.cOrderTable, K.cOrderCol, K.px_Comment, K.[property]
   from #t_KS K JOIN (SELECT distinct Link_Rule, CodeRow FROM #t_KS_difficalt) D  ON K.Link_Rule = D.Link_Rule
   where algorithm = 9 AND Val_Type = 2   

	insert #t_KS_difficalt
	select *
   from #t_KS K  
   where algorithm = 9 AND NOT EXISTS(SELECT * FROM #t_KS_difficalt D WHERE K.Link_Rule = D.Link_Rule)   
   
    set ansi_warnings ON
    SET ARITHABORT ON
    SET ARITHIGNORE ON

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Проверка сложных правил (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+55)/@countLSF))
		execute(@strProgressExec)
	END
   
	-------------------------------------------------------------------------------------------
	-- деление и умножение и т.д.

	update #t_KS_difficalt
	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,
			Code_Row = case K.Val_Type when 0 then R.Code WHEN 3 THEN  K.Code_Row WHEN 1 THEN '' ELSE (SELECT Exec_Proc_Desc FROM dbo.report_control_rows R WHERE R.link_rule =  K.[Link_Rule] AND R.[OrderRow] = K.[OrderRow]) end
	from #t_KS_difficalt K
		left join #t_summa RS on K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #t_Rows_Static R on R.Link_Row = K.Link_Row
		left join #report_dinamics RD on K.Link_Col = RD.Link_Col and RD.Code_Row = K.Code_Row


   
	update #t_KS_difficalt
	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,
			Code_Row = case K.Val_Type when 0 then R.Code WHEN 3 THEN  K.Code_Row WHEN 1 THEN '' ELSE (SELECT Exec_Proc_Desc FROM dbo.report_control_rows R WHERE R.link_rule =  K.[Link_Rule] AND R.[OrderRow] = K.[OrderRow]) end
	from #t_KS_difficalt K
		left join #t_summa RS on K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #t_Rows_Static R on R.Link_Row = K.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_difficalt K
	where CodeRow = '' and exists(select top 1 * from #t_KS_difficalt K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')

	delete #t_KS_difficalt
	from #t_KS_difficalt K
	where CodeRow = '' and exists(select top 1 * from #t_KS_difficalt K2 where K.Link_Rule = K2.Link_Rule and CodeRow <> '')

	-- операнды для вывода в протокол
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow)
	select Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow
	from #t_KS_difficalt

	-- и для вычисления нужно добавть операнды, которые не размножились
	insert #t_KS_difficalt
	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, '', [property]
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow from #t_KS_difficalt) S on K.Link_Rule = S.Link_Rule and (K.orderCol = 0 or K.orderCol = S.orderCol)
	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = K.Link_Rule and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- операнды для вывода в протокол
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow)
	select K.Link_Rule, K.OrderRow, K.[sign], K.cOrderTable, K.cOrderCol, Code_Row, '', K.part, K.Value, S.orderCol, S.CodeRow	
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow from #t_KS_difficalt) S on K.Link_Rule = S.Link_Rule  and (K.orderCol = 0 or K.orderCol = S.orderCol)
	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = K.Link_Rule and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- левая часть
	insert #t_Result ([Value], Link_Rule, part, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, part, orderCol, CodeRow
	from #t_KS_difficalt K
	where OrderRow = 1
	
	set @maxOrderRow = isnull((select max(orderRow) from #t_KS_difficalt where part = 0),0)
	set @i = 2
	
	while @i<=@maxOrderRow
	begin
		update #t_Result
		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 R, #t_KS_difficalt 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
	-- правая часть
	delete #t_KS_difficalt where part = 0


	update #t_KS_difficalt
	set OrderRow = OrderRow - OrRow + 1
	from #t_KS_difficalt K, (select min(OrderRow) as OrRow, Link_Rule from #t_KS_difficalt K1 where  part = 1 group by Link_Rule) K2
	where K.Link_Rule = K2.Link_Rule

	insert #t_Result ([Value], Link_Rule, part, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, part, orderCol, CodeRow
	from #t_KS_difficalt K
	where OrderRow = 1
	
	set @maxOrderRow = isnull((select max(orderRow) from #t_KS_difficalt ),0)
	set @i = 2



	while @i<=@maxOrderRow
	begin

		update #t_Result
		set Value = case [sign] when '*' then convert(float,R.Value) * convert(float,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 R, #t_KS_difficalt 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,'') and R.part = 1

		set @i = @i + 1
	END
	

	--------------------------------------------------------------------------------------------------------
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = LEFT(''Запись в протокол (' +  RTRIM(@cOrg) + ',' + @cBudg + ')'',100), percents = ' + str(convert(int, ((@orderLSF-1)*100+85)/@countLSF))
		execute(@strProgressExec)
	end

	-- запись в протокол

	
   update R
   SET R.Value = ROUND(convert(NUMERIC(20,5), R.Value), case when C.val_len > 4 THEN 0 ELSE C.val_len END )
   from #t_Result R JOIN #t_KS_difficalt D ON R.[Link_Rule] = D.[Link_Rule]
         JOIN #t_Col c ON D.[Link_Col] = C.[Link_Col] AND C.col_TYPE = 0

--	set Value = round(convert(numeric(20,5),Value), @round)

 
	--print 'time ' + convert(varchar(10), getdate() - @time_begin, 108)
	insert #t_Result_sr (Link_Rule, CodeRow, orderCol, error, LeftPart, RightPart, Str_Rule, Comment, OrderRule, sign_sr)	
	select isnull(L.Link_Rule,R.Link_Rule), isnull(L.codeRow, R.codeRow), isnull(L.orderCol, R.orderCol), case isnull(Ru.[sign_sr], '=')
			when '=' then case when abs(isnull(round(convert(numeric(20,5),L.Value), @round),0) - isnull(round(convert(numeric(20,5),R.Value), @round),0)) < @nprecision then 0 else 1 end
			when '>' then case when isnull(round(convert(numeric(20,5),L.Value), @round),0) - isnull(round(convert(numeric(20,5),R.Value), @round),0) > @nprecision then 0 else 1 end
			when '<' then case when isnull(round(convert(numeric(20,5),R.Value), @round),0) - isnull(round(convert(numeric(20,5),L.Value), @round),0) > @nprecision then 0 else 1 end
			when '>=' then case when isnull(round(convert(numeric(20,5),L.Value), @round),0) - isnull(round(convert(numeric(20,5),R.Value), @round),0) > -@nprecision then 0 else 1 end
			when '<=' then case when isnull(round(convert(numeric(20,5),R.Value), @round),0) - isnull(round(convert(numeric(20,5),L.Value), @round),0) > -@nprecision then 0 else 1 end
			when '<>' then case when abs(isnull(round(convert(numeric(20,5),L.Value), @round),0) - isnull(round(convert(numeric(20,5),R.Value), @round),0)) > @nprecision then 0 else 1 end
		end as error, isnull(round(convert(numeric(20,5),L.Value), @round),0), isnull(round(convert(numeric(20,5),R.Value), @round),0), case when isnull(L.Link_Rule,R.Link_Rule) < 0 then 'Досчет по дереву КБК' else Str_Rule end, Comment, OrderRule, isnull(sign_sr, '=')
	from (select * from #t_result where part = 0) L
		full join (select * from #t_result where part = 1) R on L.Link_Rule = R.Link_Rule  and isnull(L.orderCol,0) = isnull(R.orderCol,0) and RTRIM(isnull(L.CodeRow,'')) = RTRIM(isnull(R.CodeRow,''))
		left join #t_Rules Ru on isnull(L.Link_Rule,R.Link_Rule) = Ru.Link_Rule
--	order by isnull(L.Link_Rule,R.Link_Rule),isnull(L.codeRow, R.codeRow), isnull(L.orderCol, R.orderCol)
	if @varKSiNotAllRules = 0 -- если 1, то нужно показать досчет этой ячейки
		delete #t_Result_sr where error = 0
	else BEGIN
		delete R
		from #t_Result_sr R
		where Link_Rule > 0 and not exists(select top 1 * from #t_Rules_Result res where R.CodeRow = Res.CodeRow and R.orderCol = Res.orderCol)

		delete R
		from #t_Result_sr R 
		where R.Link_Rule < 0 and not exists(select top 1 * from #t_Res_Summand S where S.Link_Rule = R.Link_Rule and exists(select top 1 * from #t_Rules_Result res where S.Code_Row = Res.CodeRow and R.orderCol = Res.orderCol ))
	
		if @varKSiNotAllRules = 2 -- если 1, то нужно показать досчет этой ячейки
			delete #t_Result_sr where error = 0
		else
			delete R
			from #t_Result_sr R 
			where R.Link_Rule < 0 and not exists(select top 1 * from #t_Res_Summand S where part = 0 and S.Link_Rule = R.Link_Rule and exists(select top 1 * from #t_Rules_Result res where S.Code_Row = Res.CodeRow and R.orderCol = Res.orderCol ))
	end

	insert #t_Res_summand (Link_Rule, OrderRow, [sign], cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_Comment)
	select abs(K.Link_Rule), K.OrderRow, K.[sign], K.cOrderTable,  case when isnull(K.cOrderCol, '') = '' then isnull(C.corderCol,'') else K.cOrderCol end , case when K.Code_Row = '' and K.Link_Row is NULL then S.CodeRow else case when val_type = 3 then K.Code_Row else R.Code end end, '', K.part, 0, S.orderCol, S.CodeRow, REPLACE(px_Comment, '@@', RTRIM(R.Dop_col))
	from #t_KS K inner join (select distinct Link_Rule, orderCol, CodeRow from #t_Result) S on abs(K.Link_Rule) = S.Link_Rule 
		left join #t_Col C on K.Link_Table = C.Link_Table and S.orderCol = C.orderCol
		left join #t_Rows_Static R on (K.Link_Row = R.Link_Row and K.Link_Row is NOT NULL) or (K.Link_Row is NULL and S.CodeRow = R.Code and K.Link_Table = R.Link_Table)
	where K.Link_Rule in (select SR.Link_Rule from  #t_Result_sr SR) and
		not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = abs(K.Link_Rule) and S1.OrderRow = K.OrderRow and isnull(S.CodeRow,'') = isnull(S1.CodeRow,'') and isnull(S.orderCol,0) = isnull(S1.orderCol,0))
		

--	print 'time ' + convert(varchar(10), getdate() - @time_begin, 108)


	declare @nastr_del_nul_slag varchar(10)
	set @nastr_del_nul_slag='0'
	exec X_GET_OPTION 'RA_REP_OPTIONS_COM_DEL_P_KS',0,@nastr_del_nul_slag output
	set @nastr_del_nul_slag = isnull(@nastr_del_nul_slag, '0')

	exec RO_CHECK_KS_INSIDE_TABLE_PROTOKOL @LSF, @round, @cProgressTable, @liError output


	insert #Res (orders, res, cDoc, cKod, cTable, cCol, cValue, cGroup)
		select orders, isnull(res,''), isnull(cDoc,''), isnull(cKod,''), isnull(cTable,''), isnull(cCol, ''), isnull(cValue, ''), @cGroup from
		(select orders, case orders when 1 then isnull('№' + LTRIM(STR(OrderRule)),'+') else '' end as Res,
			case orders when 1 then Str_Rule when 6 then 'Результат слева' when 7 then 'Результат справа' when 8 then 'Отклонение' else '' end as cDoc, 
			 case orders when 1 then isnull(Comment, '') when 3 then sign_sr else '' end as cKod, '' as cTable, '' as cCol, case orders when 6 then ltrim(dbo.rn_convert_number(LeftPart,@round, ' ')) when 7 then ltrim(dbo.rn_convert_number(RightPart,@round,' ')) when 8 then '<font color="#ff0000">' + ltrim(dbo.[rn_convert_number](LeftPart-RightPart,@round,' ')) else '' end as cValue, orderCol, codeRow, isnull(OrderRule, S.Link_Rule) as OrderRule,  0 as OrderRow
		from #t_Result_sr S left join @t on 1 = 1
		union all
		select 2 + part * 2, '', @codeForm, [sign] + case when S.Code_Row = 'нет строк' then S.Code_Row + ' для фильтра ' + Filter_desc else S.Code_Row end + isnull(px_comment,''), cOrderTable, cOrderCol, ltrim(dbo.[rn_convert_number](Value, @round, ' ')), S.orderCol, S.codeRow, isnull(OrderRule, S.Link_Rule), OrderRow
		from #t_Res_summand S inner join #t_Result_sr R on S.Link_Rule = R.Link_Rule and S.CodeRow = R.CodeRow and S.orderCol = R.orderCol
		where abs(S.[Value]) > 0.0001 or @nastr_del_nul_slag='0') A
		order by OrderRule, orderCol, codeRow, orders, OrderRow

	select @liError = @liError  + count(*) from #res where cDoc = 'Отклонение' or cdoc like '%Шифр строки%' OR cDoc = 'Невидимая ошибка' 
    DELETE #res WHERE cDoc = 'Невидимая ошибка'
      
	set @CountError = @CountError + @liError -- общее количество ошибок

	if @liError = 0
	BEGIN
		insert #Res (cDoc, cGroup)
		select 'Проверка выполнена успешно', @cGroup
		delete @t_temp
		if @varKSiNotAllRules = 0 and (@cTables = '' or (select count(*) from #t_Tables) = (select count(*) from report_tables where Link_Form = @LinkF)) 
         AND (EXISTS(SELECT TOP 1 * FROM #t_Summa WHERE [summa] <> 0) OR EXISTS(select * from #report_dinamics WHERE [float_val] <> 0 ))-- у отчета есть данные
		begin
			update report_saved_forms
			set IsRightKS = 1
			where link_saved_form = @LinkSF
		end
		truncate table #t_KS
		truncate table #t_Rules
		truncate table #t_Result_sr
		truncate table #t_Summa
		truncate table #report_dinamics
		truncate table #t_Col
		truncate table #t_Rows_Static
		truncate table #t_Res_summand
		truncate table #t_Result	
		truncate table #t_Factor
		truncate table #t_Tables
		truncate table #t_KS_difficalt
	end
	else begin
		if @varKSiNotAllRules = 0
			update report_saved_forms
			set IsRightKS = 2
			where link_saved_form = @LinkSF
	END
    SET @cDataDesc = 'Форма: ' + @codeForm + ' Период: ' + @cPeriod + ' Организация: ' + @cOrg + ' Бюджет: ' + isnull(@cBudg, '') 

	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = @cDataDesc, @cDataTableName  = '#res',@cShowFields  = 
	'<field name=''res'' width=''5%'' WRAP=''1''></field>
	 <field name=''cdoc'' width=''40%'' WRAP=''1''></field>
	 <field name=''ctable'' width=''25%'' WRAP=''0''></field>
	 <field name=''ckod'' width=''20%'' WRAP=''1''></field>
	 <field name=''ccol'' width=''5%'' WRAP=''0''></field>
	<field name=''cvalue'' width=''5%'' WRAP=''0''></field>'
	, @cFieldsDesc  = 'Формула|Документ|Таблица|Операция и код|Графа|Значение', @cOrderFields = 'ord', @cGroupFields = 'cGroup', @cGroupDesc = '<Org @cGroup>'
   
   INSERT #ks_protokol_HTML ([order], [type], [html])
   SELECT ISNULL((SELECT MAX([ORDER]) FROM  #ks_protokol_HTML WHERE [TYPE] <> 0), 0)+ [order], [type], [html]
   from #ks_protokol_HTML_Table
   ORDER BY [order]

--	if @Statistics = 1
--	begin
--		set @time_end = getdate()
--		insert dbo.REPORT_STATISTICS (Operation, CodeForm, Reads, Duration) 
--		select Operation = 1, 
--				CodeForm = @CodeForm, 
--				Reads = isnull((select count(*) from #t_KS), 0) + isnull((select count(*) from #t_Rules), 0) + isnull((select count(*) from #t_Summa), 0) + isnull((select count(*) from #report_dinamics), 0),
--				Duration = @time_end - @time_begin
--	end
--


end

set @time_end = getdate()

update #ks_protokol_HTML
set html = REPLACE(REPLACE(html, '<COUNTERROR>', LTRIM(RTRIM(STR(@CountError)))), '<RUNTIME>', convert(varchar(10), @time_end - @time_begin, 108))
where html like '%<COUNTERROR>%'

--select isnull(res,'') res,isnull(cdoc,'') cdoc,isnull(ctable,'') ctable,isnull(ckod,'') ckod,isnull(ccol,'') ccol,isnull(cvalue,'') value from #Res 

IF @tmpTable<>''
begin
	set @ExecStr='insert '+@tmpTable+' select res,cdoc,ctable,ckod,ccol,cvalue from #Res '
	execute(	@ExecStr)
end
else begin
	if ((select count(*) from #Res) > 10000 and @typeProtokol = 0) or @typeProtokol = 1
	begin
			select res,cdoc,ctable,ckod,ccol,cvalue value from #Res order by ord
	end
	else
	begin
		select * from #ks_protokol_HTML order by [order]
	end
end

drop table #t_Factor
drop table #t_Col
drop table #t_KS
drop table #t_Rules
drop table #t_Result
drop table #Res
drop table #ListForms
drop table #t_Rows_Static
drop table #tmp
drop table #t_Result_sr
drop table #t_Res_summand
drop table #report_dinamics
drop table #t_Summa
drop table #t_Tables
drop table #t_LSF
drop table #t_rules_group_ks
drop table #ks_protokol_HTML
drop table #ks_protokol_HTML_Table
drop table #t_Rules_region
drop table #t_Pr_Form
drop table #t_KS_difficalt
DROP TABLE #TreeKBK
DROP TABLE #TreeExclude   


--select * from #Rules

--drop table #Rules
GO
GRANT EXECUTE ON dbo.[RO_CHECK_KS_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.[SA_N_VAC_FILL2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_VAC_FILL2]

GO

CREATE      PROCEDURE dbo.SA_N_VAC_FILL2 
--- Расчет отпускных по постановлению 562 для госслужащих
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @OBJ_CODE VARCHAR(50), --Код объекта
 @SR_VID TINYINT = 1, -- Прочие расчеты по среднему 1 - Компенсация за отпуск, 2 - прочее
 @LINK_VAC INT, --Ссылка на приказ
 @SR_LINK_EMPL INT  = NULL, --Прочие расчеты по среднему  Ссылка на сотрудника
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT  = NULL, --Тип расчетного периода: 1- 3 месяца, 2 - 12 месяцев
 @PAYMENT TINYINT  = NULL,-- Способ расчета 1 - в рабочих днях, 2 - в календарных днях
 @SR_DATE1 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала
 @SR_DATE2 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата окончания
 @SR_DATE DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала расчетного периода
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции,
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

SET @PAYMENT = 2 -- Расчет строго в календарных днях
-- Определение типа расчетного периода
SET @TYP_PERIOD = CASE WHEN COALESCE(@TYP_PERIOD,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT2')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT1')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 1
				ELSE NULL
			END
		ELSE @TYP_PERIOD END

SET @TYP_PERIOD = 2 --Строго 12 месяцев

-- Определение способа расчета
SET @PAYMENT = CASE WHEN COALESCE(@PAYMENT,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT3')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT2')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 2
				ELSE NULL
			END
		ELSE @PAYMENT END

---инит
DECLARE 
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало отпуска, командировки
 @DATE_BEGIN2 DATETIME, --Начало отпуска, командировки
 @DATE_END DATETIME, --Окончание отпуска, командировки
 @REF_TYP INT, --Ссылка на вид отпуска, командировки
 @order_link int, 
 @NEW_DATE_END DATETIME,
 @NEW_DATE_BEG DATETIME,
 @UCHET_PREM TINYINT,
 @comment varchar(100),
 @HOLIDAY TINYINT

DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN COALESCE(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@DATE_BEGIN = DATE_BEGIN,
		@SR_DATE = COALESCE(@SR_DATE, (select min(DATE_BEGIN) from dbo.ITEM_VACATION IV1 WHERE IV1.order_link = IV.order_link and IV1.EMPL_LINK = IV.EMPL_LINK)), 
		@DATE_END = DATE_END,
		@REF_TYP = IV.TYPE_LINK, @order_link = order_link,
		@comment = @UNAME + 'Начисл.отпускных:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(VV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@HOLIDAY = VV.HOLIDAY, --С учетом праздничных,
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_VACATION IV ON IV.ORDER_LINK = O.LINK
		INNER JOIN dbo.VACATION_VID VV ON IV.TYPE_LINK = VV.LINK WHERE IV.LINK = @LINK_VAC

	DECLARE	@DATE_BREAK DATETIME	-- дата отзыва из отпуска
	DECLARE	@DATE_BREAK_NEW_BEGIN DATETIME	-- дата отзыва из отпуска

	-- Уменьшение: об отзыве, о выходе из отпуска по уходу за ребенком
	IF EXISTS(SELECT * FROM ITEM_VACATION_BREAK IVB WHERE IVB.ACTIVE = 1 AND ISNULL(BREAK_WORK_DAYS,0) != 0 AND IVB.VAC_LINK = @LINK_VAC) BEGIN

		DECLARE @BREAK_WORK_DAYS INT	-- количество рабочих дней отзва
		DECLARE @LEN_KAL_DAYS INT	-- количество календарных дней продления
		DECLARE @EMPL_LINK INT		-- ссылка на сотрудника
		--
		SELECT	TOP 1
			@EMPL_LINK = EMPL_LINK,
			@DATE_BREAK = DATE_BREAK,
			@BREAK_WORK_DAYS = BREAK_WORK_DAYS,
			@LEN_KAL_DAYS = LEN_KAL_DAYS
		FROM	ITEM_VACATION_BREAK IVB
		WHERE	IVB.ACTIVE = 1
			AND ISNULL(BREAK_WORK_DAYS,0) != 0
			AND IVB.VAC_LINK = @LINK_VAC
		--
		SET ROWCOUNT @BREAK_WORK_DAYS
		SELECT	T.DATE
		INTO	#TEMP_TABLE
		FROM
		(
		SELECT	[DATE]  = dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)),
			[HOURS] = MAX(HOURS)
		FROM	GRAPHICS G INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE	G.GRAPH_LINK = dbo.kd_GetEmplGr(@EMPL_LINK)
			AND dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)) BETWEEN @DATE_BREAK AND @DATE_BREAK + @BREAK_WORK_DAYS + @LEN_KAL_DAYS
		GROUP	BY dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD))
		) T
		WHERE	T.HOURS > 0
			AND T.DATE >= @DATE_BREAK
		SET ROWCOUNT 0
		--
		SET @DATE_BREAK_NEW_BEGIN = (SELECT TOP 1 DATE + 1 FROM #TEMP_TABLE ORDER BY DATE DESC)
		SET @NEW_DATE_END = @DATE_BREAK_NEW_BEGIN + @LEN_KAL_DAYS - 1
	
		DROP TABLE #TEMP_TABLE
		SET @DATE_END = COALESCE(@NEW_DATE_END,@DATE_END)
	END 
	ELSE BEGIN
		SET @NEW_DATE_END = (SELECT MIN(ivb.DATE_BREAK - 1) FROM dbo.item_vacation iv inner join dbo.item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
		SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) <  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)
	END
	-- Увеличение: о продлении по болезни
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE  ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)
END

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL'
BEGIN
	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@SR_DATE = COALESCE(@SR_DATE, DATE_BEGIN), 
		@DATE_BEGIN = DATE_BEGIN, @DATE_END = DATE_END, 
		@REF_TYP = IT.TYPE_LINK,
		@comment = @UNAME + 'Начисл.командир.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.item_travel IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN dbo.KOMAND_VID KV ON IT.TYPE_LINK = KV.LINK WHERE IT.LINK = @LINK_VAC

	-- Увеличение: о продлении 
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END

DECLARE @PDAY NUMERIC(5,2)
SET @PDAY = 0	

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG' 
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, 
		@SR_DATE = COALESCE(@SR_DATE, DIS_DATE), 
		@DATE_BEGIN = DIS_DATE, 
		@DATE_END = DIS_DATE + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@PDAY = CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN VAC_KOMPENS_DAY - CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@REF_TYP = IT.REASON,
		@comment = @UNAME + 'Компенс.за неисп.отпуск:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_DIS_FACE IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN [dbo].[DICTION] KV ON IT.REASON = KV.LINK 
	WHERE IT.LINK = @LINK_VAC AND ISNULL(VAC_KOMPENS_DAY,0) > 0

	IF @LINK_EMPL IS NULL
		SELECT @LINK_EMPL = @SR_LINK_EMPL, @comment = @UNAME + 'Начисл.средн.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(P.[NAME])),30)
		FROM dbo.PAYS P WHERE LINK = @LINK_PAYS

	SELECT @LINK_DEP = DEP_LINK FROM DBO.USER_DEP WHERE @LINK_DEP IS NULL

END


--- Учет премии в расчете
IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' 
	OR @OBJ_CODE = 'DOCUMENTS_CALC_TRAVEL' 
	OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT8'),1)
ELSE
	SET @UCHET_PREM = 0

---

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,
 @NO_RAION TINYINT

SET @RP = (CASE @TYP_PERIOD WHEN 1 THEN 3 WHEN 2 THEN 12 ELSE 0 END)

SELECT TOP 1 
 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = DEP_LINK, 
 @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), 
 @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN), 
 @MAX_DATE = '29990101',
 @NO_RAION = ISNULL(NO_RAION,0)
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

declare @EmplNumStake numeric(5,2)
Set @EmplNumStake = Coalesce(dbo.ku_GetEmplNumStake(@LINK_EMPL,DEFAULT),0)

DECLARE @MINROT NUMERIC(18,2)

	SET @MINROT = dbo.minrot2(@DATE_BEGIN) * @EmplNumStake

---Определение расчетного периода
IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
	SELECT @DATE_BEGIN_RP = @SR_DATE, @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)), @DATE_BEGIN = @SR_DATE1, @DATE_END = @SR_DATE2, @LINK_EMPL = @SR_LINK_EMPL
ELSE
	SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > @SR_DATE THEN @DATE_BEGIN_RP ELSE @SR_DATE END),
	@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) END ),
	@SR_VID = 1

--- Если новый расчет, то получить линк документа
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME
IF COALESCE(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, @OBJ_CODE
	SET @DATE_DOC = (Select top 1 WORKDATE from USER_DATES)
	exec dbo.SD_N_VACATION_SAVE @LINK_DOC OUT,@OBJ_CODE, @NUMBER, @DATE_DOC, @LINK_PAYS, @comment, 0, @LINK_EMPL, 0, 0, @TYP_PERIOD, 
			@DATE_BEGIN, @DATE_END, 0, @PAYMENT, @LINK_VAC, 0, @SR_VID, @DATE_BEGIN_RP, @LINK_DEP
END
ELSE
	SET @DATE_DOC = (SELECT [DATE] FROM DBO.SDOC WHERE LINK = @LINK_DOC)

--
UPDATE dbo.SDOC_AVAC 
SET INSTR = 2
WHERE LINK_UP = @LINK_DOC

--
IF @RECALC <= 1  --- Расчет сумм по видам начислений
BEGIN
	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME,
		KOEF  NUMERIC(18,4),
		SUMMA_CL NUMERIC(18,2),
		p tinyint
	)


	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)

	DECLARE @FURLOUGH_GOS_OPT1 int --Премия включается в размере 1/12 от каждой выплаты
	SET @FURLOUGH_GOS_OPT1 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT1')

	DECLARE @FURLOUGH_GOS_OPT2 int --Материальная помощь включается в размере 1/12 от каждой выплаты
	SET @FURLOUGH_GOS_OPT2 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT2')

	DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
	SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
	IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
		SET @DOCUMENTS_RECALC_OPT1 = 1

	IF @RECALC = 0 BEGIN
		--Собираем материальную помощь за расчетный период
		INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, LINK_VKR, DATE1, DATE2, p)
		Select 
			PERIOD_BEGIN = CASE WHEN COALESCE(R.LINK_UP,0) = 0 THEN dbo.DateBeginOfMonth(PERIOD_BEGIN) ELSE dbo.DateBeginOfMonth(DATE1) END,
			CODE_PAY = SJ.CODE_PAYS,
			NAME_PAY = SJ.NAME_PAYS,
			WAY_CALC = SJ.WAY_CALC,
			LINK_PAY = SJ.LINK_PAYS,
			SUMMA = SUM(SJ.SUMMA),
--			SUMMA = CASE SJ.WAY_CALC
--					WHEN 6 THEN (CASE WHEN @FURLOUGH_GOS_OPT1 = 1 THEN ROUND(SUM(SJ.SUMMA)/12,2) ELSE SUM(SJ.SUMMA) END) 
--					WHEN 7 THEN (CASE WHEN @FURLOUGH_GOS_OPT1 = 1 THEN ROUND(SUM(SJ.SUMMA)/12,2) ELSE SUM(SJ.SUMMA) END) 
--					WHEN 12 THEN (CASE WHEN @FURLOUGH_GOS_OPT2 = 1 THEN ROUND(SUM(SJ.SUMMA)/12,2) ELSE SUM(SJ.SUMMA) END) 
--				END,
			LINK_VKR = COALESCE(LINK_VKR,@DEFAULT_KBK),
			DATE1, 
			DATE2,
			1
		from dbo.S_J_C_Short SJ
			INNER JOIN dbo.group_pays(@LINK_PAYS) T ON SJ.link_PAYS=T.PAY_LINK
			--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
			LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
		where 
			SJ.LINK_EMPL = @LINK_EMPL	
			AND (CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN PERIOD_BEGIN ELSE DATE1 END) >= @DATE_BEGIN_RP
			AND (CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2  THEN PERIOD_END ELSE DATE2 END) <= @DATE_END_RP
			AND SJ.WAY_CALC in (6,7,12)--Премия и материальная помощь
		GROUP BY 
			CASE WHEN COALESCE(R.LINK_UP,0) = 0 THEN dbo.DateBeginOfMonth(PERIOD_BEGIN) ELSE dbo.DateBeginOfMonth(DATE1) END,
			SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.WAY_CALC, SJ.LINK_PAYS, COALESCE(LINK_VKR,@DEFAULT_KBK), DATE1,  DATE2				
	END

	--Денежное содержание служащего

	DECLARE @DATE_BEGIN_RP_OLD DATETIME
	SELECT @DATE_BEGIN_RP_OLD = @DATE_BEGIN_RP

	SET @DATE_BEGIN_RP = dbo.DateBeginOfMonth(@DATE_BEGIN)

	INSERT INTO #BASE1 (PERIOD, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, LINK_VKR, DATE1, DATE2, p)
	select @DATE_BEGIN_RP, P.CODE, P.NAME, P.WAY_CALC, S.LINK_PAY, S.SUMMA, S.LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN), 0  
	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 
		WAY_CALC not in (6, 7, 12)
		AND
		s.link_pay IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)

	SELECT @DATE_BEGIN_RP = @DATE_BEGIN_RP_OLD



	---
	UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL

	---
	DECLARE @FURLOUGH_OPT11 int -- Расчет с учетом районного коэффициента
	--Если у сотрудника указано "Не начислять районный", то рассчитываем без районного
	SET @FURLOUGH_OPT11 = (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('FURLOUGH_OPT11') END)

	DECLARE @FURLOUGH_GOS_OPT4 varchar(10) --Дата применения районного коэффициента к мат. помощи
	SET @FURLOUGH_GOS_OPT4 = COALESCE((SELECT VALUE FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('FURLOUGH_GOS_OPT4'))) AND SID IS NULL),'')
	SET @FURLOUGH_GOS_OPT4 = CASE WHEN @FURLOUGH_GOS_OPT4 LIKE '%.  .%' THEN '' ELSE @FURLOUGH_GOS_OPT4 END

	SET @FURLOUGH_GOS_OPT4 = CASE WHEN LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) = '' THEN '01.01.1900' else LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) END

	----
	UPDATE #BASE1
	SET SUMMA_CL = SUMMA

	---Накручиваем районный коэффициент, если надо

	UPDATE #BASE1
	SET SUMMA = COALESCE(SUMMA_CL,0) *
			CASE WHEN WAY_CALC = 12
			THEN (CASE WHEN PERIOD >= CONVERT(DATETIME,@FURLOUGH_GOS_OPT4,104) THEN 1 + DBO.SA_GET_REGION(@LINK_EMPL,PERIOD,1) / 100 ELSE 1 END) 
			ELSE 1 + DBO.SA_GET_REGION(@LINK_EMPL,PERIOD,1) / 100
			END
	WHERE 
		@FURLOUGH_OPT11 = 1	

	---Накручиваем северный коэффициент, если надо
	DECLARE @FURLOUGH_GOS_OPT5 int -- Расчет с учетом северного коэффициента
	SET @FURLOUGH_GOS_OPT5 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT5')

	IF @FURLOUGH_GOS_OPT5 = 1 BEGIN
		DECLARE @NORTH_KOEF NUMERIC(6,2)
		SET @NORTH_KOEF = DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEGIN,2) / 100
	
		UPDATE #BASE1
		SET SUMMA = COALESCE(SUMMA,0) + COALESCE(SUMMA_CL,0) * @NORTH_KOEF
		WHERE @NORTH_KOEF > 0
	END

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @KBK_OPT TINYINT
	IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
		SET @KBK_OPT = dbo.sa_get_option_by_code('FURLOUGH_OPT7')
	ELSE			
		SET @KBK_OPT = 0

	IF @RECALC = 0 BEGIN
		---
		Select PERIOD = MAX(PERIOD), PERIOD1 = (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
			summa = SUM(SUMMA), KOEF= 1, LINK_VKR = (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 
		INTO #BASE
		from #BASE1 
		where p = 1
		group by (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 

		-- Перевенем таблицу 
		DECLARE @PAYS_MONTS VARCHAR(100)
		EXEC X_GET_TABLE_NAME @PAYS_MONTS OUTPUT

		---
		EXEC M_CROSS_TABLE
			'LINK_PAY, LINK_VKR',
			'PERIOD1', 'INT',
			'SUMMA', 'NUMERIC(18,2)', 'SUM(SUMMA) AS SUMMA',
			'#BASE', @PAYS_MONTS

		DECLARE @PAYS_MONTS1 VARCHAR(100)
		SET @PAYS_MONTS1 = @PAYS_MONTS + '1'

		EXEC M_CROSS_TABLE
			'LINK_PAY, LINK_VKR',
			'PERIOD1', 'INT',
			'KOEF', 'NUMERIC(18,4)', 'MAX(KOEF) AS KOEF',
			'#BASE', @PAYS_MONTS1

		DELETE FROM dbo.SDOC_AVAC_TABLE3  WHERE LINK_UP = @LINK_DOC
		
		DECLARE @SCRIPT VARCHAR(8000)
		SET @SCRIPT = ' INSERT INTO dbo.SDOC_AVAC_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, KOEF1, SUMMA2, KOEF2, SUMMA3, KOEF3, SUMMA4, KOEF4, SUMMA5, KOEF5, SUMMA6, KOEF6, 
					SUMMA7, KOEF7, SUMMA8, KOEF8,  SUMMA9, KOEF9, SUMMA10, KOEF10, SUMMA11, KOEF11,  SUMMA12, KOEF12)'  
				+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, P1.LINK_PAY, P1.LINK_VKR'  
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
				+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP)) )
				THEN ', COALESCE(SUMMA_'
					+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
					+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
					+ ',0)' ELSE ',0,0' END
			+ ' from ' + @PAYS_MONTS + ' P1 LEFT JOIN ' + @PAYS_MONTS1 + ' P2 ON P1.LINK_PAY = P2.LINK_PAY AND P1.LINK_VKR = P2.LINK_VKR' 
		exec (@SCRIPT)
		
		SET @I = 0
		UPDATE dbo.SDOC_AVAC_TABLE3  
		SET @I = @I+1, ORDERS = @I
		WHERE LINK_UP = @LINK_DOC
	END --IF @RECALC = 0 BEGIN
	
END -- IF @RECALC <= 1

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))

	-- В календарных днях
	INSERT INTO @WTIME (M,Y)
	SELECT m,y 
	FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP)
		

	Declare @KBK_DEF INT
	SET @KBK_DEF = (Select top 1 link_kbk from dbo.KU_EmplStafKBK(default) where link_empl = @LINK_EMPL)

	---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), SUMMA_MAT NUMERIC(18,2))
	INSERT INTO @TABLE2
	SELECT  
		T.Y,
		T.M,
		COALESCE(B.LINK_KBK,@KBK_DEF),
		SUMMA_ZP = SUM( CASE WHEN coalesce(PAYMENT,0) not in (6,7,12) THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_PR = SUM( CASE WHEN coalesce(PAYMENT,0) in (6,7) THEN (CASE WHEN @FURLOUGH_GOS_OPT1 = 1 THEN ROUND(coalesce(SUMMA,0)/12,2) ELSE coalesce(SUMMA,0) END) ELSE 0 END),
		SUMMA_MAT = SUM( CASE WHEN coalesce(PAYMENT,0) = 12 THEN (CASE WHEN @FURLOUGH_GOS_OPT2 = 1 THEN ROUND(coalesce(SUMMA,0)/12,2) ELSE coalesce(SUMMA,0) END) ELSE 0 END)
	FROM 
		@WTIME T LEFT JOIN 
		(
		Select PERIOD = DATEADD(MONTH,0,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA1,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,1,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA2,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA2,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,2,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA3,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA3,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,3,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA4,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA4,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,4,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA5,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA5,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,5,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA6,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA6,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,6,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA7,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA7,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,7,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA8,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA8,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,8,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA9,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA9,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,9,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA10,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA10,0) <> 0 
	UNION ALL
		Select PERIOD = DATEADD(MONTH,10,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA11,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA11,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,11,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA12,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3 WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA12,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD) AND T.M = MONTH(B.PERIOD)
	GROUP BY
		T.Y, T.M, B.LINK_KBK

	-----
	DELETE FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE2 (LINK_UP, ORDERS, PERIOD, LINK_KBK, SUMMA, PREM, DAYS, HOURS, DAYS_N, HOURS_N, MATER)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), 
	LINK_KBK, 
	SUMMA_ZP,
	SUMMA_PR, 
	0,0,0,0,SUMMA_MAT
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	INSERT INTO dbo.SDOC_AVAC_TABLE2 (LINK_UP, ORDERS, PERIOD, LINK_KBK, SUMMA, PREM, DAYS, HOURS, DAYS_N, HOURS_N, MATER)
	SELECT  @LINK_DOC, 0, @DATE_BEGIN, 
	(CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), 
	sum(SUMMA),
	0, 
	0,0,0,0,0
	FROM #BASE1
	where p = 0
	group by (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end)

	SET @I = 0
	UPDATE dbo.SDOC_AVAC_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC


END	--IF @RECALC < = 1

IF @RECALC < = 2 --- Расчет периодов отпуска и определение средних сум
BEGIN		



	--- Вычисление коэффициентов индексации зарполаты по время отпуска
	DECLARE @INDEX TABLE ([DATE] DATETIME, [DATE2] DATETIME, SUMMA NUMERIC(18,2), INDEX_VAL NUMERIC(18,10))

	INSERT INTO @INDEX
	SELECT DISTINCT 
		[DATE] = CASE WHEN @DATE_BEGIN >= DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END, 
		NULL,
		0,
		1
	FROM 
		DBO.DICTIONARY_PAYS_EMPL_FN(@DATE_END, @LINK_EMPL, DEFAULT, DEFAULT, @DEP_LINK, DEFAULT) S
	WHERE
		S.WAY_CALC not in (6, 7, 12)
		AND
		s.LINK_PAYS IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)	

		
	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A
		
	DECLARE @Cur1 CURSOR, @Cur2 CURSOR, @NEXT_DATE DATETIME, @NEXT_DATE2 DATETIME, @INDEX_VAL NUMERIC(18,10)
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT [DATE] FROM @INDEX ORDER BY [DATE]

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			UPDATE @INDEX 
			SET SUMMA = (SELECT SUM(SUMMA) FROM dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @NEXT_DATE, DEFAULT, @LINK_DEP) WHERE LINK_SOVM = 0)
			WHERE [DATE] = @NEXT_DATE

			SET @INDEX_VAL = 1
		
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT [DATE] FROM @INDEX WHERE [DATE] <= @NEXT_DATE ORDER BY [DATE]
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN
					SET @INDEX_VAL = @INDEX_VAL 
					* (CASE WHEN (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) <> 0
						THEN
							(SELECT SUMMA / (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) FROM @INDEX WHERE [DATE] = @NEXT_DATE2)
						ELSE 1
						END)
				END
				FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			END

			CLOSE @Cur2
			DEALLOCATE @Cur2				

			UPDATE @INDEX 
			SET INDEX_VAL = @INDEX_VAL
			WHERE [DATE] = @NEXT_DATE
			
		END

		FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1

	---Периоды отпуска
	DECLARE @PERIODY TABLE (DATE_BEGIN DATETIME, DATE_END DATETIME, INDEX_VAL NUMERIC(18,10), DH_NORM NUMERIC(18,2))
	DECLARE @PERIODY_DOP TABLE (NUM INT IDENTITY(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, T TINYINT)

		--- 1. Разбивка на периоды по месяцам
	if @DATE_BREAK IS NULL
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		SELECT 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_END)
	ELSE
	BEGIN
		SET @DATE_BREAK = @DATE_BREAK -1
		
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN  @DATE_BREAK < dbo.DateEndOfMonth(DATE_BEGIN) THEN  @DATE_BREAK ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_BREAK)
		UNION ALL
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BREAK_NEW_BEGIN > DATE_BEGIN THEN @DATE_BREAK_NEW_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов			
		from dbo.months_ex(@DATE_BREAK_NEW_BEGIN, @DATE_END)

	END

	--Второй тип периодов
	INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
	SELECT DATE_BEGIN = [DATE], DATE_END = [DATE2], 2 FROM @INDEX	

	DECLARE @A TABLE (NUM INT, [DATE] DATETIME, T INT)
	DECLARE @MIN_D DATETIME, @MAX_D DATETIME
	SELECT @MIN_D = MIN(DATE_BEGIN), @MAX_D = MAX(DATE_END) FROM @PERIODY_DOP

	INSERT INTO @A (NUM, [DATE], T)
	SELECT P.NUM, [DATE], T 
	FROM
		@PERIODY_DOP P
		INNER JOIN dbo.days_ex(@MIN_D, @MAX_D) D ON D.[DATE] BETWEEN P.DATE_BEGIN AND P.DATE_END
	ORDER BY P.NUM		

	DECLARE @T1 TABLE (NUM1 INT, [DATE] DATETIME, NUM2 INT)

	INSERT INTO @T1 (NUM1, [DATE], NUM2)
	SELECT A1.NUM, A1.[DATE], A2.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1 AND A2.T = 2
	UNION
	SELECT A2.NUM, A2.[DATE], A1.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1 AND A2.T = 2

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, INDEX_VAL)
	SELECT 
		DATE_BEGIN, DATE_END,
		INDEX_VAL = ISNULL((SELECT INDEX_VAL FROM @INDEX I WHERE T.[DATE_BEGIN] BETWEEN I.DATE AND I.DATE2 AND T.[DATE_END] BETWEEN I.DATE AND I.DATE2),1)
	FROM (
		SELECT DISTINCT DATE_BEGIN = MIN([DATE]), DATE_END = MAX([DATE]) FROM @T1 GROUP BY NUM1, NUM2	
		) T	

	----
	UPDATE @PERIODY
	SET DH_NORM = DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1 - (CASE WHEN @HOLIDAY = 1 THEN dbo.SA_HOLIDAY_COUNT_FN(DATE_BEGIN,DATE_END) ELSE 0 END) + @PDAY

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @PNORM NUMERIC(18,2), @PWORK NUMERIC(18,2), 
		@SR_ZP NUMERIC(18,2), @AvgDays NUMERIC(18,2), @DAYS_SZ NUMERIC(18,2)
	SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29.4)
	
	---	
	SELECT 
		@SUMMA_ZP = COALESCE(SUM(SUMMA),0), 
		@SUMMA_PR = COALESCE(SUM(PREM),0) + COALESCE(SUM(MATER),0),
		@REP_SUMMA_PR = SUM(PREM)
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC

	---	
	SET @SR_ZP = CASE WHEN @AvgDays <> 0 THEN (@SUMMA_ZP + @SUMMA_PR) / @AvgDays ELSE 0 END
		
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @S NUMERIC(18,2)
	SET @S = COALESCE((SELECT SUM(SUMMA) + SUM(PREM) + SUM(MATER) FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

	INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
	SELECT LINK_KBK, CASE WHEN @S <> 0 THEN (SUM(SUMMA) + SUM(PREM) + SUM(MATER)) / @S ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC 
	GROUP BY LINK_KBK
	
	---
	DELETE FROM dbo.SDOC_AVAC_TABLE1  WHERE LINK_UP = @LINK_DOC


	INSERT INTO dbo.SDOC_AVAC_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, [DAYS], [HOURS], SR_ZP, SUMMA, LINK_KBK, KOEF_KBK, KOEF_IDX)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		DH_NORM,
		ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOUR_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0),
		SR_ZP = @SR_ZP,
		0,
		K.LINK_KBK,	
		K.KOEF,
		P.INDEX_VAL
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	ORDER BY DATE_BEGIN

	UPDATE sdoc_avac WITH (ROWLOCK) 
	SET 
		LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SUMMA_TOTAL = @SUMMA_ZP, SR_PREM=@SUMMA_PR, 
			TYP_PERIOD=@TYP_PERIOD, SUMMA_BASE = @SR_ZP, 
		PAYMENT=@PAYMENT, REF_DOC = @LINK_VAC, DATE1 = @DATE_BEGIN, DATE2 = @DATE_END, [TYPE] = @SR_VID
	WHERE 
		LINK_UP = @LINK_DOC

	--Дневное пособие не может быть менее дневного пособия, рассчитанного исходя из МРОТ
	IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
		UPDATE dbo.SDOC_AVAC_TABLE1
		SET SR_ZP = case when SR_ZP < dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1) 
			then	
				dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1)
			else	
				SR_ZP 
			end
	WHERE LINK_UP = @LINK_DOC

END --@RECALC <= 2 

-----------------------------------------
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, CJ.DAYS, CJ.HOURS, SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_AVAC SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	COALESCE(@LINK_VAC,0) > 0
	AND
	SA.REF_DOC = @LINK_VAC
	and
	d.object = (Select top 1 link from s_objects where code = @OBJ_CODE)
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.DAYS, CJ.HOURS, CJ.LINK_VKR

DECLARE @INDEX_ZP INT, @INDEX_PREM INT
SET @INDEX_ZP = 1
SET @INDEX_PREM = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT6')

---- сопоставить старые
UPDATE dbo.SDOC_AVAC_TABLE1
SET SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.[DAYS] * KOEF_KBK) 
	+ CASE WHEN KOEF_IDX > 1 AND @INDEX_ZP = 1 THEN 
		CONVERT(NUMERIC(18,4), (CASE WHEN @AvgDays <> 0 THEN SUMMA_TOTAL / @AvgDays ELSE 0 END) * T.[DAYS] * KOEF_KBK * (KOEF_IDX-1) )
	  ELSE 
		0	
	  END
	+ CASE WHEN KOEF_IDX > 1 AND @INDEX_PREM = 1 THEN 
		CONVERT(NUMERIC(18,4), (CASE WHEN @AvgDays <> 0 THEN SR_PREM / @AvgDays ELSE 0 END) * T.[DAYS] * KOEF_KBK * (KOEF_IDX-1) )
	  ELSE 
		0		
	  END,	  
	 SUMMA_OLD = COALESCE(SO.SUMMA,0),
	[DAYS] = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	[HOURS] = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM dbo.sdoc_avac A INNER JOIN dbo.SDOC_AVAC_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR
WHERE T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

-- добавить старые, которых теперь нет
insert into dbo.SDOC_AVAC_TABLE1 (link_up, ORDERS, DATE1, DATE2, DAYS, HOURS, SUMMA, LINK_KBK, SR_ZP, KOEF_KBK, SUMMA_OLD, SUMMA_NEW)
Select @LINK_DOC, 0, DATE_BEGIN, DATE_END, -DAYS, -HOURS, 0, LINK_VKR, 0, 1, SO.SUMMA, 0
from #SUM_OLD SO
where 
	NOT EXISTS (Select * from dbo.SDOC_AVAC_TABLE1 T where T.LINK_UP = @LINK_DOC and T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR)

---- сравнить
UPDATE dbo.SDOC_AVAC_TABLE1
SET SUMMA = COALESCE(SUMMA_NEW,0) - COALESCE(SUMMA_OLD,0)
WHERE LINK_UP = @LINK_DOC


---
SET @I = 0
UPDATE dbo.SDOC_AVAC_TABLE1  
SET @I = @I+1, ORDERS = @I
WHERE LINK_UP = @LINK_DOC

---
DECLARE @SUMMA NUMERIC(18,2)
SELECT @SUMMA = COALESCE((SELECT SUM(SUMMA) FROM dbo.SDOC_AVAC_TABLE1 WHERE LINK_UP = @LINK_DOC),0), @SUMMA_ZP = COALESCE(@SUMMA_ZP,0), @SUMMA_PR = COALESCE(@SUMMA_PR,0)
---
SELECT @NUMBER = NUMBER,  @DATE_DOC = [DATE] from dbo.SDOC WHERE LINK = @LINK_DOC
--- Сохрание расчета
SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = @OBJ_CODE
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA, @LINK_DEP

IF @OPER = 1 
	exec dbo.SD_N_VACATION_PROV @LINK_DOC, @OBJ_CODE

SET NOCOUNT OFF


GO


GRANT EXECUTE ON dbo.[SA_N_VAC_FILL2] 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,
			[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,
			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.[BK_CLOSE_YEAR_CREATE_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_CLOSE_YEAR_CREATE_PROV]

GO

--- ФОРМИРОАНИЕ ПРОВОДОК ПО ЗАКРЫТИЮ ГОДА --- 
CREATE PROCEDURE dbo.BK_CLOSE_YEAR_CREATE_PROV
	@intLINK_DOC	INT,
	@intDEL_PROV	TINYINT = 1
AS
BEGIN
	DECLARE @intDEP_LINK	INT,

		@dDOC_DATE	DATETIME,
		@intROWCOUNT	INT,

		@strCOMMENT_G1	VARCHAR (254),
		@strCOMMENT_G2	VARCHAR (254),

		--- НАСТРОЙКА СЧЕТОВ --- 
		@intCh21002	TINYINT,
		@intCh30404	TINYINT,
		@intCh30405	TINYINT,
		@intCh40101100	TINYINT,
		@intCh40101200	TINYINT,
		@intCh40102100	TINYINT,
		@intCh40102200	TINYINT,
		@intCh501	TINYINT,

		@is_RBS		TINYINT,
		@dDATE_REST	DATETIME,

		@dDATE_BEGIN_YEAR	DATETIME,
		@dDATE_END_YEAR		DATETIME,

		@varKSERROR	INT,

		--- !!!ЗАПОЛНЕНИЕ ПРОВОДОК!!! --- 
		@varKSLinkG1	INT,
		@varKSLinkG2	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,
		@varKSAccount1	INT,
		@varKSKBK1		INT,
		@varKSEKR1		INT,
		@varKSDEP1		INT,
		@varKSSUB1		INT,
		@varKSEMP1		INT,
		@varKSNOMEN1	INT,
		@varKSINV1		INT,
		@varKSKAU1		INT,
		@varKSDEP_ACC1	INT,
		@varKSTMC1		INT,
		@varKSINDATE1	DATETIME,
		@varKSAP11		INT,
		@varKSAP21		INT,
		@varKSAP31		INT,
		@varKSSGU1		INT,
		@D_SUMMA		NUMERIC (28,4),
		@K_SUMMA		NUMERIC (28,4),
		@SUMMA			NUMERIC (28,4),
		@cSINTH			CHAR (3),
		@cANALIT		CHAR (2),
		@cSOURCE		CHAR (1),
		@intSA_ACTIVE		INT,
		@intORDERS_G1		INT,
		@intLINK_ECONOM_OPER	INT,
		@intACCT_CLOSING	INT,
		@intDBKR_CLOSING	TINYINT,

		@cSINTH_CLOSING		CHAR (3),
		@cANALIT_CLOSING	CHAR (2),
		@cUSER			VARCHAR (4),
		@cSGU_CODE		VARCHAR (3),
		@cSGU_CODE1		CHAR (1),

		@intSGU_MODE	TINYINT,
		@intKBK_MODE	TINYINT,
		@strACCT_BUFF_NAME	VARCHAR (50),
		@intACCOUNT	INT,
		@intSGU_CLOSING	INT,
		@intSGU0	INT,
		@intEKR_CLOSING	INT,
		@intKBK_CLOSING	INT
		
	--- НАСТРОЙКИ ДОКУМЕНТА --- 
	SELECT @intLINK_DOC = LINK,		
		@intDEP_LINK	= DEP_LINK,
		@dDOC_DATE	= [DATE],
		@intSGU_MODE	= ISNULL (SGU_MODE, 0),
		@intKBK_MODE	= ISNULL (KBK_MODE, 0)
	FROM dbo.BK_DOCUMENT_CLOSE_YEAR
	WHERE LINK = @intLINK_DOC

	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR ('Проводки не сформированы! Сохраните документ. ', 11, 1)
		RETURN 1
	END

	IF @intSGU_MODE = 1
		SELECT @intSGU0 = LINK
		FROM dbo.KOSGU
		WHERE CODE = '000'

	IF ISNULL (@intDEL_PROV, 0) = 1
		DELETE FROM dbo.G_PROV1 WHERE LINK_UP = @intLINK_DOC

	-- Субсчета, которые закрываем --
	EXEC dbo.GetRandStr 20, @strACCT_BUFF_NAME OUTPUT

	SET @strACCT_BUFF_NAME = '#ACCT_CLOSE_YEAR_' + @strACCT_BUFF_NAME

	CREATE TABLE #ACCT_CLOSE_YEAR (LINK INT)

	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC FOR
	SELECT ACCT_LINK
	FROM dbo.DOC_CLOSE_YEAR_TABLE
	WHERE LINK_UP = @intLINK_DOC
	GROUP BY ACCT_LINK 

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @intACCOUNT

	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO #ACCT_CLOSE_YEAR 
		SELECT LINK
		FROM dbo.AccountsSubtreeByRoot (@intACCOUNT) A
		WHERE NOT EXISTS
			(SELECT LINK FROM #ACCT_CLOSE_YEAR A1
				WHERE A1.LINK = A.LINK)

		FETCH NEXT FROM #DATA_CURSOR
			INTO @intACCOUNT
	END	-- #DATA_CURSOR

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	EXEC dbo.BufferClear @strACCT_BUFF_NAME
	EXEC dbo.BufferPushTable
		'#ACCT_CLOSE_YEAR',
		@strACCT_BUFF_NAME

	-- !!!!!!! НАЧАЛО !!!!!!!!!! --
	SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE) 
	SET @dDATE_BEGIN_YEAR = dbo.DateBeginOfYear (@dDOC_DATE)

	-- Счет используемый для закрытия --
	SELECT @cSINTH_CLOSING = cSINTH,
		@cANALIT_CLOSING = cANALIT
	FROM dbo.S_ACCOUNTS
	WHERE LINK = dbo.XK_GET_NASTR_INT ('OPT_DOC_CLOSE_YEAR_ACCT_LINK')

	IF @cSINTH_CLOSING IS NULL OR @cANALIT_CLOSING IS NULL
		SELECT @cSINTH_CLOSING = cSINTH,
			@cANALIT_CLOSING = cANALIT
		FROM dbo.S_ACCOUNTS
		WHERE CODE = '401.30'
		
	SET @strCOMMENT_G1 = 'Операция закрытия ' + LTRIM (STR (YEAR (@dDOC_DATE))) + ' года'

	DECLARE #REST CURSOR STATIC LOCAL 
	FOR
	SELECT
		SUM (REST.D_SUMMA), SUM (REST.K_SUMMA), 
		REST.ACCOUNT, REST.KBK, REST.EKR, REST.DEP, REST.SUB, REST.EMP, REST.NOMEN,
		REST.INV, REST.KAU, REST.DEP_ACC, REST.TMC, REST.SGU, REST.INDATE,
		REST.AP1, REST.AP2, REST.AP3, SA.cSOURCE, SA.S_ACTIVE, SA.cSINTH, SA.cANALIT, SA.cUSER
--		K.CODE
	FROM dbo.ARestTableByDateAccounts (@dDATE_REST, @strACCT_BUFF_NAME) REST
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = REST.ACCOUNT)
--	LEFT JOIN dbo.KOSGU K ON (K.LINK = REST.SGU)

	WHERE REST.DEP_LINK =  @intDEP_LINK

	GROUP BY REST.ACCOUNT, REST.KBK, REST.EKR, REST.DEP, REST.SUB, REST.EMP, REST.NOMEN,
		REST.INV, REST.KAU, REST.DEP_ACC, REST.TMC, REST.SGU, REST.INDATE,
		REST.AP1, REST.AP2, REST.AP3, SA.cSOURCE, SA.S_ACTIVE, SA.cSINTH, SA.cANALIT, SA.cUSER
		--K.CODE

	OPEN #REST
	FETCH NEXT FROM #REST
		INTO @D_SUMMA, @K_SUMMA,
			@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
			@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
			@varKSTMC, @varKSSGU, @varKSINDATE,
			@varKSAP1, @varKSAP2, @varKSAP3, @cSOURCE, @intSA_ACTIVE, @cSINTH, @cANALIT, @cUSER
--			@cSGU_CODE

	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @varKSLinkG1 = NULL
		SET @varKSLinkG2 = NULL
	
		SET @intACCT_CLOSING = dbo.BK_GetDBKTAccount (@varKSAccount,
								@cSINTH_CLOSING,
								@cANALIT_CLOSING,
								DEFAULT)

		IF @intACCT_CLOSING IS NULL
		BEGIN
			FETCH NEXT FROM #REST
				INTO @D_SUMMA, @K_SUMMA,
					@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
					@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
					@varKSTMC, @varKSSGU, @varKSINDATE,
					@varKSAP1, @varKSAP2, @varKSAP3,
					@cSOURCE, @intSA_ACTIVE, @cSINTH, @cANALIT, @cUSER
			CONTINUE
		END

		--- Разносим по счетам!!! --- 
		IF @intSA_ACTIVE = 1	-- ДЛЯ ЗАКРЫТИЯ АКТИВНЫХ СЧЕТОВ
		BEGIN
			SET @SUMMA = @D_SUMMA
			SET @varKSDB_KR = 1
			SET @intDBKR_CLOSING = 0
		END
		ELSE
		BEGIN
			SET @SUMMA = @K_SUMMA

			IF  @SUMMA > 0
				AND (@cSINTH = '304' AND @cANALIT LIKE '0[4-6]'
					OR @cSINTH = '401' AND @cANALIT = '10')
--					OR @cSINTH = '304' AND @cANALIT = '05')
				SELECT @varKSDB_KR = 0,
					@intDBKR_CLOSING = 1
			ELSE
				SELECT @varKSDB_KR = 1,
					@intDBKR_CLOSING = 0,
					@SUMMA  =  - @SUMMA
		END

		--- G_PROV1 --- 
		SET @intORDERS_G1 = ISNULL ((SELECT MAX (ORDERS)
						FROM dbo.G_PROV1
						WHERE LINK_UP = @intLINK_DOC), 0) + 1
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV1
						@varKSLinkG1 OUTPUT,
						@intLINK_DOC,
						NULL,
						@strCOMMENT_G1,
						@intORDERS_G1
		IF @varKSERROR <> 0
			RETURN @varKSERROR

		IF @intDBKR_CLOSING = 0
			SET @intLINK_ECONOM_OPER = (SELECT TOP 1 XO.LINK
							FROM dbo.CORRECT_PROV_FULL CPF
							INNER JOIN dbo.XOZ_OPER XO ON (XO.LINK = CPF.LINK_HOZ)
							INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK
								AND XOG.CODE = '98')
							WHERE CPF.LINK_DT = @intACCT_CLOSING
								AND CPF.LINK_KT = @varKSAccount)
		ELSE
			SET @intLINK_ECONOM_OPER = (SELECT TOP 1 XO.LINK
							FROM dbo.CORRECT_PROV_FULL CPF
							INNER JOIN dbo.XOZ_OPER XO ON (XO.LINK = CPF.LINK_HOZ)
							INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK
								AND XOG.CODE = '98')
							WHERE CPF.LINK_DT = @varKSAccount
								AND CPF.LINK_KT = @intACCT_CLOSING)

		SET @strCOMMENT_G2 = ISNULL ((SELECT RTRIM (CONVERT (VARCHAR (254), NAME))
						FROM dbo.XOZ_OPER
						WHERE LINK = @intLINK_ECONOM_OPER), @strCOMMENT_G1)

		--- G_PROV2 --- 
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV2 @varKSLinkG2 OUTPUT,
						@varKSLinkG1,
						NULL,
					 	@SUMMA,
						0,
						0,
						@strCOMMENT_G2,
						@intLINK_ECONOM_OPER,
						1

		IF @varKSERROR <> 0
			RETURN @varKSERROR	


		IF @intACCT_CLOSING IS NULL OR @varKSAccount IS NULL
		BEGIN
			DELETE FROM dbo.G_PROV1 WHERE LINK = @varKSLinkG1

			FETCH NEXT FROM #REST
			INTO @D_SUMMA, @K_SUMMA,
				@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
				@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
				@varKSTMC, @varKSSGU, @varKSINDATE,
				@varKSAP1, @varKSAP2, @varKSAP3, @cSOURCE,
				@intSA_ACTIVE, @cSINTH, @cANALIT, @cUSER
--				@cSGU_CODE
			CONTINUE
		END

		SET @intSGU_CLOSING = ISNULL (@intSGU0, @varKSSGU)
		IF EXISTS (SELECT LINK
				FROM dbo.S_ACCOUNTS WHERE LINK = @intACCT_CLOSING)
			SET @intEKR_CLOSING = @intSGU_CLOSING

		SET @intKBK_CLOSING = @varKSKBK

		IF @intKBK_MODE = 1	-- Поиск КБК с главой --
		BEGIN
			EXECUTE @varKSERROR = dbo.BK_RETURN_ONLY_ADM_KBK
					@intKBK_CLOSING OUTPUT,
					@varKSKBK

			IF @varKSERROR <> 0
				RETURN @varKSERROR	
		END
		
		--- 40103 --- 
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_AP @varKSLinkG2, @intDBKR_CLOSING, @intACCT_CLOSING, 
					@intKBK_CLOSING, @intEKR_CLOSING, @varKSDEP, @varKSSUB,
					@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
					@varKSTMC, @varKSINDATE, @varKSAP1, @varKSAP2, @varKSAP3, @intSGU_CLOSING 
		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		--- ACCOUNT --- 
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_AP @varKSLinkG2, @varKSDB_KR, @varKSAccount, 
					@varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
					@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
					@varKSTMC, @varKSINDATE, @varKSAP1, @varKSAP2, @varKSAP3, @varKSSGU 
		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		FETCH NEXT FROM #REST
			INTO @D_SUMMA, @K_SUMMA,
				@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
				@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
				@varKSTMC, @varKSSGU, @varKSINDATE,
				@varKSAP1, @varKSAP2, @varKSAP3,
				@cSOURCE, @intSA_ACTIVE, @cSINTH, @cANALIT, @cUSER
--			@cSGU_CODE

	END

	CLOSE #REST
	DEALLOCATE #REST

	EXEC dbo.BufferClear @strACCT_BUFF_NAME
	DROP TABLE #ACCT_CLOSE_YEAR

	RETURN 0
END


GO


GRANT EXECUTE ON dbo.[BK_CLOSE_YEAR_CREATE_PROV] TO PUBLIC

GO


--Расширенные свойства--


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[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(50), 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(50), 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(50), 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(50), 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(50), [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(50), 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(50), Link_Table int, orders int)
create table #report_dinamics(Link_SF int, Code_Row varchar(50), 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(50), 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(50), Link_Table int, Calc tinyint, cOrderTable varchar(300))
create table #TreeExclude (Code VARCHAR(50), 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(4000),@ExecStr1 nvarchar(4000), @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(50), @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(', 'dbo.RO_COL_Static(@LSF, K.Link_Table, S.Link_Row,') + ')
	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(', 'dbo.RO_COL_Static(@LSF, K.Link_Table, S.Link_Row,') + '
	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', 
                   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(50)', @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 

		delete #tmp
		update #t_KS SET Link_Rule = -Link_Rule where Link_Rule = @LinkRule AND CodeRow = @CodeRow 
		exec sp_executesql N'select @count = count(*) from #t_KS where algorithm  = 9 and Link_Rule > 0', 
					   N'@count int output', @count = @a_count OUTPUT
	end

	delete #t_KS
	where algorithm = 4
   
   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 Link_Rule = ABS(Link_RULE)   

	-------------------------------------------------------------------------------------------
	-- деление и умножение и т.д.
	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 #t_Result_C
	set Link_Col = K.Link_Col,
		Link_Table = K.Link_Table,
		Value = CASE WHEN isnull(IsDoschet, 0) & 16 = 0 THEN round(convert(numeric(20,5), #t_Result_C.Value), C.Val_Len) ELSE ABS(round(convert(numeric(20,5), #t_Result_C.Value), C.Val_Len)) END 
	from #t_KS_Left K left join #t_Col C on K.Link_Col = C.Link_Col
         LEFT JOIN #t_Rules R ON R.[Link_Rule] = K.[Link_Rule] 
	where #t_Result_C.orderCol = 0 and K.Link_Rule = #t_Result_C.Link_Rule

	update Res
	set Link_Col = C.Link_Col,
		Link_Table = K.Link_Table,
		Value = CASE WHEN isnull(IsDoschet, 0) & 16 = 0 
            THEN round(convert(numeric(20,5), Res.Value), C.Val_Len) 
            ELSE ABS(round(convert(numeric(20,5), Res.Value), C.Val_Len)) END 
	from     #t_KS_Left K 
            join #t_Col C on K.Link_Table = C.Link_Table
            JOIN #t_Rules R ON R.[Link_Rule] = K.[Link_Rule]
            join #t_Result_C Res ON K.Link_Rule = Res.Link_Rule and Res.orderCol = C.orderCol
	--where #t_Result_C.orderCol <> 0 and K.Link_Rule = #t_Result_C.Link_Rule and #t_Result_C.orderCol = C.orderCol

	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.[XK_UPDATE_OUT_TABLE_MZ_SUMMA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XK_UPDATE_OUT_TABLE_MZ_SUMMA]
GO

CREATE PROCEDURE dbo.XK_UPDATE_OUT_TABLE_MZ_SUMMA
	(@LINK_ROW INT,
	@INV_TYPE VARCHAR(30),
	@INV 	INT,
	@PRICE NUMERIC(19, 4) = 0,
	@AKCIZ NUMERIC (19, 4) = 0,
	@NUM_TD VARCHAR(30) = '',
	@QTY NUMERIC(19, 4) = 0,
	@SUMMA NUMERIC(19, 4) = 0,
	@STAVKA_NDS NUMERIC(5, 2) = 0,
	@SUMMA_NDS NUMERIC(19, 4) = 0,
	@SUMMA_ALL NUMERIC(19, 4) = 0,
	@EKR INT = NULL,
	@FIN_SOURCE CHAR(1)= '',
	@NO_NDS	TINYINT = 0,
	@COUNTRY_LINK	INT = NULL,
	@TYPE_NDS	TINYINT = NULL
	)
AS
BEGIN
	DECLARE @intINV	INT,
		@intNOMEN INT,
		@intTMC INT,

		@varKStrancount INT,
		@varKSRowCount INT,
		@varKSERROR INT

	IF NOT EXISTS (SELECT * FROM dbo.OUT_TABLE_ROW WHERE LINK = @LINK_ROW)
	BEGIN
		RAISERROR ('Строка была удалена!', 11, 1)
		RETURN 5
	END

	--- Вычисляем правильные линки в зависимости от типа МЗ ---
	SELECT @intINV = NULL,
		@intNOMEN = NULL,
		@intTMC = NULL

	IF @INV_TYPE IN ('BV_NOMENCLATURE', 'DICTIONARY_SERV')
		SELECT @intNOMEN = LINK FROM dbo.NOMENCLATURE WITH (NOLOCK) WHERE LINK = @INV

	IF @INV_TYPE = 'INVENTORY_CARD'
		SELECT @intINV = LINK FROM dbo.INVENTORY WITH (NOLOCK) WHERE LINK = @INV
	
	IF @INV_TYPE = 'DICTIONARY_TMC'
		SELECT @intTMC = LINK FROM dbo.DICTION WITH (NOLOCK) WHERE LINK = @INV

	IF @STAVKA_NDS < 0
	BEGIN
		SET @NO_NDS = 1
		SET @STAVKA_NDS = 0
	END

	SELECT @PRICE = ISNULL (@PRICE, 0), 
		@AKCIZ = ISNULL (@AKCIZ, 0), 
		@NUM_TD = ISNULL (@NUM_TD, ''), 
		@QTY = ISNULL (@QTY, 0), 
		@SUMMA = ISNULL (@SUMMA, 0), 
		@STAVKA_NDS = ISNULL (@STAVKA_NDS, 0), 
		@SUMMA_NDS = ISNULL (@SUMMA_NDS, 0), 
		@SUMMA_ALL = ISNULL (@SUMMA_ALL, 0), 
		@FIN_SOURCE = ISNULL (@FIN_SOURCE, ''),
		@NO_NDS	= ISNULL (@NO_NDS, 0)

	SET @EKR = (SELECT LINK FROM dbo.KOSGU WHERE LINK = @EKR)
	SET @COUNTRY_LINK = (SELECT LINK FROM dbo.KL_COUNTRY WHERE LINK = @COUNTRY_LINK)
	SET @TYPE_NDS = (SELECT LINK FROM dbo.TYPE_OPER_NDS WHERE LINK = @TYPE_NDS)

	SET LOCK_TIMEOUT 30000
	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	UPDATE dbo.OUT_TABLE_MZ_SUMMA
	SET 	
		INV_TYPE = @INV_TYPE, 
		INV = @intINV,
		NOMEN = @intNOMEN, 
		TMC = @intTMC,
		PRICE = @PRICE,
		AKCIZ = @AKCIZ, 
		NUM_TD = @NUM_TD,
		QTY = @QTY,
		SUMMA = @SUMMA, 
		STAVKA_NDS = @STAVKA_NDS,
		SUMMA_NDS = @SUMMA_NDS,
		SUMMA_ALL = @SUMMA_ALL,
		EKR = @EKR,
		FIN_SOURCE = @FIN_SOURCE,
		NO_NDS = @NO_NDS,
		COUNTRY_LINK = @COUNTRY_LINK,
		TYPE_NDS = @TYPE_NDS
	WHERE LINK_ROW = @LINK_ROW

	SELECT @varKSRowCount = @@ROWCOUNT, @varKSERROR = @@ERROR
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	IF @varKSRowCount = 0
	BEGIN
		INSERT INTO dbo.OUT_TABLE_MZ_SUMMA (LINK_ROW, INV_TYPE, INV, NOMEN, TMC, PRICE,
				AKCIZ, NUM_TD, QTY,
				SUMMA, STAVKA_NDS, SUMMA_NDS, SUMMA_ALL, EKR, FIN_SOURCE, NO_NDS,
				COUNTRY_LINK, TYPE_NDS)
		VALUES 	(@LINK_ROW, @INV_TYPE, @intINV, @intNOMEN, @intTMC, @PRICE,
				@AKCIZ, @NUM_TD, @QTY,
				@SUMMA, @STAVKA_NDS, @SUMMA_NDS, @SUMMA_ALL, @EKR, @FIN_SOURCE, @NO_NDS,
				@COUNTRY_LINK, @TYPE_NDS)

		SELECT @varKSRowCount = @@ROWCOUNT, @varKSERROR = @@ERROR

		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0

END


GO


GRANT EXECUTE ON dbo.[XK_UPDATE_OUT_TABLE_MZ_SUMMA] 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_KS_SUMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_KS_SUMM]
GO




/*
© Кейсистемс (Keysystems), 2012
*/
CREATE  PROCEDURE dbo.RO_KS_SUMM
	@varKStOrderTable    TINYINT,
   @varKSvcOrderCol     VARCHAR(50),
   @varKSvcFilter       varchar(1000), 
	@varKSiLSF	int
AS
	declare @val numeric(18, 2), @nvExecStr NVARCHAR(4000)
	

   SET @nvExecStr = 'SELECT @val = SUM(float_val)
   FROM #report_dinamics rd 
         JOIN dbo.report_coloumns rc ON rd.link_col = rc.link_col
         JOIN dbo.report_tables rt ON rc.link_table = rt.link_table
   WHERE rt.orders = @varKStOrderTable AND CHARINDEX('','' + LTRIM(STR(rc.orders)) + '','' , '','' +  REPLACE(@varKSvcOrderCol, '' '', '''') + '','') > 0'
         + CASE WHEN ISNULL(@varKSvcFilter, '') = '' THEN '' ELSE ' and ' + REPLACE(@varKSvcFilter, 'code', 'code_row')  END  
   

   EXEC sp_executesql @nvExecStr, N'@val numeric(18,2) output, @varKStOrderTable    TINYINT, @varKSvcOrderCol     VARCHAR(50)' , @val = @val OUTPUT, @varKStOrderTable = @varKStOrderTable,@varKSvcOrderCol = @varKSvcOrderCol 

	select isnull(@val, 0)



GO
GRANT ALL ON [dbo].[RO_KS_SUMM] 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_CONTROL_PROV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CONTROL_PROV]

GO

CREATE  PROCEDURE dbo.SA_CONTROL_PROV
AS
DECLARE 	@varKSControlObjLink int,
			@varKSControlObjCode varchar(30),
			@varKSControlObjName varchar(100),
			@varKSCurs	CURSOR,
			@varKSCurLINK int,
			@varKSCurNAME varchar(100),
			@CODE_ACC VARCHAR(6),
			@varKSCurFieldName varchar(30),
			@varKSCurRecFieldText varchar(254),
			@LINK_KAU INT,
			@varKSCurLINK_OPER int

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)
		
CREATE TABLE #TempControlTable
(OBJ_CODE varchar(30),
 OBJ_NAME varchar(50),
 FIELD_NAME varchar(30),
 LINK	int,
 COMMENTS varchar(254), Type int)

DECLARE @CALC_PERIOD DATETIME
SET @CALC_PERIOD = dbo.SalaryCalcPeriod()

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)

IF @WORKMODE157N = 1 BEGIN

	CREATE TABLE #ACC_CONTROL
	(
		CHECKED BIT,
		UPD BIT,
		DEL BIT,
		LOCKED BIT,
		LINK INT,
		CODE VARCHAR(13),
		INF_MAIN VARCHAR(254),
		INF_LOSTAP VARCHAR(254),
		INF_OVERAP VARCHAR(254)
	)

	INSERT INTO #ACC_CONTROL (CHECKED, UPD, DEL, LOCKED, LINK, CODE, INF_MAIN, INF_LOSTAP, INF_OVERAP)
	EXEC DBO.BX_PLAN_ACCOUNTS_CONTROL

	-- Проверка 302 счета
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	select 'PLAN_ACCOUNTS', 'План счетов', 'Счет ' + RTRIM(CODE), LINK, 'Счет ' + RTRIM(CODE) + ' - ' +  convert(varchar(254), INF_MAIN), 1
	FROM #ACC_CONTROL RES
	WHERE @WORKMODE157N = 1 AND INF_MAIN <> '' AND (CODE LIKE '%.302.11' OR CODE LIKE '%.302.12' OR CODE LIKE '%.302.13')

END

-- Проверка счетов в справочнике удержанй
SET @varKSControlObjCode = 'DICTIONARY_TAX_SALARY'
SELECT @varKSControlObjLink = LINK,@varKSControlObjName = NAME FROM S_OBJECTS WHERE CODE = @varKSControlObjCode 
SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT LINK,[NAME], CODE_ACC FROM DBO.DICTIONARY_TAX_SALARY 
WHERE LINK IN (Select DISTINCT CJ.LINK_PAYS from dbo.CALCULATE_JURNAL CJ WHERE YEAR(CJ.PERIOD_BEGIN) = YEAR(@CALC_PERIOD))

ORDER BY CODE
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME, @CODE_ACC
WHILE @@FETCH_STATUS = 0
BEGIN
	
	IF LTRIM(RTRIM(ISNULL(@CODE_ACC,''))) = ''
	BEGIN
		SET @varKSCurRecFieldText = 'У удержания '''+LTRIM(RTRIM(@varKSCurNAME))+ ''' не заполнен реквизит "Кредит счета"'
		INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
 		VALUES (@varKSControlObjCode,@varKSControlObjName,'Кредит счета',@varKSCurLINK,@varKSCurRecFieldText,1)
	END

	FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME,@CODE_ACC
END
CLOSE @varKSCurs

-- Проверка типовых операций в справочнике начислений
SET @varKSControlObjCode = 'DICTIONARY_PAY_SALARY'
SELECT @varKSControlObjLink = LINK,@varKSControlObjName = NAME FROM S_OBJECTS WHERE CODE = @varKSControlObjCode 
SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT LINK,[NAME], LINK_OPER FROM DICTIONARY_PAY_SALARY 
WHERE LINK IN (Select DISTINCT CJ.LINK_PAYS from dbo.CALCULATE_JURNAL CJ WHERE YEAR(CJ.PERIOD_BEGIN) = YEAR(@CALC_PERIOD))

ORDER BY CODE
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME,@varKSCurLINK_OPER
WHILE @@FETCH_STATUS = 0
BEGIN
	
	IF @varKSCurLINK_OPER = 0 OR @varKSCurLINK_OPER IS NULL 	
	BEGIN
		SET @varKSCurRecFieldText = 'У начисления '''+LTRIM(RTRIM(@varKSCurNAME))+ ''' не заполнен реквизит "типовая операция"'
		INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
 		VALUES (@varKSControlObjCode,@varKSControlObjName,'Типовая операция',@varKSCurLINK,@varKSCurRecFieldText,1)
	END
	
	FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME,@varKSCurLINK_OPER
END
CLOSE @varKSCurs
DEALLOCATE @varKSCurs

-- Проверка счетов в справочнике отчислений
SET @varKSControlObjCode = 'DICTIONARY_DEDUCT_SALARY'
SELECT @varKSControlObjLink = LINK,@varKSControlObjName = NAME FROM DBO.S_OBJECTS WHERE CODE = @varKSControlObjCode 
SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT LINK,[NAME], CODE_ACC, LINK_KAU FROM DBO.DICTIONARY_DEDUCT_SALARY 

ORDER BY CODE
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME, @CODE_ACC, @LINK_KAU
WHILE @@FETCH_STATUS = 0
BEGIN
	
	IF LTRIM(RTRIM(ISNULL(@CODE_ACC,''))) = ''
	BEGIN
		SET @varKSCurRecFieldText = 'У отчисления '''+LTRIM(RTRIM(@varKSCurNAME))+ ''' не заполнен реквизит "Кредит счета"'
		INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
 		VALUES (@varKSControlObjCode,@varKSControlObjName,'Кредит счета',@varKSCurLINK,@varKSCurRecFieldText,1)
	END

	--IF @LINK_KAU is null 
	--BEGIN
	--	SET @varKSCurRecFieldText = 'У отчисления '''+LTRIM(RTRIM(@varKSCurNAME))+ ''' не заполнен реквизит "КАУ"'
	--	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
 --		VALUES (@varKSControlObjCode,@varKSControlObjName,'КАУ',@varKSCurLINK,@varKSCurRecFieldText,0)
	--END

	FETCH NEXT FROM @varKSCurs INTO @varKSCurLINK,@varKSCurNAME, @CODE_ACC, @LINK_KAU
END
CLOSE @varKSCurs
DEALLOCATE @varKSCurs


-- Проверяем существование ЭКР
IF NOT EXISTS (SELECT LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	VALUES ('DICTIONARY_ITEM','','ЭКР',0,'В справочнике ''Экономическая классификация расходов (ЭКР)'' 211 ЭКР',0)

IF NOT EXISTS (SELECT LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '212')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	VALUES ('DICTIONARY_ITEM','','ЭКР',0,'В справочнике ''Экономическая классификация расходов (ЭКР)'' 212 ЭКР',0)

IF NOT EXISTS (SELECT LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	VALUES ('DICTIONARY_ITEM','','ЭКР',0,'В справочнике ''Экономическая классификация расходов (ЭКР)'' 213 ЭКР',0)



-- Проверяем установку счетов в общих настройках по зарплате ЭКР
IF NOT EXISTS (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT1'))) AND SID IS NULL)
OR RTRIM(LTRIM(COALESCE((SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT1'))) AND SID IS NULL),''))) IN ('','.','.  .')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SALARY_OPTIONS', '', 'Настройка', 0, 'В общих настройках по зарплате не задан ''' + RTRIM(LTRIM([NAME])) + '''', 1 FROM S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT1'

IF NOT EXISTS (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT2'))) AND SID IS NULL)
OR RTRIM(LTRIM(COALESCE((SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT2'))) AND SID IS NULL),'')))  IN ('','.','.  .')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SALARY_OPTIONS', '', 'Настройка', 0, 'В общих настройках по зарплате не задан ''' + RTRIM(LTRIM([NAME])) + '''', 1 FROM S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT2'

IF @WORKMODE157N = 1 AND @BUH_TYPE = 0
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'DICTIONARY_DEPARTMENT', '', 'Настройка', 0, 'В реквизитах текущей организации не определён реквизит "Вид государственного учреждения"', 0

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE)
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SA_SAL_NASTR_PROV', '', 'Настройка', 0, 'В настройках формирования проводок по зарплате не указано ни одного счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения"', 1

IF NOT EXISTS (SELECT TOP 1 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)
OR RTRIM(LTRIM(COALESCE((SELECT TOP 1 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),'')))  IN ('','.','.  .')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SALARY_OPTIONS', '', 'Настройка', 0, 'В общих настройках по зарплате не задан ''' + RTRIM(LTRIM([NAME])) + '''', 1 FROM S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT5'

IF NOT EXISTS (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT6'))) AND SID IS NULL)
OR RTRIM(LTRIM(COALESCE((SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT6'))) AND SID IS NULL),'')))  IN ('','.','.  .')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SALARY_OPTIONS', '', 'Настройка', 0, 'В общих настройках по зарплате не задан ''' + RTRIM(LTRIM([NAME])) + '''', 1 FROM S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT6'

IF NOT EXISTS (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT7'))) AND SID IS NULL)
OR RTRIM(LTRIM(COALESCE((SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT7'))) AND SID IS NULL),'')))  IN ('','.','.  .')
	INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
	SELECT 'SALARY_OPTIONS', '', 'Настройка', 0, 'В общих настройках по зарплате не задан ''' + RTRIM(LTRIM([NAME])) + '''', 1 FROM S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT7'

--Проверка возможности удаления проводок
DECLARE @varKSnMonth INT, @varKSnYear INT
SELECT @varKSnMonth = MONTH(dbo.SALARYCALCPERIOD()), @varKSnYear = YEAR(dbo.SALARYCALCPERIOD())

-- Ссылки на проводки по ведомостям на выплату через банк, которые сформированы по ведомостям
-- с формированием операций по периоду ведомости и дата ведомости не совпадает с периодом ведомости
CREATE TABLE #PROV (LINK INT)
INSERT INTO #PROV (LINK)
SELECT
	R.LINK_RKO
FROM	
	dbo.SDOC S INNER JOIN dbo.S_OBJECTS O ON S.OBJECT = O.LINK
	INNER JOIN 
	(
		SELECT SD1.LINK_CARD, S1.LINK, REF_BASE = S1.DATE_CALC 
		FROM dbo.SDOC S1 INNER JOIN dbo.SDOC_VEDOM SD1 ON S1.LINK = SD1.LINK_UP
		WHERE S1.LINK_DEP = @DEP_LINK
		UNION
		SELECT SD2.LINK_CARD, S2.LINK, REF_BASE = S2.DATE_CALC 
		FROM dbo.SDOC S2 INNER JOIN dbo.SDOC_VEDOM_DGH SD2 ON S2.LINK = SD2.LINK_UP
		WHERE S2.LINK_DEP = @DEP_LINK
	) D ON S.LINK = D.LINK
	INNER JOIN dbo.SDOC_VEDOM_RKO R ON R.LINK_VEDOM = S.LINK
	INNER JOIN dbo.G_PROV GP ON GP.LINK = R.LINK_RKO
WHERE   
	MONTH(S.[DATE]) = @varKSnMonth AND YEAR(S.[DATE]) = @varKSnYear
	AND S.LINK_DEP = @DEP_LINK
	AND LINK_CARD IS NOT NULL
	AND YEAR(D.REF_BASE) * 100 + MONTH(D.REF_BASE) <>  YEAR(S.[DATE]) * 100 + MONTH(S.[DATE])
	AND GP.[OBJECT] = (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE= 'DOCUMENTS_SALARY')

-- Прочие проводки по зарплате
INSERT INTO #PROV (LINK)
SELECT LINK
FROM dbo.G_PROV
WHERE 
	[OBJECT]= (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE= 'DOCUMENTS_SALARY') 
	AND DEP = @DEP_LINK
	AND MONTH([DATE])=@varKSnMonth 
	AND YEAR([DATE])=@varKSnYear


INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
SELECT SO.CODE, '', 'Основание', G.LINK,
	'Невозможно переформировать проводки, т.к. в документе "' + SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104) + ' используется в качестве основания ' + O.INFO,
	1
FROM dbo.G_PROV G
INNER JOIN dbo.S_OBJECTS SO ON G.[OBJECT] = SO.LINK
INNER JOIN dbo.G_AVANSE_TABLE T ON T.LINK_UP = G.LINK
INNER JOIN dbo.BD_OSNOV O ON O.LINK = T.OSNOV AND  O.TP = 1
INNER JOIN #PROV P ON O.DOC_LINK = P.LINK

INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
SELECT distinct SO.CODE, '', 'Основание', G.LINK,
	'Невозможно переформировать проводки, т.к. в документе "' + SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104) + ' используется в качестве основания ' + O.INFO,
	1
FROM dbo.G_PROV G
INNER JOIN dbo.S_OBJECTS SO ON G.[OBJECT] = SO.LINK
INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP GAP ON GAP.LINK_UP = G2.LINK
INNER JOIN dbo.BD_OSNOV O ON O.LINK = GAP.AP1 AND  O.TP = 1
INNER JOIN #PROV P ON O.DOC_LINK = P.LINK


SELECT * FROM #TempControlTable order by 3
DROP TABLE #TempControlTable



GO


GRANT EXECUTE ON dbo.[SA_CONTROL_PROV] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_EXPORT_F1152028_502]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_EXPORT_F1152028_502]

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152028_502 (@iLINK_FORM INT)
AS
BEGIN
--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK VARCHAR (20),
		@OKATO VARCHAR (15),
		@OKATO_D VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT @DEP_LINK = LINK_ORGANIZATION,
			@dDATE_FORM	= BEGIN_DATE,
			@PERIOD_TYPE = PERIOD_TYPE,
			@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT @INN	= CONVERT (VARCHAR (10), INN_LONG),
			@KPP = CONVERT (VARCHAR (9), KPP),
			@IMNS = CONVERT (VARCHAR (4), IMNS),
			@OKVED = CONVERT (VARCHAR (8), OKVED),
			@DEP_NAME = [NAME],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT @NAME_RUK = IM,
			@FAM_RUK = FM,
			@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКАТО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT @KBK = ISNULL (COL2, ''),
		@OKATO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 1.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '120'

	SELECT @CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '130'

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '140'

	SELECT @Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT @NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT @SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '200'

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_IMUR_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE (ID INT IDENTITY (1,1),
				F_NAME VARCHAR(254) DEFAULT (''),
				OUT_TEXT TEXT DEFAULT (''))

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE @NAME_PROG VARCHAR(254),
		@VERS_PROG VARCHAR(254)

	SELECT @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK
	WHERE CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.02">')

-- Документ

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152028"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@cREORG_INN, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@cREORG_KPP, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущАв>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКАТО="' + CASE WHEN ISNULL (@OKATO, '') = ''
											THEN ISNULL (@OKATO_D, '')
											ELSE @OKATO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОст="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер СумАвИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущАв>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TASK_PROP
END 

GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152028_502] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[VX_UPGRADE_CLEAR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[VX_UPGRADE_CLEAR]

GO

CREATE       PROCEDURE [dbo].VX_UPGRADE_CLEAR
AS
if exists (select * from dbo.sysobjects where id = object_id(N'[object_values_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table object_values_u
if exists (select * from dbo.sysobjects where id = object_id(N'[object_values]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_values')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_var_values_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table object_var_values_u
if exists (select * from dbo.sysobjects where id = object_id(N'[object_var_values]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_var_values')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_property_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table object_property_u
if exists (select * from dbo.sysobjects where id = object_id(N'[object_property]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_property')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_navigator_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_navigator_u

if exists(select * from syscolumns sc where name = 'old_link' and id = OBJECT_ID('s_navigator'))
begin
	IF EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'tmp_index_for_old_link' and id = object_id(N'[dbo].[S_NAVIGATOR]'))
		drop index s_navigator.tmp_index_for_old_link
	alter table s_navigator
		drop column old_link
end

if exists (select * from dbo.sysindexes where name = N'IX_S_NAVIGATOR' and id = object_id(N'[dbo].[S_NAVIGATOR]'))
	drop index [dbo].[S_NAVIGATOR].[IX_S_NAVIGATOR]

if exists (select * from dbo.sysobjects where id = object_id(N'[s_navigator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_navigator')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_var_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table object_var_u
if exists (select * from dbo.sysobjects where id = object_id(N'[object_var]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_var')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_property_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_property_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_property]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_property')

if exists (select * from sysobjects where id = OBJECT_ID(N's_permissions_u') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_permissions_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_permissions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_permissions')

if exists (select * from sysobjects where id = OBJECT_ID(N's_dbobjects_u') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_dbobjects_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_dbobjects]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_dbobjects')

if exists (select * from sysobjects where id = OBJECT_ID(N's_tables_u') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_tables_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_tables]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_tables')

if exists (select * from sysobjects where id = OBJECT_ID(N's_release_u') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_release_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_release]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_release')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_objects_u]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table s_objects_u
if exists (select * from dbo.sysobjects where id = object_id(N'[s_objects]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_objects')

if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_FORMS_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table REPORT_FORMS_U

if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_TABLES_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table REPORT_TABLES_U

if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_ROWS_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table REPORT_ROWS_U

if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_COLOUMNS_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table REPORT_COLOUMNS_U
if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_FORMULA_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table REPORT_FORMULA_U
--if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_CONDITIONS_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
--	drop table REPORT_CONDITIONS_U
--if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_COND_VALUE_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
--	drop table REPORT_COND_VALUE_U
--if exists (select * from sysobjects where id = OBJECT_ID(N'REPORT_CONTROL_PARITIES_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
--	drop table REPORT_CONTROL_PARITIES_U
if exists (select * from sysobjects where id = OBJECT_ID(N'S_FILES_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table S_FILES_U
if exists (select * from sysobjects where id = OBJECT_ID(N'S_HISTORY_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table S_HISTORY_U
if exists (select * from sysobjects where id = OBJECT_ID(N'S_FILEPARTS_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table S_FILEPARTS_U
if exists (select * from sysobjects where id = OBJECT_ID(N'DICTION_U') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table DICTION_U
if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_OPTIONS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [REPORT_OPTIONS_U]
if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_CONTROL_ROWS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [REPORT_CONTROL_ROWS_U]
if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_CONTROL_RULES_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [REPORT_CONTROL_RULES_U]

if exists (select * from dbo.sysobjects where id = object_id(N'u_obj') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [u_obj]

if exists (select * from dbo.sysobjects where id = object_id(N'u_prop') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [u_prop]


if exists (select * from dbo.sysobjects where id = object_id(N'[EXPORT_FIELDS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [EXPORT_FIELDS_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[EXPORT_BLOCKS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [EXPORT_BLOCKS_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[EXPORT_MODELS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [EXPORT_MODELS_U]


if exists (select * from dbo.sysobjects where id = object_id(N'[S_BANK_FORMAT_BASE_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [S_BANK_FORMAT_BASE_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[S_GROUP_SID_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [S_GROUP_SID_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[DICTION_APP_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)   
	drop table [dbo].[DICTION_APP_U]  

if exists (select * from dbo.sysobjects where id = object_id(N'[OBJECT_VAR_U_DELETE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [OBJECT_VAR_U_DELETE]

if exists (select * from dbo.sysobjects where id = object_id(N'[ECONOMY_OPER_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [ECONOMY_OPER_U]

/*if exists (select * from dbo.sysobjects where id = object_id(N'[XOZ_OPER_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [XOZ_OPER_U]*/

if exists (select * from dbo.sysobjects where id = object_id(N'[JOURNAL_OPERATION_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [JOURNAL_OPERATION_U]


if exists (select * from dbo.sysobjects where id = object_id(N'[HISTORY_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [HISTORY_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[FAQ_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [FAQ_U]

if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_GROUP_KS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_GROUP_KS_U] 

if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_CONTROL_GROUP_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].REPORT_CONTROL_GROUP_U 

if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_FORM_GROUPS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].REPORT_FORM_GROUPS_U 

if exists (select * from dbo.sysobjects where id = object_id(N'[REPORT_FORM_GROUPS_REF_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].REPORT_FORM_GROUPS_REF_U 

if exists (select * from dbo.sysobjects where id = object_id(N'[R_FILES_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].R_FILES_U

if exists (select * from dbo.sysobjects where id = object_id(N'[R_FILEPARTS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].R_FILEPARTS_U

if exists (select * from dbo.sysobjects where id = object_id(N'[REMIND_QUERY_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].REMIND_QUERY_U

----Удалить все временные талицы, заканчивающиеся на _U
--DECLARE @TABLE_NAME VARCHAR(256), @SQL_SCRIPT VARCHAR(4000)
--WHILE EXISTS (SELECT NAME FROM SYS.TABLES WHERE RIGHT(NAME,2) = '_U')
--BEGIN

--	SELECT @TABLE_NAME = NAME FROM SYS.TABLES WHERE RIGHT(NAME,2) = '_U'

--	SET @SQL_SCRIPT = '
--	IF exists(select * from sysobjects where id = object_id(''[dbo].[' + @TABLE_NAME + ']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
--		drop table [dbo].[' + @TABLE_NAME + ']'

--	PRINT @SQL_SCRIPT
--	EXEC (@SQL_SCRIPT)

--	SET @TABLE_NAME = LEFT(@TABLE_NAME,LEN(@TABLE_NAME)-2)

--	SET @SQL_SCRIPT = '
--	if exists (select * from dbo.sysobjects where id = object_id(N'''+@TABLE_NAME+''') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
--		DBCC DBREINDEX (''' + @TABLE_NAME + ''')'
		
--	PRINT @SQL_SCRIPT
--	EXEC (@SQL_SCRIPT)
--END

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_KBK_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_KBK_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_CALC_FORMS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_CALC_FORMS_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_CALC_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_CALC_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_CALC_ROWS_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_CALC_ROWS_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_CALC_ATRIBUTE_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_CALC_ATRIBUTE_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[S_ACCOUNTS_EQUIVALENT_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[S_ACCOUNTS_EQUIVALENT_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[S_ACCOUNTS_NASTR_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[S_ACCOUNTS_NASTR_U]

IF exists (select * from sysobjects where id = object_id('[dbo].[S_ACCOUNTS_NASTR_KOSGU_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[S_ACCOUNTS_NASTR_KOSGU_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[S_ACCOUNTS_NEW_FOR_HO_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[S_ACCOUNTS_NEW_FOR_HO_U]

IF exists(select * from sysobjects where id = object_id('[dbo].[REPORT_KBK_HIST_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[REPORT_KBK_HIST_U]

GO


GRANT EXECUTE ON dbo.[VX_UPGRADE_CLEAR] 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_CALC_READ_DATA]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_CALC_READ_DATA]
END
GO
/*******************************************************************************

   © Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- Процедура чтения данных из БКС/Сметы (в зависимости от глобальной настройки). А также записи их в кэш
-- Вход: @dBEGIN_DATE               - начало расчетного период
--       @dEND_DATE                 - конец расчетного период
-- Выход: CREATE TABLE #CALC_DATA ( KBK_DT     CHAR(17),
--                          KBK_TYPE_DT  TINYINT,
--                          ACC_DT       CHAR(6),
--                          SGU_DT       CHAR(3),
--                          EKR_DT       CHAR(3),
--                          KBK_KT       CHAR(17),
--                          KBK_TYPE_KT  TINYINT,
--                          ACC_KT       CHAR(6),
--                          SGU_KT       CHAR(3),
--                          EKR_KT       CHAR(3),                          
--                          DATE         DATETIME,
--                          SUMMA        NUMERIC(20,2))
--              -1 - Нет такой формы
CREATE PROCEDURE dbo.[RO_CALC_READ_DATA]
   @dBEGIN_DATE            DATETIME,
   @dEND_DATE              DATETIME,
   @dDEP_INN               VARCHAR(20)
AS

SET NOCOUNT ON
DECLARE @vcServer VARCHAR(100), @vcBase VARCHAR(100), @vcStr VARCHAR(100), @nvExecStr NVARCHAR(4000), @uid UNIQUEIDENTIFIER

SET @uid = NEWID()

exec dbo.X_GET_OPTION 'REPORT_ORTIONS_SERVER_BKS', 0 , @vcStr OUTPUT 	
SET  @vcServer = RTRIM(@vcStr)     

exec dbo.X_GET_OPTION 'REPORT_ORTIONS_BASE_BKS' ,0 , @vcStr OUTPUT 	
SET @vcBase = RTRIM(@vcStr)

SET @nvExecStr = 'EXEC [' + RTRIM(@vcServer) + '].[' + RTRIM(@vcBase) + '].[dbo].[PROV2SMETA] @uid, @dBEGIN_DATE, @dEND_DATE, 2 ' + 
   'INSERT #CALC_DATA (KBK_DT, KBK_TYPE_DT, ACC_DT, SGU_DT, EKR_DT, KBK_KT, KBK_TYPE_KT, ACC_KT, SGU_KT, EKR_KT, DATE, SUMMA, [OPERS]) ' + 
   'SELECT KBK_CODE_DT, KBK_TYPE_DT, ACC_CODE_DT, SGU_CODE_DT, EKR_CODE_DT, KBK_CODE_KT, KBK_TYPE_KT, ACC_CODE_KT, SGU_CODE_KT, EKR_CODE_KT, DATE_PROV, SUM(SUMMA), Types ' +
   'FROM  [' + RTRIM(@vcServer) + '].[' + RTRIM(@vcBase) + '].[dbo].DOC2SMETA WHERE UID = @UID AND DEP_INN = @dDEP_INN AND DATE_PROV >= @dBEGIN_DATE AND DATE_PROV <= @dEND_DATE ' +
   ' GROUP BY KBK_CODE_DT, KBK_TYPE_DT, ACC_CODE_DT, SGU_CODE_DT, EKR_CODE_DT, KBK_CODE_KT, KBK_TYPE_KT, ACC_CODE_KT, SGU_CODE_KT, EKR_CODE_KT, DATE_PROV, Types ' + 
   'DELETE [' + RTRIM(@vcServer) + '].[' + RTRIM(@vcBase) + '].[dbo].DOC2SMETA WHERE UID = @UID'

PRINT @nvExecStr   
EXEC sp_executesql @nvExecStr, N'@dBEGIN_DATE datetime, @dEND_DATE datetime, @dDEP_INN varchar(20), @uid UNIQUEIDENTIFIER', @uid = @uid, @dBEGIN_DATE = @dBEGIN_DATE, @dEND_DATE = @dEND_DATE, @dDEP_INN = @dDEP_INN     


--CREATE PROCEDURE dbo.PROV2SMETA
--		@uid uniqueidentifier = null,
--		@dDate_1 datetime /*Начало периода*/,
--		@dDate_2 datetime /*Конец периода*/,
--		@nOption_4 int = 4 /*Уровень*/,
--		@nOtborLink1 int = 0 /*Операции*/,
--		@nOtborLink2 int = 0 /*Проводки*/,
--		@nOtborLink3 int = 0 /*Счета бюджета*/,
--		@nOtborLink4 int = 0 /*Субсчета*/,
--		@nOtborLink5 int = 0 /*Субконто*/,
--		@nOtborLink6 int = 0 /*Бюджеты*/,
--		@nOtborLink7 int = 0 /*Администраторы (Администратор-Д)*/,
--		@nOtborLink8 int = 0 /*Доходы (Администратор-Д)*/,
--		@nOtborLink9 int = 0 /*Типы проводок*/,
--		@nOtborLink10 int = 0 /*ОКАТО (Администратор-Д)*/,
--		@nOtborLink11 int = 0 /*Счета*/,
--		@nOtborLink12 int = 0 /*Корреспонденты*/,
--                 @nMode INT = 0  -- 0 -smeta, 1- svod




RETURN 0      

GO
GRANT ALL ON dbo.[RO_CALC_READ_DATA] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*
EXEC dbo.[RA_ERROR_DELETE] 'R_CALC_READ_OPTION'
EXEC dbo.[RA_ERROR_UPDATE] 'R_CALC_READ_OPTION',0,'Нет ошибок. Успех.',0
EXEC dbo.[RA_ERROR_UPDATE] 'R_CALC_READ_OPTION',-1,'Не найдена форма',0
*/
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 @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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHECK_CR_COLS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_CR_COLS]
GO

--проверка наличия строк в формах 
CREATE                     PROCEDURE dbo.RO_CHECK_CR_COLS
  @code_form1 varchar(500),
  @code_form2 varchar(500),
  @table int, --номер таблицы
  @mask1 varchar(50), 
  @mask2 varchar(50), 
	@filter1 varchar(1000),
	@filter2 varchar(1000),
   @col1    VARCHAR(250) = NULL,
   @col2    VARCHAR(250) = NULL
 AS
declare @lsf1 int,@lsf2 int,@i int,@link_table1 int,@link_table2 int,@link_form1 int,@link_form2 int,@nomErr int,@link_col1 int,@link_col2 int, @ExecStr nvarchar(4000)
select @code_form1=codeForm,@lsf1=lsf,@link_form1=linkForm from  #ListForms where codeForm like @code_form1
select @code_form2=codeForm,@lsf2=lsf,@link_form2=linkForm from  #ListForms where codeForm like @code_form2
select @link_table1 = link_table from #report_tables where link_form = @link_form1 and orders = @table
select @link_table2 = link_table from #report_tables where link_form = @link_form2 and orders = @table

IF @lsf2 is null or @lsf1 is null
 RETURN 

--итоговые строки
create table #TMP_ITOG1 (link_table int,code varchar(50))
create table #TMP_ITOG2 (link_table int,code varchar(50))

insert #TMP_ITOG1 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form1,1)  

if left(@code_form1,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form1,1)  
end

if left(@code_form1,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form1,1)  
	insert #TMP_ITOG1 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form1,1)  
end

insert #TMP_ITOG2 (link_table,code)
select link_table,code from dbo.RA_SELECT_FORM_TOTALS(0,@link_form2,1)  

if left(@code_form2,7) in ('0503117', '0503127', '0503114')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_17(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@link_form2,1)  
end

if left(@code_form2,7) in ('0503317', '0503314')
begin
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_DOH_20(0,@link_form2,1)  
	insert #TMP_ITOG2 (link_table,code)
	select link_table,code from dbo.RO_SELECT_FORM_TOTALS_IST_23(0,@link_form2,1)  
end

declare @cstr varchar(8000)
set @i=@table 


IF @code_form1 in ('0503117M','0503127M', '0503127G', '0503117G') and @table=2
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 and substring(code_row,15,3) IN ('200','000','210','220','230','240','250','260','300','500','600')
	end

IF @code_form1 in ('0503317M') and @table=3 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and substring(code_row,1,3) IN ('751', '752', '753', '754', '755', '756')
	end

IF @code_form1 in ('0503317M') and @table=1 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00087000000000000151', '00087000000000001151', '00087000000000002151', '00087000000000000120')
	end

IF @code_form1 in ('0503317M') and @table=2 AND @code_form2 in ('0503152M')
	begin
		insert #TMP_ITOG1 (link_table,code)
		select distinct @link_table1,code_row from #report_dinamics where link_sf=@lsf1 
		and (code_row) IN ('00097000000000000251', '00097000000000000231')
	end

		


create table #err (code varchar(250),code_form1 varchar(50),code_form2 varchar(50))



if @mask2 = '' and @mask1 = '' and @filter1 = '' and @filter2 = ''
BEGIN
	insert #err (code,code_form1,code_form2)		
	select distinct dbo.RA_MASK(code_row,@mask2),@code_form2,@code_form1 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.orders = @table
	 where link_sf=@lsf2 and  float_val<>0 and CHARINDEX(',' + LTRIM(STR(RC.orders)) + ',', isnull(',' + @col2 + ',', ',' + LTRIM(STR(RC.orders)) + ',')) > 0
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 and link_col in (select link_col from #report_coloumns where link_table=@link_table1 and CHARINDEX(',' + LTRIM(STR(orders)) + ',', isnull(',' + @col1 + ',', ',' + LTRIM(STR(orders)) + ',')) > 0 ) and float_val<>0   and dbo.RA_Mask(A.code_row, @mask2) = dbo.RA_Mask(B.code_row, @mask1))
		and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)
end
else
begin
	set @ExecStr = 'insert #err (code,code_form1,code_form2)		
	select distinct ' + case when @mask2 = '' then 'code_row' else 'dbo.RA_MASK(code_row,@mask2)' end + ',@code_form2,@code_form1 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.link_table = @link_table2
	 where link_sf=@lsf2 and CHARINDEX('','' + LTRIM(STR(RC.orders)) + '','', isnull('','' + @col2 + '','', '','' + LTRIM(STR(RC.orders)) + '','')) > 0 and  float_val<>0 ' + case when @filter2 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter2, 'code', 'A.Code_Row'), ']',')'), '[', '(') end + '
		and not exists(select * from #report_dinamics B where link_sf=@lsf1 ' + case when @filter1 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter1, 'code', 'B.Code_Row'), ']',')'), '[', '(') end + ' and link_col in (select link_col from #report_coloumns where link_table=@link_table1 and CHARINDEX('','' + LTRIM(STR(orders)) + '','', isnull('','' + @col1 + '','', '','' + LTRIM(STR(orders)) + '','')) > 0) and float_val<>0   and ' + case when @mask2 = '' then 'A.code_row' else 'dbo.RA_Mask(A.code_row, @mask2)' end + ' = ' + case when @mask1 = '' then 'B.Code_Row' else 'dbo.RA_Mask(B.code_row, @mask1)' end + ')
	and not exists(select * from #tmp_itog2 B where B.link_table=@link_table2 and A.code_row=B.code)'

print @ExecStr
	exec sp_executesql @ExecStr, N'@mask1 varchar(50), @mask2 varchar(50), @lsf1 int, @lsf2 int, @link_table1 int, @link_table2 int, @code_form2 varchar(30),@code_form1 varchar(30), @col1 varchar(250), @col2 varchar(250)', @mask1 = @mask1, @mask2 = @mask2, @lsf1 = @lsf1, @lsf2 = @lsf2, @link_table1 = @link_table1, @link_table2 = @link_table2, @code_form2=@code_form2,@code_form1=@code_form1, @col1 = @col1, @col2 = @col2
end

IF exists(select * from #err)
	begin
		select @nomErr=MAX(ORDERS) FROM #res 
		insert #Res(orders, res, cdoc, ctable)	
		select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
		from #err
		delete #err
	end

delete #err
if @mask2 = '' and @mask1 = '' and @filter1 = '' and @filter2 = ''
begin
	insert #err (code,code_form1,code_form2)		
	select distinct dbo.RA_MASK(code_row,@mask1),@code_form1,@code_form2 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.orders = @table
	where link_sf=@lsf1 and float_val<>0 and CHARINDEX(',' + LTRIM(STR(RC.orders)) + ',', isnull(',' + @col1 + ',', ',' + LTRIM(STR(RC.orders)) + ',')) > 0
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 and link_col in (select link_col from #report_coloumns where link_table=@link_table2 and CHARINDEX(',' + LTRIM(STR(orders)) + ',', isnull(',' + @col2 + ',', ',' + LTRIM(STR(orders)) + ',')) > 0) and float_val<>0   and dbo.RA_MASK(A.code_row,@mask1)=dbo.RA_MASK(B.code_row,@mask2))
		and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)
end
else
begin
	set @ExecStr = 'insert #err (code,code_form1,code_form2)		
	select distinct ' + case when @mask1 = '' then 'code_row' else 'dbo.RA_MASK(code_row,@mask1)' end + ',@code_form1,@code_form2 
	from #report_dinamics A join #report_coloumns RC on A.link_col = RC.link_col
			join #report_tables RT on RC.link_table = RT.link_table and RT.link_table = @link_table1
	 where link_sf=@lsf1 and CHARINDEX('','' + LTRIM(STR(RC.orders)) + '','', isnull('','' + @col1 + '','', '','' + LTRIM(STR(RC.orders)) + '','')) > 0 and   float_val<>0 ' + case when @filter1 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter1, 'code', 'A.Code_Row'), ']',')'), '[', '(') end + '
		and not exists(select * from #report_dinamics B where link_sf=@lsf2 ' + case when @filter2 = '' then '' else 'and ' + REPLACE(REPLACE(REPLACE(@filter2, 'code', 'B.Code_Row'), ']',')'), '[', '(') end + ' and link_col in (select link_col from #report_coloumns where link_table=@link_table2 and CHARINDEX('','' + LTRIM(STR(orders)) + '','', isnull('','' + @col2 + '','', '','' + LTRIM(STR(orders)) + '','')) > 0) and float_val<>0   and ' + case when @mask1 = '' then 'A.code_row' else 'dbo.RA_Mask(A.code_row, @mask1)' end + ' = ' + case when @mask2 = '' then  'B.code_row' else 'dbo.RA_Mask(B.code_row, @mask2)' end + ')
	and not exists(select * from #tmp_itog1 B where B.link_table=@link_table1 and A.code_row=B.code)'
print @ExecStr
	exec sp_executesql @ExecStr, N'@mask1 varchar(50), @mask2 varchar(50), @lsf1 int, @lsf2 int, @link_table1 int, @link_table2 int, @code_form2 varchar(30),@code_form1 varchar(30),@col1 varchar(250), @col2 varchar(250)', @mask1 = @mask1, @mask2 = @mask2, @lsf1 = @lsf1, @lsf2 = @lsf2, @link_table1 = @link_table1, @link_table2 = @link_table2, @code_form2=@code_form2,@code_form1=@code_form1, @col1 = @col1, @col2 = @col2
end
	
IF exists(select * from #err)
	begin
		select @nomErr=MAX(ORDERS) FROM #res 
		insert #Res(orders, res, cdoc, ctable)	
		select @nomErr,'-','Код:'+rtrim(code)+' из формы '+rtrim(code_form1)+' отсутствует в форме ' +rtrim(code_form2),'№'+ltrim(str(@i))
		from #err
		delete #err
	end

drop table #err

select 0 
GO
GRANT ALL ON dbo.[RO_CHECK_CR_COLS] 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.[BK_SAVE_DOC_INVOICE_COR_IN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_SAVE_DOC_INVOICE_COR_IN]

GO
CREATE PROCEDURE dbo.BK_SAVE_DOC_INVOICE_COR_IN
	@intLINK	INT	OUTPUT,
	@strNUMBER	VARCHAR (30) = null,
	@dDOC_DATE	DATETIME = null,
	@dDOC_DATE_PROV	DATETIME = null,
	@nDOC_Summa	NUMERIC(19,2) = 0,
	@strComment	VARCHAR(254) = null,
	@intDEP_LINK	INT	=	NULL,

	@intOSNOV_LN    INT = null,
	@strCOR_NUM	VARCHAR(30) = '',
	@dCOR_DATE	DATETIME = NULL,
	@intINBOOK     TINYINT = 0
AS
BEGIN
	SET LOCK_TIMEOUT 30000
	SET IMPLICIT_TRANSACTIONS ON

	DECLARE @intERROR	tinyint,
		@strVALUE	varchar(7000),
		@strEventText	varchar(254),
		@inttrancount	int,
	
		@intDOC_SOBJ_LINK	INT,
		@intSOBJ_LINK	INT

	SET @inttrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	BEGIN TRAN
	COMMIT TRAN

	--Проверка рабочего периода
	IF @dDOC_DATE_PROV is not null and not exists(Select * from admin_info Where @dDOC_DATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	--Вставка/обновление G_PROV
	SET @intDOC_SOBJ_LINK = dbo.GetObjLink ('DOCUMENTS_INVOICE_COR_IN')

	EXECUTE @intERROR = dbo.X_UPDATE_G_PROV
			@intLINK OUTPUT,
			@strNUMBER,
			@dDOC_DATE,
			@intDOC_SOBJ_LINK,
			@dDOC_DATE_PROV,
			@nDOC_Summa,
			@strComment,
			0,
			@intDEP_LINK,
			DEFAULT

	IF @intERROR <> 0
		RETURN @intERROR

	EXECUTE @intERROR = dbo.BK_UPDATE_G_PROV_INVOICE_COR
			@intDOC_LINK	=	@intLINK, 
			@intOSNOV	=	@intOSNOV_LN,
			@strCOR_NUM	=	@strCOR_NUM,
			@dCOR_DATE	=	@dCOR_DATE,
			@INBOOK		=	@intINBOOK

	IF @intERROR <> 0
		RETURN @intERROR

	--Событие системного журнала
	SET @strEventText = 'Корректировочный счет-фактура (полученный)' + ' №' + RTRIM(@strNUMBER) + ' от ' + convert(varchar, @dDOC_DATE, 104)
	EXECUTE dbo.WF_GENERATEEVENT 'Сохранение документа',
			@strEventText,
			@intDOC_SOBJ_LINK,
			'G_PROV',
			@intLINK

	IF @@TRANCOUNT > @inttrancount
		COMMIT TRAN

	RETURN 0
END



GO


GRANT EXECUTE ON dbo.[BK_SAVE_DOC_INVOICE_COR_IN] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_BASE_SUM_PAY_MONTH_KBK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_BASE_SUM_PAY_MONTH_KBK]

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE    PROCEDURE [dbo].SALARY_BASE_SUM_PAY_MONTH_KBK


 @varKSRefPay 	int,
 @varKSlinkEmpl	 int,
 @varKSMonth	int,
 @varKSYear	int		 
AS  
declare @varKSdDate1 datetime, @varKSdDate2 datetime

SELECT * INTO #S_J_C_Short FROM dbo.S_J_C_Short WHERE LINK_EMPL = @varKSlinkEmpl

if @varKSMonth<1 or @varKSMonth>12
	return -1
SET @varKSdDate1 = convert(datetime,'01.'+str(@varKSMonth)+'.'+str(@varKSYear),104)
SET @varKSdDate2 =DATEADD(M,1,@varKSdDate1) -1

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

SELECT 			
			[CODE_PAY] = CODE_PAYS,
			[NAME_PAY] = NAME_PAYS,
			[WAY_CALC],
			SJ.link_PAYS as [LINK_PAY],
			SUM(SJ.summa) as [SUMMA],
			T.KOEF AS [KOEF], 
			LINK_INC, LINK_VKR
INTO #TMP
FROM #S_J_C_Short SJ INNER JOIN dbo.group_pays(@varKSRefPay) T ON SJ.link_PAYS=T.PAY_LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP
WHERE SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.DATE1>=@varKSdDate1 AND SJ.DATE2<=@varKSdDate2 AND WAY_CALC <> 6
	AND COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2-- суммы по перерасчету берем в следующем блоке
GROUP BY  SJ.link_PAYS, T.KOEF, LINK_INC, CODE_PAYS, NAME_PAYS, WAY_CALC, LINK_VKR
UNION
SELECT 			
			[CODE_PAY] = CODE_PAYS,
			[NAME_PAY] = NAME_PAYS,
			[WAY_CALC],
			SJ.link_PAYS as [LINK_PAY],
			SUM(SJ.summa) as [SUMMA],
			T.KOEF AS [KOEF],
			LINK_INC, LINK_VKR
FROM #S_J_C_Short SJ INNER JOIN dbo.group_pays(@varKSRefPay) T ON SJ.link_PAYS=T.PAY_LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP
WHERE SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.PERIOD_BEGIN>=@varKSdDate1 AND SJ.PERIOD_END<=@varKSdDate2 
	AND 
	(	WAY_CALC=6 
		OR
		COALESCE(R.LINK_UP,0) > 0 AND @DOCUMENTS_RECALC_OPT1 = 1-- суммы по перерасчету берем здесь, чтобы операции попали по периоду расчета
	)
GROUP BY  SJ.link_PAYS, T.KOEF, LINK_INC, CODE_PAYS, NAME_PAYS, WAY_CALC, LINK_VKR

IF dbo.sa_get_option_by_code('ARCHE_OPT3') = 1
BEGIN
	
	/*
	Игнатьев А.Н. 2007-02-05
		В соответствии с ФЗ "255-ФЗ от 29.12.2006 ст.14, п.2
		Учитываем доходы, с которых уплачивались взносы в ФСС.
		Мат. помощь и пр. доходы, на которые предоставляется льгота 3000р. берем за минусом этой льготы
	*/
	
	DECLARE @SPR TABLE (LINK_PAY int, LINK_DOH int, LINK_VYCH int, PREDEL numeric(18,2))
	
	/*Справочник пределов льгот*/
	insert into @SPR(LINK_PAY, LINK_DOH, LINK_VYCH, PREDEL)
	select DISTINCT LINK_PAY= P.link, LINK_DOH= DTI.LINK, LINK_VYCH= REF_PAY,  PREDEL from dbo.pays P inner join dbo.DICTIONARY_TYP_INCOMS DTI on P.link_inc = DTI.link 
		inner join dbo.Salary_deduct_esn(@varKSdDate1) SDE on SDE.ref_pay = DTI.ref_deduct
	
	DECLARE @PREDEL TABLE (LINK_DOH int, PREDEL numeric(18,2))
	
	/*Для каждого кода дохода рассчитывается остаток льготы*/
	INSERT INTO @PREDEL (LINK_DOH, PREDEL)
	SELECT DISTINCT SPR.LINK_DOH, OSTATOK = (case when SPR.PREDEL > SUM(SJC.SUMMA) then SPR.PREDEL - SUM(SJC.SUMMA) else 0 end)
	from #S_J_C_Short SJC inner join #tmp TMP on SJC.link_PAYS = TMP.LINK_PAY 
			inner join @SPR SPR ON TMP.LINK_PAY = SPR.LINK_PAY
	WHERE SJC.LINK_EMPL = @varKSlinkEmpl AND SJC.DATE1>=convert(datetime,'01.01'+'.'+str(@varKSYear),104) AND SJC.DATE2<@varKSdDate1
	GROUP BY SPR.LINK_DOH, SPR.PREDEL
	
	/*Если какой доход со льготой не использовался вовсе, добавляем льготу целиком в размере ее предела*/
	INSERT INTO @PREDEL (LINK_DOH, PREDEL)
	SELECT DISTINCT LINK_DOH, PREDEL FROM @SPR where LINK_DOH NOT IN (SELECT LINK_DOH FROM @PREDEL)

	/*Для каждого вида дохода с льготой*/
	DECLARE @Cur1 CURSOR, @LINK_DOH int, @PREDEL_SUM numeric(18,2), @Cur2 CURSOR, @LINK_PAY INT, @SUMMA1 numeric(18,2)
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR Select * from @PREDEL where PREDEL > 0
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR Select LINK_PAY, SUMMA from #tmp where LINK_INC = @LINK_DOH and summa > 0
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_PAY, @SUMMA1
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN	
					/*Уменьшаем сумму начисления на сумму льготы, т.к. со суммы льготы не отчислялии в ФСС*/
					UPDATE #tmp SET SUMMA = (CASE WHEN @PREDEL_SUM > 0 and summa - @PREDEL_SUM > 0 then summa - @PREDEL_SUM else 0 end) where LINK_PAY = @LINK_PAY
					/*Рассчитаем остаток льготы*/
					SET @PREDEL_SUM = @PREDEL_SUM - (Select @SUMMA1 - SUMMA from #tmp where LINK_PAY = @LINK_PAY)
				END
				FETCH NEXT FROM @Cur2 INTO @LINK_PAY, @SUMMA1
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END
		FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1
END

Select * from #tmp order by REPLACE(STR(CODE_PAY,10),' ', 0)




GO


GRANT EXECUTE ON dbo.[SALARY_BASE_SUM_PAY_MONTH_KBK] 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_ZAYAVKA_F_VIL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_ZAYAVKA_F_VIL]
GO




/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.FB_ZAYAVKA_F_VIL
	@dDate 		DATETIME = null,
	@iDocLink	int = null,
	@iDopEkr 	tinyint = 1,
	@iZB		tinyint = 0,
	@iFin		tinyint = 1


AS

DECLARE @iDepLink	INT,
	@iYear		INT,
	@dDateB		datetime,
	@dDateBM	datetime	


set @iDepLink = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
set @iYear = year(@dDate)
set @dDateB = dbo.DateBeginOfYear(@dDate)
set @dDateBM = dbo.DateBeginOfMonth(@dDate)


-- Ассигнования
DECLARE @tAssign TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2))

--Кассовый план
DECLARE @tKPlan TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2))

--Кассовый план начало месяца
DECLARE @tKPlanBM TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2))

-- Кассовый расход 
DECLARE @tKassa TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2))

-- Кассовый расход начало месяца
DECLARE @tKassaBM TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2))

-- Финансирование
DECLARE @tFinans TABLE(
	VKR 	INT,
	EKR 	INT,
	DOP_CL 	INT,
	DEP 	INT,
	SUMMA 	NUMERIC(28,2),
	TITLE   varchar(256))

DECLARE @tTemp TABLE( 
	KBK 	 INT,
	EKR 	 INT, 
	DOP_CL 	 INT, 
	DEP 	 INT,
	SUMMA_A	 NUMERIC(28,2),
	SUMMA_KR NUMERIC(28,2),
	SUMMA_F	 NUMERIC(28,2),
	SALDO_KP NUMERIC(28,2),
	SALDO_KPBM NUMERIC(28,2),
	TITLE    varchar(256))

DECLARE @tTempGroup TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	DEP 	 INT,
	SUMMA_A	 NUMERIC(28,2),
	SUMMA_KR NUMERIC(28,2),
	SUMMA_F	 NUMERIC(28,2),
	SALDO_KP NUMERIC(28,2),
	SALDO_KPBM NUMERIC(28,2),
	TITLE    varchar(256),
	DOP_EKR	INT)

DECLARE @tTempDopEkr TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	DEP 	 INT,
	SUMMA_A	 NUMERIC(28,2),
	SUMMA_KR NUMERIC(28,2),
	SUMMA_F	 NUMERIC(28,2),
	SALDO_KP NUMERIC(28,2),
	SALDO_KPBM NUMERIC(28,2),
	TITLE    varchar(256),
	DOP_EKR	INT)

DECLARE @tTempDopEkr2 TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	DEP 	 INT,
	SUMMA_A	 NUMERIC(28,2),
	SUMMA_KR NUMERIC(28,2),
	SUMMA_F	 NUMERIC(28,2),
	SALDO_KP NUMERIC(28,2),
	SALDO_KPBM NUMERIC(28,2),
	TITLE    varchar(256),
	DOP_EKR	INT)



-- Ассигнования
INSERT INTO @tAssign
SELECT R.VKR, R.EKR, isnull(R.DOP_CL,0), case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end, sum(R.SUMMA)
FROM dbo.FB_REST_FINANS_PERIOD(	@dDateB, @dDate, 'FINANS_ASSIGN', '1', 1, null) R
left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC
where @iZB = 1 or @iZB = 0 and isnull(R.DEP, DA.LINK_UP) = @iDepLink
GROUP BY R.VKR, R.EKR, R.DOP_CL, case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end



--Кассовый план
INSERT INTO @tKPlan
SELECT R.VKR, R.EKR, isnull(R.DOP_CL,0), case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end, sum(R.SUMMA)
FROM dbo.FB_REST_FINANS_PERIOD(	@dDateB, @dDate, 'FB_PLAN', '1', 1, null) R
left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC
where @iZB = 1 or @iZB = 0 and isnull(R.DEP, DA.LINK_UP) = @iDepLink
GROUP BY R.VKR, R.EKR, R.DOP_CL, case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end
/*SELECT FT.VKR, FT.EKR, isnull(FT.DOP_CL,0), case @iZB when 0 then isnull(G.DEP,0) else 0 end, sum(FT.SUMMA)
FROM dbo.G_PROV G
inner join dbo.S_OBJECTS SO on SO.LINK = G.OBJECT and left(SO.CODE,7) = 'FB_PLAN'
inner join dbo.FINANSE_PLAN_SUMM FT on FT.LINK_UP = G.LINK 
WHERE G.DATE_PROV between @dDateB and @dDate and (@iZB = 1 or @iZB = 0 and G.DEP = @iDepLink)
GROUP BY VKR, EKR, DOP_CL, case @iZB when 0 then isnull(G.DEP,0) else 0 end*/

--Кассовый план
INSERT INTO @tKPlanBM
SELECT R.VKR, R.EKR, isnull(R.DOP_CL,0), case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end, sum(R.SUMMA)
FROM dbo.FB_REST_FINANS_PERIOD(	@dDateB, @dDateBM, 'FB_PLAN', '1', 1, null) R
left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC
where @iZB = 1 or @iZB = 0 and isnull(R.DEP, DA.LINK_UP) = @iDepLink
GROUP BY R.VKR, R.EKR, R.DOP_CL, case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end
/*SELECT FT.VKR, FT.EKR, isnull(FT.DOP_CL,0), case @iZB when 0 then isnull(G.DEP,0) else 0 end, sum(FT.SUMMA)
FROM dbo.G_PROV G
inner join dbo.S_OBJECTS SO on SO.LINK = G.OBJECT and left(SO.CODE,7) = 'FB_PLAN'
inner join dbo.FINANSE_PLAN_SUMM FT on FT.LINK_UP = G.LINK 
WHERE G.DATE_PROV between @dDateB and @dDateBM and (@iZB = 1 or @iZB = 0 and G.DEP = @iDepLink)
GROUP BY VKR, EKR, DOP_CL, case @iZB when 0 then isnull(G.DEP,0) else 0 end
*/


exec dbo.BufferClear 'ISP_KRash'

INSERT INTO BUFFER (link, id)
select link, 'ISP_KRash' from s_accounts where code like '%304.05%'


-- Кассовый расход 
INSERT INTO @tKassa
SELECT 	KBK, EKR, isnull(AP2,0), case @iZB when 0 then isnull(DEP_LINK,0) else 0 end, sum(K_SUMMA) - SUM(D_SUMMA)
from ARestOborotByAccounts (@dDateB, @dDate, 'ISP_KRash')
where (@iZB = 1 or @iZB = 0 and DEP_LINK = @iDepLink)
group by KBK, EKR, AP2,case @iZB when 0 then isnull(DEP_LINK,0) else 0 end

INSERT INTO @tKassaBM
SELECT 	KBK, EKR, isnull(AP2,0), case @iZB when 0 then isnull(DEP_LINK,0) else 0 end, sum(K_SUMMA) - SUM(D_SUMMA)
from ARestOborotByAccounts (@dDateB, @dDateBM, 'ISP_KRash')
where (@iZB = 1 or @iZB = 0 and DEP_LINK = @iDepLink)
group by KBK, EKR, AP2,case @iZB when 0 then isnull(DEP_LINK,0) else 0 end

exec dbo.BufferClear 'ISP_KRash'

-- Финансирование
INSERT INTO @tFinans
SELECT R.VKR, R.EKR, isnull(R.DOP_CL,0), case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end, sum(R.SUMMA), max(R.TITLE)
FROM dbo.FB_REST_FINANS_PERIOD(	@dDate, @dDate, 'FB_ZAYAVKA', '1', 1, null) R
left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = R.DEP_ACC
where @iZB = 1 or @iZB = 0 and isnull(R.DEP, DA.LINK_UP) = @iDepLink
GROUP BY R.VKR, R.EKR, R.DOP_CL, case @iZB when 0 then coalesce(R.DEP, DA.LINK_UP,0) else 0 end
/*SELECT FT.VKR, FT.EKR, isnull(FT.DOP_CL,0), case @iZB when 0 then isnull(G.DEP,0) else 0 end, sum(FT.SUMMA),  max(FT.TITLE)
FROM dbo.G_PROV G
inner join dbo.S_OBJECTS SO on SO.LINK = G.OBJECT and SO.CODE = 'FB_ZAYAVKA'
inner join dbo.FINANSE_PLAN_SUMM FT on FT.LINK_UP = G.LINK 
WHERE (G.DATE_PROV = @dDate and @iDocLink is null or G.LINK = @iDocLink and @iDocLink is not null) and (@iZB = 1 or @iZB = 0 and G.DEP = @iDepLink)
GROUP BY VKR, EKR, DOP_CL, case @iZB when 0 then isnull(G.DEP,0) else 0 end
*/
insert into @tTemp
SELECT CD.VKR, CD.EKR, CD.DOP_CL, CD.DEP,
	SUMMA_A  = ISNULL(A.SUMMA,0),
	SUMMA_KR = ISNULL(K.SUMMA,0),
	SUMMA_F  = ISNULL( F.SUMMA,0),
	SALDO_KP = ISNULL(KP.SUMMA,0) - ISNULL(K.SUMMA,0),
	SALDO_KPBM = ISNULL(KPBM.SUMMA,0) - ISNULL(KBM.SUMMA,0),
	TITLE 	 = ISNULL(F.TITLE,'')
FROM (SELECT VKR, EKR, DOP_CL, DEP FROM @tAssign where @iFin = 0 UNION
	SELECT VKR, EKR, DOP_CL, DEP FROM @tKPlan where @iFin = 0 UNION
	SELECT VKR, EKR, DOP_CL, DEP FROM @tKassa where @iFin = 0 UNION
	SELECT VKR, EKR, DOP_CL, DEP FROM @tKPlanBM where @iFin = 0 UNION
	SELECT VKR, EKR, DOP_CL, DEP FROM @tKassaBM where @iFin = 0 UNION
	SELECT VKR, EKR, DOP_CL, DEP FROM @tFinans) CD
LEFT JOIN @tAssign A ON isnull(CD.VKR,0) = isnull(A.VKR,0) AND isnull(CD.EKR,0) = isnull(A.EKR,0) AND CD.DOP_CL = A.DOP_CL AND CD.DEP = A.DEP
LEFT JOIN @tKPlan KP  ON isnull(CD.VKR,0) = isnull(KP.VKR,0) AND isnull(CD.EKR,0) = isnull(KP.EKR,0) AND CD.DOP_CL = KP.DOP_CL AND CD.DEP = KP.DEP
LEFT JOIN @tKassa K  ON isnull(CD.VKR,0) = isnull(K.VKR,0) AND isnull(CD.EKR,0) = isnull(K.EKR,0) AND CD.DOP_CL = K.DOP_CL AND CD.DEP = K.DEP
LEFT JOIN @tKPlanBM KPBM  ON isnull(CD.VKR,0) = isnull(KPBM.VKR,0) AND isnull(CD.EKR,0) = isnull(KPBM.EKR,0) AND CD.DOP_CL = KPBM.DOP_CL AND CD.DEP = KPBM.DEP
LEFT JOIN @tKassaBM KBM  ON isnull(CD.VKR,0) = isnull(KBM.VKR,0) AND isnull(CD.EKR,0) = isnull(KBM.EKR,0) AND CD.DOP_CL = KBM.DOP_CL AND CD.DEP = KBM.DEP
LEFT JOIN @tFinans F  ON isnull(CD.VKR,0) = isnull(F.VKR,0) AND isnull(CD.EKR,0) = isnull(F.EKR,0) AND CD.DOP_CL = F.DOP_CL AND CD.DEP = F.DEP


INSERT INTO @tTempGroup
SELECT  KBK, EKR, DOP_CL, DEP, sum(SUMMA_A), sum(SUMMA_KR), sum(SUMMA_F), sum(SALDO_KP), sum(SALDO_KPBM), MAX(TITLE),0
FROM @tTemp 
GROUP BY KBK, EKR, DOP_CL, DEP
UNION 
SELECT  KBK, EKR, NULL, DEP, sum(SUMMA_A), sum(SUMMA_KR), sum(SUMMA_F), sum(SALDO_KP), sum(SALDO_KPBM), MAX(TITLE),1
FROM @tTemp  
WHERE @iDopEkr = 1
GROUP BY KBK, EKR, DEP
having count(*) > 1


INSERT INTO @tTempDopEkr
SELECT * FROM @tTempGroup UNION 
SELECT F1.KBK, EKR2.LINK, NULL, DEP, sum(SUMMA_A), sum(SUMMA_KR), sum(SUMMA_F), sum(SALDO_KP), sum(SALDO_KPBM), MAX(TITLE),2
FROM @tTempGroup F1 
INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '0'
INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '0' AND 
					EKR2.LINK NOT IN (SELECT EKR FROM @tTempGroup T1 WHERE T1.KBK = F1.KBK and T1.DEP = F1.DEP)
WHERE @iDopEkr = 1 and F1.DOP_EKR = 0  
GROUP BY F1.KBK, EKR2.LINK, F1.DEP  

INSERT INTO @tTempDopEkr2
SELECT F.* 
	FROM @tTempDopEkr F
	INNER JOIN dbo.KOSGU EKR5 ON EKR5.LINK = F.EKR 		
	UNION 
SELECT F2.KBK, EKR4.LINK, null as dop_kl,F2.DEP, sum(SUMMA_A), sum(SUMMA_KR), sum(SUMMA_F), sum(SALDO_KP), sum(SALDO_KPBM), MAX(TITLE),3
	FROM @tTempDopEkr F2 
	INNER JOIN dbo.KOSGU EKR3 ON EKR3.LINK = F2.EKR AND RIGHT(EKR3.CODE,1) = '0'
	INNER JOIN dbo.KOSGU EKR4 ON EKR4.CODE = LEFT(EKR3.CODE,1) + '00' AND 
						EKR4.LINK NOT IN (SELECT EKR FROM @tTempDopEkr T2
									WHERE T2.KBK = F2.KBK and T2.DEP = F2.DEP)
	WHERE @iDopEkr = 1 and dop_cl is null   
	GROUP BY F2.KBK,EKR4.LINK,F2.DEP

--объединяем и добавляем расшифровку 

SELECT T.KBK, T.EKR, T.DOP_CL, T.DEP, 
	[KBK_CODE] = KBK.CODE,
	[EKR_CODE] = EKR.CODE,
	[DCL_CODE] = DC.CODE,
	[KBK_NAME] = KBK.NAME,
	[EKR_NAME] = EKR.NAME,
	[DCL_NAME] = DC.NAME,
	[SUMMA_A] = ISNULL(T.SUMMA_A,0),
	[SALDO_KP] = ISNULL(T.SALDO_KP,0),
	[SALDO_KPBM] = ISNULL(T.SALDO_KPBM,0),
	[SUMMA_KR] = ISNULL(T.SUMMA_KR,0),
	[SUMMA_F] = ISNULL(T.SUMMA_F,0),
	IT.SUMMAI_A,
	[SALDOI_KP] = ISNULL(IT.SALDOI_KP,0),
	[SALDOIKPBM] = ISNULL(IT.SALDOI_KPBM,0),
	IT.SUMMAI_KR,
	IT.SUMMAI_F,
	TITLE = ISNULL(T.TITLE,'')
FROM @tTempDopEkr2 T 
LEFT JOIN (SELECT KBK, DEP, SUMMAI_A = sum(SUMMA_A), SUMMAI_KR = sum(SUMMA_KR), SUMMAI_F = sum(SUMMA_F), SALDOI_KP = sum(SALDO_KP), SALDOI_KPBM = sum(SALDO_KPBM)
		FROM @tTempDopEkr2 where (0 = DOP_EKR) GROUP BY KBK, DEP) IT ON IT.KBK = T.KBK AND IT.DEP = T.DEP
LEFT JOIN KL_KBK KBK on T.KBK = KBK.link
LEFT JOIN KOSGU EKR on T.ekr = EKR.link
LEFT JOIN DOP_CLASSIF DC on T.DOP_CL = DC.link
ORDER BY KBK.CODE, EKR.CODE, DC.CODE, T.DEP 

SELECT [DCL_CODE] = DC.CODE,
	[SUMMA_A] = sum(ISNULL(T.SUMMA_A,0)),
	[SALDO_KP] = sum(ISNULL(T.SALDO_KP,0)),
	[SALDO_KPBM] = sum(ISNULL(T.SALDO_KPBM,0)),
	[SUMMA_KR] = sum(ISNULL(T.SUMMA_KR,0)),
	[SUMMA_F] = sum(ISNULL(T.SUMMA_F,0))
FROM @tTemp T
left JOIN DOP_CLASSIF DC on T.DOP_CL = DC.link
GROUP BY DC.CODE
ORDER BY DC.CODE 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT ALL ON dbo.FB_ZAYAVKA_F_VIL 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_CHECK_86N]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_CHECK_86N]
END
GO
/*******************************************************************************

   © Кейсистемс (Keysystems), 2011

*******************************************************************************/

CREATE PROCEDURE dbo.[RO_CHECK_86N]
   @tRazdel TINYINT,
   @iLSF    INT
AS
SET NOCOUNT               ON
DECLARE @bError BIT

CREATE TABLE #tab001 (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении
CREATE TABLE #tab001_OKVED (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [NAME] VARCHAR(8000), [NAMEU] VARCHAR(8000)) -- основыне ОКВЕД
CREATE TABLE #tab001_OKVED_ADD (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [NAME] VARCHAR(8000), [NAMEU] VARCHAR(8000)) -- дополнительные ОКВЕД
CREATE TABLE #tab001_BRANCH (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [FULL_NAME] VARCHAR(8000), [NAME] VARCHAR(8000), [TYPE] VARCHAR(50)) -- филиалы и представительства
		-- создание временных табличек
		CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
								ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета

		CREATE TABLE #tab002
		(
		   ID       UNIQUEIDENTIFIER
		   ,[changeDate]  VARCHAR(50)    -- Дата и время изменения
		   ,[versionNumber]   VARCHAR(50)-- Номер версии
		   ,[financialYear]  INT         -- Текущий финансовый год
		   ,[nextFinancialYear] INT      -- Очередной финансовый год
		   ,[planFirstYear] INT          --Первый год планового периода
		   ,[planLastYear] INT        --Второй год планового периода
		)
		-- Услуги
		CREATE TABLE #tab002_SERVICE
		(
		   ID       UNIQUEIDENTIFIER
		   ,[CODE]  VARCHAR(50)    -- Код услуги
		   ,[NUM]   VARCHAR(50)    -- Порядковый номер раздела, соответствующий услуге
		   ,[NAME]  VARCHAR(1000)  -- Наименование услуги, указанной в данном разделе
		   ,[KAT]   VARCHAR(1000)  -- Категория потребителей (наименование)   
		)
		-- Показатели качества услуг 
		CREATE TABLE #tab002_QUALITY
		(
		   ID       UNIQUEIDENTIFIER
		   ,[CODE]  VARCHAR(50)       -- Код услуги
		   ,[NAME]     VARCHAR(8000)  -- Наименование показателя качества услуги  
		   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                                  
		   ,[EI_SYMBOL] VARCHAR(1000)  -- Единица измерения (symbol ОКЕИ)                               
		   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
		   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя качества услуги за отчетный финансовый год
		   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя качества услуги на текущий финансовый год 
		   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя качества услуги на очередной финансовый год  
		   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя качества услуги на первый год планового периода  
		   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя качества услуги на второй год планового периода
		   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя качества услуги за текущий финансовый
		   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя качества 
		)
		-- Показатели объема услуги
		CREATE TABLE #tab002_VOLUME
		(
		   ID       UNIQUEIDENTIFIER
		   ,[CODE]  VARCHAR(50)       -- Код услуги
		   ,[NAME]     VARCHAR(8000)  -- Наименование показателя объема услуги   
		   ,[EI_CODE]  VARCHAR(1000)  -- Единица измерения (код ОКЕИ)                               
		   ,[EI_NAME]   VARCHAR(1000) -- Наименование единицы измерения 
		   ,[EI_SYMBOL] VARCHAR(1000)  -- Единица измерения (symbol ОКЕИ)                               
		   ,[SUMMA1]   NUMERIC(20,2)  --Значение показателя объема услуги за отчетный финансовый год
		   ,[SUMMA2]   NUMERIC(20,2)  --Значение показателя объема услуги на текущий финансовый год 
		   ,[SUMMA3]   NUMERIC(20,2)  --Значение показателя объема услуги на очередной финансовый год  
		   ,[SUMMA4]   NUMERIC(20,2)  --Значение показателя объема услуги на первый год планового периода  
		   ,[SUMMA5]   NUMERIC(20,2)  --Значение показателя объема услуги на второй год планового периода
		   ,[SUMMA6]   NUMERIC(20,2)  --Фактическое значение показателя объема услуги за текущий финансовый
		   ,[REASON]   VARCHAR(8000)  --Причины отклонения от запланированного значения показателя объема 
		)
		-- Возможность взимания платы за услугу
		CREATE TABLE #tab002_PRICE
		(
		   ID       UNIQUEIDENTIFIER
		   ,[CODE]  VARCHAR(50)       -- Код услуги
		   ,[SUMMA]   NUMERIC(20,2)   --Средневзвешенная цена за единицу услуги (руб.) 
		   ,[NPA_VID]   VARCHAR(8000) --Вид нормативного правового акта 
		   ,[NPA_NAME_ORGAN]   VARCHAR(8000) -- Наименование органа, утвердившего нормативный правовой акт 
		   ,[NPA_DATE]   VARCHAR(8000)--Дата нормативного правового акта
		   ,[NPA_NUM]   VARCHAR(8000) --Номер нормативного правового акта
		   ,[NPA_NAME]   VARCHAR(8000)--Наименование нормативного правового акта 
		)
		-- Сведения о работах   
		CREATE TABLE #tab002_WORK
		(
		   ID       UNIQUEIDENTIFIER
		   ,[CODE]  VARCHAR(50)       -- Код работы
		   ,[NUM]   VARCHAR(50)       --Порядковый номер раздела соответствующий работе
		   ,[NAME]   VARCHAR(8000)    --Наименование работы, указанной в данном разделе
		)


DECLARE @tabErrorLog TABLE([ID] UNIQUEIDENTIFIER, [TXT] VARCHAR(8000),[ORDER] INT IDENTITY(1,1))
-- получение данных

EXEC dbo.[RO_EXPORT_86N_GET_DATA] @iLSF, @tRazdel

CREATE TABLE #tabExportLog (TXT VARCHAR(8000), [ORDER] INT IDENTITY(1,1))

IF @tRazdel = 1
	EXEC dbo.[RO_EXPORT_FORM_86N_001_ANALYZE] @bError OUTPUT
	
IF @tRazdel = 2
	BEGIN
		 
		EXEC dbo.[RO_EXPORT_FORM_86N_002_ANALYZE] @bError OUTPUT
	END

DELETE #tabExportLog WHERE txt LIKE '%Выгрузка отменена%'
  
IF @bError = 1
BEGIN
   exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = 'Протокол проверки заполненных полей для выгрузки', @cDataTableName  = '#tabExportLog',@cShowFields  = 
      '<field name=''TXT'' width=''100%'' WRAP=''1''></field>'
      , @cFieldsDesc  = 'Текст', @cOrderFields = '[order]'
      INSERT #res (cdoc)
      SELECT 'Невидимая ошибка'
      FROM #tabExportLog WHERE LEFT(TXT,23)<>'Для организации с кодом'
      
END
   
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код вида учреждения" (стр.16)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '116001' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Длина поля "Код вида учреждения" должна равняться 7 знакам  (таблица "Вид учреждения")'
--FROM #tab001 T
--WHERE T.[CODE] = '116001' AND LEN(T.[VALUE])<>7 AND T.[VALUE]<>'' 
 
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код по ОКАТО публично-правового образования, создавшего учреждение" (стр.6)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '106002' AND T1.[VALUE] <> '') 

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код по ОКТМО публично-правового образования, создавшего учреждение" (стр.6)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '106003' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код муниципального образования по месту регистрации учреждения по ОКТМО" (стр.20)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '120000' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код района" (стр.24.2)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124020' AND T1.[VALUE] <> '')
      --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124030' AND T1.[VALUE] <> '')
      --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124040' AND T1.[VALUE] <> '')      

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код города" (стр.24.3)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124020' AND T1.[VALUE] <> '')
      --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124030' AND T1.[VALUE] <> '')
      --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124040' AND T1.[VALUE] <> '')      

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код населенного пункта" (стр.24.4)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124020' AND T1.[VALUE] <> '')
  --    AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124030' AND T1.[VALUE] <> '')
      --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '124040' AND T1.[VALUE] <> '')
      
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код органа государственной власти(местного самоуправления), осуществляющего функции и полномочия учредителя"(стр.7)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '107000' AND T1.[VALUE] <> '') 

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Код главы ГРБС по бюджетной классификации" (стр.9)'
FROM #tab001 T
WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '109000' AND T1.[VALUE] <> '')             
      AND EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '115000' AND T1.[VALUE] LIKE '%каз%')
      
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "ИНН ГРБС" не должен превышать 10 знаков (стр.8)'
FROM #tab001 T
WHERE T.[CODE] = '108001' AND LEN(T.[VALUE])>10      

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "ИНН распорядителя бюджетных средств" не должен превышать 10 знаков (стр.10)'
FROM #tab001 T
WHERE T.[CODE] = '110001' AND LEN(T.[VALUE])>10

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "ИНН органа, осуществляющего функции и полномочия учредителя, принявшего решение о назначении членов наблюдательного совета" не должен превышать 10 знаков (стр.11.2)'
FROM #tab001 T
WHERE T.[CODE] = '111020' AND LEN(T.[VALUE])>10      

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Реестроый номер распорядителя бюджетных средств в ОГС" (стр.10)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '110001' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Сокращенное наименование" в таблице "Обособленные структурные подразделения"'
--FROM #tab001_BRANCH
--WHERE [NAME] = ''             
      
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], '"Код главы ГРБС по бюджетной классификации" (стр.9) отсутствует в справочнике КБК'
--FROM #tab001 T
--WHERE T.[CODE] = '109000' AND T.[VALUE] <> '' AND NOT EXISTS(SELECT * FROM dbo.rn_view_kbk_adm_m_atr A WHERE A.[CODE] = T.[VALUE])             

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Таблица "Обособленные структурные подразделения" содержит, по крайней мере, одну строку'
--FROM #tab001 T
--WHERE T.[CODE] = '114000' AND T.[VALUE] <> ''
      --AND EXISTS(SELECT * FROM #tab001_BRANCH T1 WHERE T.[ID] = T1.[ID])

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Вид правового акта" (стр.11.1)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
   --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111010' AND T1.[VALUE] <> '')
 
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Наименование правового акта" (стр.11.5)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
   --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111050' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Номер правового акта" (стр.11.4)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
   --AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111040' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Дата правового акта" (стр.11.3)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
  -- AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111030' AND T1.[VALUE] <> '')

DECLARE @cCodeRegion  VARCHAR(100)
SET @cCodeRegion = ''
--проверка regnum
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для организации с кодом: '+[VALUE]
--FROM #tab001 WHERE CODE = '000000' AND 
--dbo.rn_get_ogs_code([VALUE],@cCodeRegion,0) = ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Поле "Идентификационный номер налогоплательщика (ИНН)" должено быть 10 знаков (стр.3)'
--FROM #tab001 T
--WHERE T.[CODE] = '103000' AND LEN(T.[VALUE])<>10 AND [VALUE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Поле "Код причины постановки на учет (К1Ш)" должено быть 9 знаков (стр.4)'
--FROM #tab001 T
--WHERE T.[CODE] = '104000' AND LEN(T.[VALUE])<>9 AND [VALUE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнен код по ОКАТО публично-правового образования, создавшего учреждение(стр.6)'
--FROM #tab001 A WHERE CODE = '106000' AND VALUE = ''
--and (select dbo.rn_get_ppo_code([VALUE]) FROM #tab001 B WHERE A.ID = B.ID AND CODE = '106002') = ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Фамилия"(стр.12.1)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112010' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Имя"(стр.12.2)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112020' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Отчество"(стр.12.3)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112030' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Наименование должности"(стр.12.4)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112040' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не верно заполнено поле "Контактный телефон" (стр.26) "'+[VALUE]+'" (Пример: Код страны-Код города-Номер 8-495-1234567)'
--FROM #tab001 T
--WHERE [CODE] = '126000' AND [VALUE] <> '' AND dbo.RN_GETWORDCOUNT([VALUE],'-') IN (0,1,4,5,6,7,8,9)

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для организации (филиал, представительство) с кодом: '+[CODE]
--FROM #tab001_BRANCH WHERE  
--dbo.rn_get_ogs_code(RTRIM(CODE),@cCodeRegion,0) = ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Поле "Тип филиала" в таблице "Обособленные структурные подразделения" может принимать только значения: 01, 02, 03'
--FROM #tab001_BRANCH
--WHERE [TYPE] NOT IN ('01', '02', '03') AND TYPE <> '' 

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для организации учредителя с кодом: '+[VALUE]
--FROM #tab001 WHERE dbo.rn_get_ogs_code(RTRIM(VALUE),@cCodeRegion,0) = ''
--and CODE = '107000' AND [VALUE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено наименование учредителя (стр. 7)'
--FROM #tab001 WHERE CODE = '107001' AND VALUE=''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для правого органа с кодом: '+[VALUE]
--FROM #tab001 WHERE dbo.rn_get_ogs_code(RTRIM(VALUE),@cCodeRegion,0) = ''
--and CODE = '111020' AND [VALUE] <> ''


--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Реестровый номер в ОГС органа, осуществляющего функции и полномочия учредителя, принявшего решение о назначении членов наблюдательного совета" (стр.11.2)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '115000' AND T1.[VALUE] LIKE '%авто%')
--   AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111020' AND T1.[VALUE] <> '')


TRUNCATE TABLE #tabExportLog

IF EXISTS(SELECT * 
          FROM @tabErrorLog)
BEGIN
   INSERT #tabExportLog([TXT])
   SELECT [TXT]
   FROM 
      (SELECT -1 [order], [ID], 'Для организации с кодом ' + RTRIM(T.[VALUE]) + ' ' + ISNULL((SELECT d.name FROM dbo.departments d WHERE d.budg = T.[VALUE] AND 1 = (SELECT COUNT(*) FROM dbo.departments d1 WHERE d1.budg = T.[VALUE])), '') AS [TXT]  
      from #tab001 T 
      WHERE T.[CODE] = '000000'
         AND EXISTS(SELECT * FROM   @tabErrorLog T1 WHERE T.[ID] = T1.[ID])
      UNION ALL
      SELECT [ORDER], [ID], [TXT]
      FROM @tabErrorLog) A
   ORDER BY [ID], [ORDER]

      INSERT #res (cdoc)
      SELECT 'Невидимая ошибка'
      FROM #tabExportLog

   exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = 'Протокол проверки заполненных полей', @cDataTableName  = '#tabExportLog',@cShowFields  = 
      '<field name=''TXT'' width=''100%'' WRAP=''1''></field>'
      , @cFieldsDesc  = 'Текст', @cOrderFields = '[order]'

END
ELSE
   BEGIN
      IF @bError = 0 
   			update report_saved_forms
			set IsRightKS = 1
			where link_saved_form = @iLSF
   END


SELECT 0

DROP TABLE #tabExportLog

RETURN 0
GO
GRANT ALL ON dbo.[RO_CHECK_86N] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXEC dbo.[RA_ERROR_DELETE] 'RO_EXPORT_FORM_RRO_ANALYZE'
EXEC dbo.[RA_ERROR_UPDATE] 'RO_EXPORT_FORM_RRO_ANALYZE',0,'Нет ошибок.Успех.',0
EXEC dbo.[RA_ERROR_UPDATE] 'RO_EXPORT_FORM_RRO_ANALYZE',-1,'Логические ошибки во входных данных (см. в R_OUTPUT).',0
EXEC dbo.[RA_ERROR_UPDATE] 'RO_EXPORT_FORM_RRO_ANALYZE',-2,'Системная ошибка в х.п. RO_EXPORT_FORM_RRO_ANALYZE.',0



*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHECK_KS_OUTSIDE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_KS_OUTSIDE]
GO


/*
c Кейсистемс (Keysystems), 2009
Проверка междокументных КС
*/
CREATE    PROCEDURE dbo.RO_CHECK_KS_OUTSIDE
		@varKScGroup varchar(8000),  -- линки групп КС
		@varKSiPeriodType smallint, 
		@varKSiPeriodNumber smallint,
		@varKSdBeginDate datetime,
		@varKScLinksTree	varchar(8000), -- линки дерева организаций и бюджетов
		@varKStableName varchar(100) = '', -- таблица с линками отчетов 
		@varKSiDown			tinyint, --проверка по ветке
		@cProgressTable		varchar(100), 
		@tmpTable			varchar(100), --временная таблица для протокола
		@typeProtokol		tinyint -- тип протокола (если @tmpTable пустно): 
							-- 0 - автоматический выбор (если меньше 10000 строк, то html, иначе грид),
							-- 1 - грид всегда
							-- 2 - html всегда
AS


--set @typeProtokol = 1
---------------------------------------------------------------------------------
declare @ExecStr varchar(8000), @strProgressExec varchar(1000), @cDataDesc VARCHAR(1000)

if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 1'
    execute(@strProgressExec)
end

create table #tree(link int)
create table #LSF (lsf int)


if  isnull(rtrim(@varKScLinksTree),'') <> ''
begin
	set @ExecStr = 'select link from report_svod_tree where link in (' + REPLACE(@varKScLinksTree, ' ', ',') + ')'
	insert #tree execute(@ExecStr)
end

if @varKStableName <> ''
begin
	set @ExecStr = 'select * from ' + @varKStableName
	insert #LSF execute(@ExecStr)
end

insert #tree 
select T.Link
from report_svod_tree T inner join report_saved_forms RSF on T.Link_report_org = RSF.Link_Organization and isnull(T.Link_report_budg,0) = isnull(RSF.Link_Type_Svod, 0)
where Link_Saved_Form in (select lsf from #LSF)


if exists(select top 1 * from #LSF)
begin
	select top 1 @varKSiPeriodType = Period_Type, @varKSiPeriodNumber = Period_Number, @varKSdBeginDate = Begin_Date from report_saved_forms RSF where Link_Saved_Form in (select lsf from #LSF)
end

declare @t_tree table (link int, link_report_budg int, link_report_org int, name_org varchar(254), name_budg varchar(254), email varchar(254)) -- пусть она на входе будет вообще!
insert @t_tree 
select T.link, link_report_budg, link_report_org, D.Name, B.Name, ''--D.email
from report_svod_tree T left join departments D on T.Link_report_org = D.link left join kl_budg_type B on isnull(T.link_report_budg,0) = isnull(B.link,0)
where T.link in (select link from #tree)

if @varKSiDown = 1 -- проверка по ветке
begin
	insert @t_tree 
	select T.link, link_report_budg, link_report_org, D.Name, B.Name, '' --D.email
	from report_svod_tree T left join departments D on T.Link_report_org = D.link left join kl_budg_type B on isnull(T.link_report_budg,0) = isnull(B.link,0)
	where Link_self in (select link from #tree)
end
if @varKSiDown = 2 -- проверка по всем нижележащим
begin
	insert @t_tree 
	select -R.link, R.link_report_budg, R.link_report_org, D.Name, B.Name, '' --D.email
	from report_svod_tree R left join departments D on R.Link_report_org = D.link left join kl_budg_type B on isnull(R.link_report_budg,0) = isnull(B.link,0)
	where Link_self in (select link from #tree)
	while exists(select top 1  * from report_svod_tree where link_self in (select -link from @t_tree where link < 0))
	begin
		update @t_tree set link = -link where link < 0
		insert @t_tree 
		select -R.link, link_report_budg, link_report_org, D.Name, B.Name, '' --D.email
		from report_svod_tree R left join departments D on R.Link_report_org = D.link left join kl_budg_type B on isnull(R.link_report_budg,0) = isnull(B.link,0)
		where Link_self in (select link from @t_tree) and not exists(select top 1 * from @t_tree T where T.link = R.link)
	end
	update @t_tree set link = -link where link < 0
END
drop table #tree
drop table #LSF
IF EXISTS(SELECT * FROM  dbo.[BufferGetTableByID]('RO_MDKS_LSF'))
BEGIN
	insert @t_tree 
	select R.link, R.link_report_budg, R.link_report_org, D.Name, B.Name, '' --D.email
	from dbo.[BufferGetTableByID]('RO_MDKS_LSF') L
         JOIN dbo.report_saved_forms rsf ON L.link = rsf.[Link_Saved_Form]
         join report_svod_tree R ON R.[Link_report_Org] = rsf.[Link_Organization] AND ISNULL(R.[LINK_REPORT_BUDG], 0) = ISNULL(rsf.[Link_Type_Svod], 0) AND R.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](rsf.[Begin_Date]) 
         left join departments D on R.Link_report_org = D.link left join kl_budg_type B on isnull(R.link_report_budg,0) = isnull(B.link,0)
   EXEC dbo.[BufferClear]  'RO_MDKS_LSF'     
END    
----------------------------------------------------------------------------------------
-- правила:
create table #t_Rules (Link_Rule int, algorithm tinyint, [sign_sr] char(2), cols varchar(250), [rows] varchar(1000), Str_Rule varchar(8000), Group_KS varchar(20), Comment varchar(2000), OrderRule int, Group_Name varchar(254), atr_code_sr varchar(254), IsDoschet tinyint)
-- члены правила, используется для вычисления выражения:
create table #t_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(1000), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1000), 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_Rows_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(1000), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(1000), cOrderTable varchar(254), cOrderCol varchar(10), px_Comment varchar(254) default '', [property] tinyint)
-- записываем результат левой и правой частей:
create table #t_Result([Value] float, Link_Rule int, atr_code varchar(250), part tinyint, algorithm tinyint, orderCol int, CodeRow varchar(50))
-- будущий протокол (туда же пишут хранимки):
create table #Res (orders int,ord int IDENTITY (1, 1) NOT NULL, res varchar(8000) default '',cKod varchar(250) default '',cDoc varchar(5000) default '',cTable varchar(100) default '',cCol varchar(100) default '',cValue varchar(100) default '', cPeriod varchar(30) default '', cBudg varchar(254) default '', Group_KS varchar(254) default '', cGroup varchar(254) default '')
create table #Res_atr (cDoc varchar(2000) default '', Group_KS varchar(254) default '')
-- список отчетов (для хранимок):
create table #ListFormsA (lsf int, linkForm int, codeForm varchar(100), startDate datetime, cPeriod varchar(20), catr varchar(254), cbudg varchar(254), cGroupKS VARCHAR(30))
create table #ListForms (lsf int, linkForm int, codeForm varchar(100), startDate datetime, cPeriod varchar(20), catr varchar(254), cbudg varchar(254), cGroupKS VARCHAR(30))
-- результат хранимок (хотя в будущем этого не надо)
create table #tmp (Value float)
-- результат сравнения левой и правой частей
create table #t_Result_sr (Link_Rule int, atr_code varchar(254), CodeRow varchar(1000), orderCol int, error tinyint, LeftPart numeric(20,4), RightPart numeric(20,4), Str_Rule varchar(8000), Group_KS varchar(20), Comment varchar(2000), OrderRule int, sign_sr char(2))
-- для протокола слагаемые
create table #t_Res_summand (Link_Rule int, OrderRow int, [sign] char(2), lf int, lsf int, atr_code varchar(254),cOrderTable varchar(254), cOrderCol varchar(10), Code_Row varchar(1000), Filter_desc varchar(200), part tinyint, [Value] numeric(20,4), orderCol tinyint default 0, CodeRow varchar(254) default '', px_Comment varchar(254) default '')
-- чтобы не вываливалось, когда проверяют хранимки
create table #atr (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_cur (lsf int, atr varchar(50), str_val varchar(50))
create table #atr_empty (lsf int, atr varchar(50), str_val varchar(50))
-- для вычисления сложных правил (деление и умножение)
declare @t_temp table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(1000), 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 #report_tables (Link_Table int, orders tinyint, Name varchar(254), link_form int, Val_Type tinyint, Dop_Col int)
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 #report_coloumns (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len int, Orders tinyint, Export_Order tinyint, Col_Type tinyint)
create table #t_Rows_Static(Link_Row int primary key, Code varchar(50), Link_Table int, Dop_Col varchar(50))
create table #report_Dinamics(Link_SF int, Code_Row varchar(50), link_col int, float_val numeric(20,4), str_val varchar(8000), Link_Table int, OT tinyint)
create table #t_Summa(LSF int, link_col int, link_row int, Code varchar(50), summa float)
create table #t_Factor (Link_Rule int, OrderRow int, [sign] char(2), atr_code varchar(254), part tinyint, factor float)

-- для проверки внутри хранимок 
CREATE TABLE #t_MDKS_PROC([CODE] CHAR(5), [TXT] VARCHAR(1000))

Create index #IX_report_dinamics on #report_dinamics (link_sf,code_row,link_col)
Create index #IX_REPORT_SUMMA on #t_summa (link_col,link_row)

declare @LinkOrg int, @LinkBudg int, @LinkRule int, @atr_code varchar(254), @i int, @maxOrderRow int, @NameOrg varchar(254), @NameBudg varchar(254), @OrderRow int
declare @nprecision float, @countOrg int, @orderOrg int, @round int, @cPeriod varchar(100), @GroupKS varchar(254), @time_begin datetime, @time_end datetime, @one tinyint, @atr varchar(254), @lsf int, @cGroup varchar(254)
set @nprecision = 0.0005
set @time_begin = getdate()
CREATE TABLE #t_PeriodType (PeriodType TINYINT)
INSERT #t_PeriodType (PeriodType)
VALUES (@varKSiPeriodType)
------------------------------------------------------------------------------------
-- получение правил
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Получение правил'', percents = 2'
    execute(@strProgressExec)
end
set @varKSdBeginDate =  convert(datetime, case @varKSiPeriodType when 1 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '1231' when 2 then 
				case @varKSiPeriodNumber when 1 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0331' when 2 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0630' when 3 then LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0930' else LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '1231' end
				when 4 then dateadd(month, @varKSiPeriodNumber, LTRIM(RTRIM(STR(YEAR(@varKSdBeginDate)))) + '0101') - 1 end)

set @cPeriod = case @varKSiPeriodType when 1 then LTRIM(STR(YEAR(@varKSdBeginDate))) + ' год' 
				when 2 then LTRIM(STR(@varKSiPeriodNumber)) + ' квартал ' + LTRIM(STR(YEAR(@varKSdBeginDate))) + ' года'
				when 4 then case @varKSiPeriodNumber 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   + LTRIM(STR(YEAR(@varKSdBeginDate))) + ' года' end


create table #t_Rules_region (Link_Rule int, OrderRule int)

insert #t_Rules_region 
exec  dbo.[I_CONTROL_RULES_LIST] default, 1, @varKSiPeriodType, @varKSiPeriodNumber, default, default

insert #t_Rules (Link_Rule, algorithm, [sign_sr], cols, [rows], Str_Rule, Group_KS, Comment, OrderRule, Group_Name, atr_code_sr, IsDoschet) 
exec dbo.RO_CHECK_KS_LIST_RULES default, 1, @varKSiPeriodType, @varKSiPeriodNumber, @varKScGroup

delete #t_Rules where Link_Rule not in (select Link_Rule from #t_Rules_region)

truncate table #t_Rules_region

if not exists(select top 1  * from #t_Rules)
begin
	return 0
end

-- предварительные действия, которые можно сделать вне цикла
insert #t_Rows_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows], cOrderTable, cOrderCol, px_Comment, [property])
select distinct Ro.Link_Rule, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, (case isnull(Ro.period_year,0) when 0 then dateadd(month, Ro.period_form, @varKSdBeginDate+1)-1 else Ro.begin_date end) , Ro.budg_code, Ro.atr_code, 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, Ru.cols, Ru.[rows], '№' + isnull(ltrim(STR(RT.orders)),'') + ' (' + RTRIM(RT.Name) + ')', '№' + isnull(ltrim(str(RC.export_order)),''), Ro.px_comment, Ro.[property]
from #t_Rules Ru left join report_control_rows Ro (NOLOCK) on Ro.Link_Rule = Ru.Link_Rule
	left join report_tables RT on Ro.Link_Table = RT.Link_Table
	left join report_coloumns RC on RC.Link_Col = Ro.Link_Col
--where OrderRule = 82


update #t_Rows_KS
set Exec_Proc = 'exec dbo.' + RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,')',' '),'(',' ')))
where val_type = 2
--update #t_Rows_KS
--set Exec_Proc = RTRIM(LTRIM(REPLACE(REPLACE(Exec_Proc,']',')'),'[','('))) 
--where val_type = 2

insert #report_tables (Link_Table, orders, Name, link_form, Val_Type, Dop_Col)
select RT.Link_Table, RT.orders, RT.Name, RT.link_form, case when RF.Code like '050307[45]%' then 1 else RT.Val_Type end, (select top 1 Link_Col from report_coloumns RC where RT.Link_Table = RC.Link_Table and IsEdited = 0 and RT.Link_Code_Col <> RC.Link_Col and RC.Val_len < 50 and RC.Val_len <> 0)
from report_tables RT (NOLOCK)
	join report_forms RF on RF.Link_Form = RT.Link_Form
where RT.Link_Table in (select distinct Link_Table from #t_Rows_KS where Link_Table is NOT NULL)

insert #report_coloumns (Link_Col, Name, Link_Table, Val_Len, Orders, Export_Order,Col_Type)
select Link_Col, Name, Link_Table, Val_Len, Orders, Export_Order, Col_Type
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, '№' + LTRIM(STR(Export_Order))
from #report_coloumns RC

select @round = max(Val_Len) from #report_coloumns where col_type = 0

insert #t_Rows_Static(Link_Row, Code, Link_Table, Dop_Col)
select RR.Link_Row, RR.Code, RR.Link_Table, RF.formula
from i_report_rows RR 
			join #report_Tables T on RR.Link_Table = T.Link_Table and T.Val_Type = 0
			left join dbo.report_formula RF on RR.link_row = RF.link_row and RF.Link_Col = T.Dop_Col

-- константы для простых правил не будем учитывать, лсф для них не будем смотреть и в конце их прибавим
insert #t_Factor (Link_Rule, OrderRow, [sign], atr_code, part, factor)
select Link_rule, OrderRow, [sign], atr_code, part, case [sign] when '+' then K.Factor else -K.Factor end
from #t_Rows_KS K
where Val_Type = 1 and algorithm in (1,2,3,4)

delete #t_Rows_KS
where Val_Type = 1 and algorithm in (1,2,3,4)

select @countOrg = count(*) from @t_tree
set @orderOrg = 1

-- для ускорения протокола
declare @t table (orders int)
	insert @t values(1)
	insert @t values(3)
	insert @t values(6)
	insert @t values(7)
	insert @t values(8)

----------------------------------------------------------------------------------------
-- для протокола HTML
CREATE TABLE #ks_protokol_HTML ([order] Integer, [type] Integer, [html] VarChar(8000))
exec HTMLReport @nMode = 0, @cWorkTableName = '#ks_protokol_HTML', @cRepHeader = 'Протокол проверки контрольных соотношений'

select * 
into #Res_Group
from #Res
--insert #res_Group (cDoc, cTable)
--select 'Количество ошибок: ' + LTRIM(STR(count(*))), 'Время выполнения: ' + convert(varchar(10), @time_end - @time_begin, 108)
-- пошел цикл по организациям
while exists(select top 1 * from @t_tree)
begin

	if (select count(*) from #Res) > 1
	begin
		set @time_end = getdate()
		update #res
		set cDoc = 'Количество ошибок: ' + c,
			cTable = 'Время выполнения: ' + t
		from (select LTRIM(STR(count(*))) as c, convert(varchar(10), @time_end - @time_begin, 108) as t from #res where cDoc = 'Отклонение') A
		where ord = 1
      
      set @cDataDesc = '<B> Организация: </B>' + RTRIM(isnull(@NameOrg, '')) + '<B> Бюджет: </B>' + RTRIM(isnull(@NameBudg,'')) + '<B> Период: </B>' + RTRIM(isnull(@cPeriod, '')) + '</B>'
      
		  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = @cDataDesc, @cDataTableName  = '#Res',@cShowFields  = 
		'<field name=''res'' width=''4%'' WRAP=''1''></field>
		 <field name=''cdoc'' width=''36%'' WRAP=''1''></field>
		 <field name=''cPeriod'' width=''10%'' WRAP=''1''></field>
		 <field name=''cBudg'' width=''10%'' WRAP=''1''></field>
		 <field name=''ctable'' width=''15%'' WRAP=''1''></field>
		 <field name=''ckod'' width=''15%'' WRAP=''0''></field>
		 <field name=''ccol'' width=''5%'' WRAP=''1''></field>
		<field name=''cvalue'' width=''5%'' WRAP=''0''></field>'
		, @cFieldsDesc  = 'Формула|Документ|Период|Бюджет|Таблица|Операция и код|Графа|Значение', @cOrderFields = 'Group_KS, ord'--, @cGroupFields = 'cGroup', @cGroupDesc = 'фыва @cGroup'
		truncate table #Res
	end
	insert #Res  (cDoc, cTable) values ('','')
	select top 1 @LinkOrg = Link_report_org, @LinkBudg = Link_report_budg, @NameOrg = name_org, @NameBudg = name_budg, @cGroup = ' Организация: ' + @NameOrg + ' Бюджет: ' + @NameBudg from @t_tree
	delete @t_tree where Link_report_org = @LinkOrg and Link_report_budg  = @LinkBudg
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Организация: ' + left(rtrim(REPLACE(@NameOrg, '''', '''''')), 120) + ' Бюджет: ' + left(rtrim(@nameBudg),50) + ''', percents = ' + str(convert(int, (@orderOrg-1)*100/@countOrg + 10))
		execute(@strProgressExec)
	end
	set @orderOrg = @orderOrg + 1
--	insert #Res (cDoc, cGroup)
--	values ('<B>Организация: ' + @NameOrg, @cGroup)
--	insert #Res (cDoc, cGroup)
--	values ('<B>Бюджет: ' + @NameBudg, @cGroup)
--	insert #Res (cDoc, cGroup)
--	values( '<B>Отчетный период: ' + @cPeriod, @cGroup)
	----------------------------------------------------------------------------------------
	-- получение слагаемых с lsf (отчеты получаем как обычно)
	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property])
	select Ro.Link_Rule, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, case when RSF.Link_Saved_form is NULL and Ro.Link_Form is NOT NULL then '#' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') else dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#') end, RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property]
	from #t_Rows_KS Ro left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, @LinkBudg) RSF on Ro.Link_Form = RSF.Link_Form and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and RSF.begin_date = Ro.begin_date and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end
	where budg_code = '' and part = 0

	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property])
	select Ro.Link_Rule, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, case when RSF.Link_Saved_form is NULL and Ro.Link_Form is NOT NULL then '#' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') else dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#') end, RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property]
	from #t_Rows_KS Ro left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, @LinkBudg) RSF on Ro.Link_Form = RSF.Link_Form and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and RSF.begin_date = Ro.begin_date and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end
	where budg_code = '' and part = 1

	-- слагаемые, для которых указан бюджет
	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask, part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property])
	select Ro.Link_Rule, Ro.OrderRow, Ro.val_type, Ro.[sign], Ro.Link_Form, Ro.period_form, Ro.period_type, Ro.period_year, Ro.begin_date, Ro.budg_code, case when RSF.Link_Saved_form is NULL and Ro.Link_Form is NOT NULL then '#' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') else dbo.[RA_GETWORDNUM](Ro.atr_code,1,'#') end, RSF.Link_Saved_form, Ro.Link_Table, Ro.Link_Col, Ro.Link_Row, Ro.Code_Row, Ro.Factor, Ro.px, Ro.Exec_Proc, Ro.Filter, Ro.Filter_desc, Ro.Mask, Ro.part, algorithm, cols, [rows],cOrderTable, cOrderCol, px_Comment, [property]
	from #t_Rows_KS Ro left join kl_budg_type B on B.code = Ro.budg_code	
		left join dbo.RO_SAVED_FORMS_FOR_ORG_MAX_VERS(@LinkOrg, NULL) RSF on Ro.Link_Form = RSF.Link_Form and (RSF.atr_code like '%' + dbo.[RA_GETWORDNUM](Ro.atr_code,2,'#') + '%') and RSF.begin_date = Ro.begin_date  and RSF.Link_Type_Svod = B.Link and Ro.period_type = case when Ro.period_type = 8 then RSF.period_type else RSF.period_type1 end
	where budg_code <> ''

	insert #Res (cDoc, Group_KS, cGroup)
	select distinct '', Group_KS, @cGroup
	from #t_Rules
	union all
	select distinct '<B>Группа: ' + RTRIM(Group_KS) + ' (' + RTRIM(Group_Name) + ')', Group_KS, @cGroup
	from #t_Rules

	-- удаляем правила, для которых нет отчетов
	insert #Res (cDoc, Group_KS, cGroup)
	select distinct 'Отсутствует отчет: ' + RF.Code + case when K.atr_code <> '' then ' с атрибутом ' + SUBSTRING(K.atr_code,2,LEN(K.atr_code)-1) else '' end + case when K.budg_code <> '' then ' '+ RTRIM((select top 1 name from dbo.kl_budg_type where code = K.budg_code)) else '' end + ' ' + RF.Name + ' (Версия: ' + convert(varchar(10), start_date, 104) + ')' , R.Group_KS, @cGroup
	from #t_KS K left join #t_Rules R on K.Link_Rule = R.Link_Rule
		left join report_forms RF (NOLOCK) on K.Link_Form = RF.Link_Form
	where lsf is NULL and Val_Type <> 1 and Val_Type <> 2 and R.Group_Name not like '%(ГРБС)%' AND K.[property] & 1 = 0

	delete #t_KS
	where Link_Rule in (select Link_Rule from #t_KS K where K.Val_Type <> 1 and K.Val_Type <> 2 and K.lsf is NULL and px_comment not like '%@@OPTIONAL%' and [property] & 1 = 0)
	
	update #t_ks set px_comment = REPLACE(px_comment, '@@OPTIONAL','')

	update 	#t_KS
	set lsf = 0
	where link_form is NOT NULL and lsf is NULL

	update #t_KS
	set atr_code = ''
	where lsf = 0 and left(atr_code,1) = '#'

	if not exists(select top 1 * from #t_KS)
	begin
		insert #Res_Group (cDoc, Group_KS, cGroup)
		select cDoc, Group_KS, cGroup
		from #Res

		continue
	end

	insert #ListFormsA (lsf, linkForm, codeForm, startDate, cPeriod, catr, cbudg)
	select SF.lsf, RSF.Link_Form, RF.code, RF.start_Date, 
		case RSF.Period_Type when 1 then LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' год' 
				when 2 then LTRIM(STR(Period_Number)) + ' квартал ' + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				when 4 then case Period_Number 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   + LTRIM(STR(YEAR(RSF.Begin_DAte))) + ' года'
				end,
			RSF.atr, case when budg_code <> '' then B.Name else '' end
	from (select lsf, max(budg_code) as budg_code from #t_KS where lsf is NOT NULL group by lsf) SF
		left join report_saved_forms RSF on SF.lsf = RSF.Link_Saved_Form
		left join report_forms RF on RF.Link_Form = RSF.Link_Form
		left join dbo.kl_budg_type B on RSF.Link_Type_Svod = B.Link

	insert #atr
	select A.lsf,V.code,dbo.RN_GET_ATR_VALUE(A.LSF, V.Code)
	from #ListFormsA A inner join dbo.report_saved_forms RSF on A.lsf = RSF.link_saved_form
		inner join dbo.N_REPORT_ATRIBUTS_VIEW V on CHARINDEX(RTRIM(V.Code) + '=', RSF.atr_code) > 0
	where V.code in ('REPORTS_ATR_ADM','REPORTS_ATR_DATE','REPORTS_ATR_ACC','REPORTS_ATR_ACC_2011')

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@orderOrg-1)*100/@countOrg + 10 + 20/@countOrg))
		execute(@strProgressExec)
	end
	-----------------------------------------------------------------------
	-- теперь добавляем атрибуты
	exec dbo.RO_RAZMNOJ_KS_ATR
	-----------------------------------------------------------------------
	insert #Res (cDoc, Group_KS, cGroup)
	select distinct '' , Group_KS + '#' + atr_code, @cGroup
	from #t_KS K left join #t_Rules R on K.Link_Rule = R.Link_Rule
	where atr_code <> ''
	union
	select distinct '<B> Проверка по атрибуту ' + atr_code , Group_KS + '#' + atr_code, @cGroup
	from #t_KS K left join #t_Rules R on K.Link_Rule = R.Link_Rule
	where atr_code <> ''

	insert #Res (cDoc, Group_KS, cGroup)
	select cDoc, Group_KS, @cGroup
	from #Res_atr
	where isnull(cDoc, '') <> ''

	insert #Res (cDoc, Group_KS, cGroup)
	select distinct 'Проверка выполнена успешно' , Group_KS + '#' + atr_code, @cGroup
	from #t_KS K left join #t_Rules R on K.Link_Rule = R.Link_Rule
	where atr_code <> ''

	insert #Res (cDoc, Group_KS, cGroup)
	select distinct 'Проверка выполнена успешно' , Group_KS, @cGroup
	from #t_KS K left join #t_Rules R on K.Link_Rule = R.Link_Rule
	where atr_code = ''

	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_all (NOLOCK) where Link_Saved_Form in (select lsf from #ListFormsA))	RS left 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, OT)
	select Link_SF, Code_Row, D.link_col, float_val, str_val, C.Link_Table, RT.orders
	from report_dinamics_all D (NOLOCK) left join #t_Col C on D.Link_Col = C.Link_Col left join #report_tables RT on C.Link_Table = RT.Link_Table
		join #ListFormsA F on D.Link_SF = F.lsf
	where codeForm not like '050307[45]%'

	insert #report_dinamics(Link_SF, Code_Row, link_col, float_val, str_val, Link_Table, OT)
	select Link_SF, 'КБК: ' + (select top 1 kbk from REPORT_FORM14_RAZD_NAME_FOR_KS where shifr = left(Code_Row,5)) + ' СТР: ' + RIGHT(RTRIM(Code_Row), 3), 
			D.link_col, float_val, str_val, C.Link_Table, RT.orders
	from report_dinamics_all D (NOLOCK) left join #t_Col C on D.Link_Col = C.Link_Col left join #report_tables RT on C.Link_Table = RT.Link_Table
		join #ListFormsA F on D.Link_SF = F.lsf
	where codeForm  like '050307[45]%'
--	select convert(varchar(10), getdate() - @time_begin, 108)

	set ansi_warnings OFF
    SET ARITHABORT OFF
    SET ARITHIGNORE OFF
	-- хранимки - теперь только одна хранимка в одном правиле!!!

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@orderOrg-1)*100/@countOrg + 10 + 70/@countOrg))
		execute(@strProgressExec)
	end

	set @one = 1

	while exists(select top 1 * from #atr) or @one = 1
	begin
		insert into #atr_cur (lsf, atr, str_val) select top 1 lsf, atr, str_val from #atr
		set @atr = ''
		select @atr= str_val from #atr_cur

		insert #ListForms select * from #ListFormsA where isnull(catr,'') = '' or lsf in (select A.lsf from #atr A join #atr_cur  C on A.atr = C.atr and A.str_val = C.str_val)		

		delete  #atr where exists(select top 1 * from #atr_cur C where #atr.str_val = C.str_val and #atr.atr = C.atr)
		while exists(select top 1 * from #t_KS where algorithm = 9 and Link_Rule > 0)
		begin

			select top 1 @LinkRule = Link_Rule, @ExecStr = Exec_Proc
			from #t_KS
			where algorithm = 9 and Val_Type = 2 and Link_Rule > 0
			
			select  @GroupKS = Group_KS from #t_Rules where Link_Rule = @LinkRule
         
         UPDATE #ListForms
         SET cGroupKS = @GroupKS 

			if @one = 1 or exists(select top 1 * from #t_KS K left join #t_Rules R on abs(K.Link_Rule) = R.Link_Rule where atr_code <>'' and Group_KS = @GroupKS)
			begin
				set @i = isnull((select max(ord) from #Res), 0)
			   insert #tmp 
				execute(@ExecStr)
				update #Res
				set Group_KS = @GroupKS + case when @atr = '' then '' else '#' + @atr end, cGroup = @cGroup
				where ord > @i
			END
         
			update #t_KS set Link_Rule = -Link_Rule where Link_Rule = @LinkRule 
		end
		set @one = 0
		truncate table #ListForms
		delete #atr_cur
		update #t_KS set Link_Rule = -Link_Rule where algorithm = 9
	END
   
    set ansi_warnings ON
    SET ARITHABORT ON
    SET ARITHIGNORE ON

	delete #t_KS
	where algorithm = 9
	------------------------------------------------------------------------------------------
	exec dbo.RO_RAZMNOJ_KS_OUTSIDE -- размножение правил для фильтров и знака '^'
	------------------------------------------------------------------------------------------
	-- правила типа сверки, пока algorithm = 5, затем будет настройка
	exec dbo.RO_CHECK_KS_SVERKA
	------------------------------------------------------------------------------------------
--	select convert(varchar(10), getdate() - @time_begin, 108)

	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@orderOrg-1)*100/@countOrg + 10 + 50/@countOrg))
		execute(@strProgressExec)
	end

	-- 	вычисляем правила
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select Link_Rule, OrderRow, max([sign]), K.link_form, K.lsf, max(atr_code), max(cOrderTable), max(cOrderCol), case when K.Mask = '' then coalesce(RS.Code,K.Code_Row,'') else K.Mask end, max(Filter_desc), max(part), 
					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 
					else 0
				end), orderCol, max(CodeRow), max(REPLACE(px_Comment, '@@', RTRIM(RS.Dop_col)))	
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Col = K.Link_Col and S.Link_Row = K.Link_Row left join #t_Rows_Static RS on RS.Link_Row = K.Link_Row
		left join #report_dinamics D on D.link_sf = K.lsf and D.Link_Col = K.Link_Col and D.Code_Row = K.Code_Row
	where algorithm = 1 -- простое правило
	group by Link_Rule, OrderRow, case when K.Mask = '' then coalesce(RS.Code,K.Code_Row,'') else K.Mask end, orderCol, K.lsf, K.Link_Form

	--delete #t_KS
	--where algorithm = 1

	-- правило размножения для диапозона колонок 
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select  Link_Rule, OrderRow, [sign], K.link_form, K.lsf, atr_code, cOrderTable, isnull(RC1.corderCol, RC2.corderCol), coalesce(S.Code, K.Code_Row, ''), Filter_desc, part, 
					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 
					else 0
				end, isnull(RC1.orderCol, RC2.orderCol), CodeRow, K.px_comment
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Row = K.Link_Row
		left join #t_Col RC1 on S.link_col = RC1.link_col
		left join #report_dinamics D on D.link_sf = K.lsf and D.Code_Row = K.Code_Row and D.Link_Table = K.Link_Table
		left join #t_Col RC2 on D.link_col = RC2.link_col
	where algorithm = 2 and (charindex(',' + rtrim(ltrim(str(isnull(RC1.orderCol,RC2.orderCol)))) + ',', ','+cols+',') > 0 or cols = '')

	-- правило размножения для всех строк 
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select  Link_Rule, OrderRow, [sign], K.link_form, K.lsf, atr_code, cOrderTable, cOrderCol, coalesce(RR.Code, D.Code_Row, ''), Filter_desc, part, 
					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 
					else 0
				end, orderCol, coalesce(RR.Code, D.Code_Row, ''), REPLACE(px_Comment, '@@', RTRIM(RR.Dop_col))
	from #t_KS K left join #t_Rows_Static RR on K.Link_Table = RR.Link_Table
		left join #t_summa S on S.Link_Col = K.Link_Col and RR.Link_Row = S.Link_Row and S.lsf = K.lsf
		left join #report_dinamics D on D.link_sf = K.lsf and D.Link_Col = K.Link_Col
	where algorithm = 3

	-- диапозон строк 
	while exists(select top 1 * from #t_KS where algorithm  = 4 and Link_Rule > 0) --and (@i < 2)
	begin
		select top 1 @LinkRule = Link_Rule, @ExecStr = 'insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select  Link_Rule, OrderRow, [sign], K.link_form, K.lsf, atr_code, cOrderTable, cOrderCol, S.Code, Filter_desc, part, 
					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 
					else 0
				end, orderCol, S.Code, K.px_comment
	from #t_KS K left join #t_summa S on S.lsf = K.lsf and S.Link_Col = K.Link_Col
	where Val_Type = 0 and Link_Rule = ' + STR(Link_Rule) + ' and (' + REPLACE([rows], 'COL(', 'dbo.RO_COL_Static(K.lsf, K.Link_Table, S.Link_Row,') + ')
insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select  Link_Rule, OrderRow, [sign], K.link_form, K.lsf, atr_code, cOrderTable, cOrderCol, RD.Code_Row, Filter_desc, part, 
					case Val_Type 
					when 3 then  case [sign] -- динамическая таблица
							when ''+'' then case when K.[property] & 2 = 0 then isnull(RD.float_val,0)*px else isnull(abs(RD.float_val),0)*px end
							else case when K.[property] & 2 = 0 then -isnull(RD.float_val, 0)*px else -isnull(abs(RD.float_val), 0)*px end
						end 
					else 0
				end, orderCol, RD.Code_Row, K.px_comment
	from #t_KS K left join #report_dinamics RD on RD.link_sf = K.lsf and RD.Link_Col = K.Link_Col 
	where Link_Rule = ' + STR(Link_Rule) + ' and (' + REPLACE(REPLACE(REPLACE([rows],'CODE', 'RD.Code_Row'),'.RD.Code_Row','.Code'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,K.Link_Table, RD.Code_Row,') + ')'
		from #t_KS
		where algorithm = 4 and Link_Rule > 0
		print @ExecStr
		execute(@ExecStr)
		update #t_KS set Link_Rule = -Link_Rule where Link_Rule = @LinkRule 
	end
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow)
	select F.Link_Rule, F.OrderRow, F.[sign], NULL, NULL, F.atr_code, '', '', convert(varchar(50), abs(F.factor)), '', F.part, F.factor, S.orderCol, S.CodeRow
	from #t_Factor F left join (select distinct Link_Rule, CodeRow, orderCol, atr_code from #t_Res_summand) S on F.Link_Rule = S.Link_Rule and F.atr_code = S.atr_code

	insert #t_Result ([Value], Link_Rule, atr_code, part, algorithm, orderCol, CodeRow)	
	select sum(S.Value) , S.Link_Rule, S.atr_code, S.part, 0, S.orderCol, S.CodeRow
	from #t_Res_summand S 
	group by Link_Rule, atr_code, part, orderCol, CodeRow

	update #t_KS
	set Link_Rule = abs(Link_Rule)
	where algorithm = 4

	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select K.Link_Rule, K.OrderRow, K.[sign], K.link_form, K.lsf, K.atr_code, K.cOrderTable,  case when isnull(K.cOrderCol, '') = '' then isnull(C.corderCol,'') else K.cOrderCol end , case when K.Code_Row = '' then S.CodeRow else K.Code_Row end, '', K.part, 0, S.orderCol, S.CodeRow	, K.px_comment
	from #t_KS K left merge join (select distinct Link_Rule, orderCol, CodeRow, atr_code from #t_Result) S on K.Link_Rule = S.Link_Rule and K.atr_code = S.atr_code and (K.CodeRow = S.CodeRow or K.CodeRow = '') and K.orderCol = S.orderCol
		left join #t_Col C on K.Link_Table = C.Link_Table and S.orderCol = C.orderCol
	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = K.Link_Rule and S1.atr_code = K.atr_code and S1.OrderRow = K.OrderRow and isnull(S.CodeRow,'') = isnull(S1.CodeRow,'') and isnull(S.orderCol,0) = isnull(S1.orderCol,0))
		and algorithm in (1, 2, 3, 4)

	delete #t_KS
	where algorithm in (1, 2, 3, 4)

	-- деление и умножение и т.д.
	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 else case when K.[property] & 2 = 0 then isnull(RD.Float_Val, 0)*px else isnull(abs(RD.Float_Val), 0)*px end end
	from #t_KS K
		left join #t_summa RS on K.lsf = RS.lsf and K.link_Col = RS.Link_Col and K.Link_Row = RS.Link_Row
		left join #report_dinamics RD on RD.link_sf = K.lsf and 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 K.atr_code = K2.atr_code 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 K.atr_code = K2.atr_code and CodeRow <> '')

	-- операнды для вывода в протокол
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code,cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select Link_Rule, OrderRow, [sign], K.link_form, lsf, atr_code, cOrderTable, cOrderCol, case when Val_Type = 0 then RS.Code else K.Code_Row end, Filter_desc, part, [Value], orderCol, CodeRow, K.px_comment
	from #t_KS K left join #t_Rows_Static RS on RS.Link_Row = K.Link_Row

	-- и для вычисления нужно добавть операнды, которые не размножились
	insert #t_KS (Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf,	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)
	select K.Link_Rule, K.OrderRow, val_type, [sign], K.Link_Form, K.period_form, K.period_type, K.period_year, K.begin_date, K.budg_code, K.atr_code, K.lsf, K.Link_Table, Link_Col, K.Link_Row, case when Val_Type = 0 then RS.Code else K.Code_Row end, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], S.orderCol, S.CodeRow, cOrderTable, cOrderCol
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow, atr_code from #t_KS) S on K.Link_Rule = S.Link_Rule and K.atr_code = S.atr_code
		left join #t_Rows_Static RS on RS.Link_Row = K.Link_Row
	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = K.Link_Rule and S1.atr_code = K.atr_code and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- операнды для вывода в протокол
	insert #t_Res_summand (Link_Rule, OrderRow, [sign], lf, lsf, atr_code, cOrderTable, cOrderCol, Code_Row, Filter_desc, part, [Value], orderCol, CodeRow, px_comment)
	select K.Link_Rule, K.OrderRow, K.[sign], K.link_form, K.lsf, K.atr_code, K.cOrderTable, K.cOrderCol, Code_Row, '', K.part, K.Value, S.orderCol, S.CodeRow, K.px_comment	
	from @t_temp K left join (select distinct Link_Rule, orderCol, CodeRow, atr_code from #t_KS) S on K.Link_Rule = S.Link_Rule and K.atr_code = S.atr_code
	where not exists(select top 1 * from #t_Res_summand S1 where S1.Link_Rule = K.Link_Rule and S1.atr_code = K.atr_code and S1.OrderRow = K.OrderRow and S.CodeRow = S1.CodeRow)

	-- левая часть
	insert #t_Result ([Value], Link_Rule, atr_code, part, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, atr_code, part, orderCol, CodeRow
	from #t_KS K
	where OrderRow = 1
	
	set @maxOrderRow = isnull((select max(orderRow) from #t_KS where part = 0),0)
	set @i = 2
	
	while @i<=@maxOrderRow
	begin
		update #t_Result
		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 R, #t_KS K
		where K.orderRow = @i and R.Link_Rule = K.Link_Rule  and R.atr_code = K.atr_code and isnull(R.orderCol,0) = isnull(K.orderCol,0) and isnull(R.CodeRow, '') = isnull(K.CodeRow,'')
	
		set @i = @i + 1
	end
	-- правая часть
	delete #t_KS where part = 0

	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 ([Value], Link_Rule, atr_code, part, orderCol, CodeRow)
	select case [sign] when '+' then Value else -Value end, Link_Rule, atr_code, part, 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 #t_Result
		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 R, #t_KS K
		where K.orderRow = @i and R.atr_code = K.atr_code and R.Link_Rule = K.Link_Rule and isnull(R.orderCol,0) = isnull(K.orderCol,0) and isnull(R.CodeRow, '') = isnull(K.CodeRow,'') and R.part = 1

		set @i = @i + 1
	end

	update R
	set Value = abs(Value)
	from #t_Result R join #t_Rules Ru on R.Link_Rule = Ru.Link_Rule and IsDoschet & 16 = 16
----------------------------



	-- запись в протокол
	if @cProgressTable <>'' begin
		set @strProgressExec = 'update '+@cProgressTable+' set percents = ' + str(convert(int, (@orderOrg-1)*100/@countOrg + 10 + 80/@countOrg))
		execute(@strProgressExec)
	end

	update #t_Result
	set Value = round(convert(numeric(20,5),Value), val_len)
   FROM (SELECT R.Link_Rule AS lr, min(C.Val_len) AS val_len from #t_Rows_KS [R] JOIN #t_Res_summand [S] on [R].LINK_RULE = [S].LINK_RULE AND [R].OrderRow = [S].OrderRow
               join #report_coloumns [C] ON [C].[LINK_TABLE] = [R].LINK_TABLE AND (C.[Link_Col] = [R].[LINK_COL] OR [C].orders = S.orderCol)
         GROUP BY R.Link_Rule) A
   WHERE Link_Rule = lr 

	insert #t_Result_sr (Link_Rule, atr_code, CodeRow, orderCol, error, LeftPart, RightPart, Str_Rule, Group_KS, Comment, OrderRule, sign_sr)	
	select isnull(L.Link_Rule,R.Link_Rule), isnull(L.atr_code, R.atr_code) , isnull(L.codeRow, R.codeRow), isnull(L.orderCol, R.orderCol), case Ru.[sign_sr]
			when '=' then case when abs(isnull(L.Value,0) - isnull(R.Value,0)) < @nprecision then 0 else 1 end
			when '>' then case when isnull(L.Value,0) - isnull(R.Value,0) > @nprecision then 0 else 1 end
			when '<' then case when isnull(R.Value,0) - isnull(L.Value,0) > @nprecision then 0 else 1 end
			when '>=' then case when isnull(L.Value,0) - isnull(R.Value,0) > -@nprecision then 0 else 1 end
			when '<=' then case when isnull(R.Value,0) - isnull(L.Value,0) > -@nprecision then 0 else 1 end
			when '<>' then case when abs(isnull(L.Value,0) - isnull(R.Value,0)) > @nprecision then 0 else 1 end
		end as error, isnull(L.Value,0), isnull(R.Value,0), Str_Rule, Group_KS, Comment, OrderRule, sign_sr
	from (select * from #t_result where part = 0) L
		full join (select * from #t_result where part = 1) R on L.Link_Rule = R.Link_Rule and L.atr_code = R.atr_code and isnull(L.orderCol,0) = isnull(R.orderCol,0) and isnull(L.CodeRow,'') = isnull(R.CodeRow,'')
		left join #t_Rules Ru on isnull(L.Link_Rule,R.Link_Rule) = Ru.Link_Rule
	order by isnull(L.Link_Rule,R.Link_Rule),isnull(L.codeRow, R.codeRow), isnull(L.orderCol, R.orderCol)

	delete #t_Result_sr where error = 0

	delete #Res
	where cDoc = 'Проверка выполнена успешно'
			and (exists(select top 1 * from #t_Result_sr R where R.Group_KS + case when R.atr_code <> '' then '#' + R.atr_code else '' end like #Res.Group_KS + '%')
			or (select count(*) from #Res R where Group_KS like #Res.group_KS + '%' and cDoc not like 'Отсутствует отчет%') > 3	)

	declare @nastr_del_nul_slag varchar(10)
	set @nastr_del_nul_slag='0'
	exec X_GET_OPTION 'RA_REP_OPTIONS_COM_DEL_P_KS',0,@nastr_del_nul_slag output
	
	set @nastr_del_nul_slag=isnull(@nastr_del_nul_slag, '0')


	insert #Res (orders, res, cDoc, cPeriod, cBudg, cKod, cTable, cCol, cValue, Group_KS, cGroup)
	select orders, isnull(res,''), isnull(cDoc,''), cPeriod, cBudg, isnull(cKod,''), isnull(cTable,''), isnull(cCol, ''), isnull(cValue, ''), Group_KS, @cGroup from
	(select orders, case orders when 1 then '№' + LTRIM(STR(OrderRule)) else '' end as Res,
		case orders when 1 then Str_Rule when 6 then 'Результат слева' when 7 then 'Результат справа' when 8 then 'Отклонение' else '' end as cDoc, case orders when 1 then 'Группа: ' + isnull(Group_KS, '') else '' end as cPeriod, '' as cBudg,
		 case orders when 1 then isnull(Comment, '') when 3 then sign_sr else '' end as cKod, '' as cTable, '' as cCol, case orders when 6 then ltrim(dbo.[rn_convert_number](LeftPart,@round,' ')) when 7 then ltrim(dbo.[rn_convert_number](RightPart,@round,' ')) when 8 then '<font color="#ff0000">' + ltrim(dbo.[rn_convert_number](LeftPart-RightPart,@round, ' ')) else '' end as cValue, orderCol, codeRow, OrderRule, 0 as OrderRow, Group_KS + case when atr_code <> '' then '#' + atr_code else '' end as Group_KS
	from #t_Result_sr S left join @t on 1 = 1
	union all
	select 2 + part * 2, '', case when cOrderTable <> '' and isnull(codeForm, '') = '' then 'отчет ' + isnull((select Code from dbo.report_forms where link_form = lf), '') + ' не найден' else codeForm + ' ' + catr end, isnull(cPeriod,''), isnull(cBudg,''), [sign] + S.Code_Row + isnull(px_comment,''), cOrderTable, cOrderCol, ltrim(dbo.[rn_convert_number](Value, @round, ' ')), S.orderCol, S.codeRow, OrderRule, OrderRow, Group_KS + case when R.atr_code <> '' then '#' + R.atr_code else '' end
	from #t_Res_summand S inner join #t_Result_sr R on S.Link_Rule = R.Link_Rule and isnull(S.CodeRow, '') = isnull(R.CodeRow, '') and isnull(S.orderCol,0) = isnull(R.orderCol,0) and isnull(S.atr_code,'') = isnull(R.atr_code,'')
	left join #ListFormsA LF on S.lsf = LF.lsf
	where abs(Value) > 0.0001 or @nastr_del_nul_slag='0') A
	order by OrderRule, orderCol, codeRow, orders, OrderRow

--	insert #Res_Group (orders, res, cDoc, cPeriod, cBudg, cKod, cTable, cCol, cValue, Group_KS, cGroup)
--	select orders, res, cDoc, cPeriod, cBudg, cKod, cTable, cCol, cValue, Group_KS, cGroup
--	from #Res
--	order by Group_KS, ord

	delete @t_temp
	truncate table #t_Res_summand
	truncate table #t_Result	
	truncate table #t_KS
	truncate table #t_Result_sr
	truncate table #ListFormsA
	truncate table #t_Summa
	truncate table #report_dinamics
end

set @time_end = getdate()

update #res
set cDoc = 'Количество ошибок: ' + c,
	cTable = 'Время выполнения: ' + t
from (select LTRIM(STR(count(*))) as c, convert(varchar(10), @time_end - @time_begin, 108) as t from #res where cDoc like  '%Отклонение%') A
where ord = 1

   set @cDataDesc = '<B> Организация: </B>' + RTRIM(isnull(@NameOrg, '')) + '<B> Бюджет: </B>' + RTRIM(isnull(@NameBudg,'')) + '<B> Период: </B>' + RTRIM(isnull(@cPeriod, '')) + '</B>'

  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = @cDataDesc, @cDataTableName  = '#Res',@cShowFields  = 
'<field name=''res'' width=''4%'' WRAP=''1''></field>
 <field name=''cdoc'' width=''36%'' WRAP=''1''></field>
 <field name=''cPeriod'' width=''10%'' WRAP=''1''></field>
 <field name=''cBudg'' width=''10%'' WRAP=''1''></field>
 <field name=''ctable'' width=''15%'' WRAP=''1''></field>
 <field name=''ckod'' width=''15%'' WRAP=''0''></field>
 <field name=''ccol'' width=''5%'' WRAP=''1''></field>
<field name=''cvalue'' width=''5%'' WRAP=''0''></field>'
, @cFieldsDesc  = 'Формула|Документ|Период|Бюджет|Таблица|Операция и код|Графа|Значение', @cOrderFields = 'Group_KS, ord'--, @cGroupFields = 'cGroup', @cGroupDesc = '<Org @cGroup>'



IF @tmpTable<>''
begin
	set @ExecStr='insert '+@tmpTable+' select res,cdoc, cPeriod, cBudg,ctable,ckod,ccol,cvalue from #Res_Group  '
	execute(	@ExecStr)
end
else begin
	if ((select count(*) from #Res_Group) > 10000 and @typeProtokol = 0) or @typeProtokol = 1
	begin
			select isnull(res, '') as res,isnull(cdoc,'') as cDoc, isnull(cPeriod,'') + ' ' + isnull(cBudg,'') as cPeriod,isnull(ctable,'') as cTable,isnull(ckod, '') as ckod, isnull(ccol,'') as ccol, isnull(cvalue, '') value from #Res_Group order by  ord
	end
	else
	begin
--	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#ks_protokol_HTML', @cDataDesc    = 'Протокол', @cDataTableName  = '#Res_Group',@cShowFields  = 
--	'<field name=''res'' width=''4%'' WRAP=''1''></field>
--	 <field name=''cdoc'' width=''36%'' WRAP=''1''></field>
--	 <field name=''cPeriod'' width=''10%'' WRAP=''1''></field>
--	 <field name=''cBudg'' width=''10%'' WRAP=''1''></field>
--	 <field name=''ctable'' width=''15%'' WRAP=''1''></field>
--	 <field name=''ckod'' width=''15%'' WRAP=''0''></field>
--	 <field name=''ccol'' width=''5%'' WRAP=''1''></field>
--	<field name=''cvalue'' width=''5%'' WRAP=''0''></field>'
--	, @cFieldsDesc  = 'Формула|Документ|Период|Бюджет|Таблица|Операция и код|Графа|Значение', @cOrderFields = 'ord', @cGroupFields = 'cGroup', @cGroupDesc = '<Org @cGroup>'

		select * from #ks_protokol_HTML order by [order]
	end
end

drop table #t_Rules_region
drop table #Res_Group
drop table #report_coloumns
drop table #ks_protokol_HTML
drop table #t_Factor
drop table #t_Col
drop table #t_KS
drop table #t_Rules
drop table #t_Rows_KS
drop table #t_Result
drop table #Res
drop table #ListFormsA
drop table #ListForms
drop table #t_Rows_Static
drop table #tmp
drop table #t_Result_sr
drop table #t_Res_summand
drop table #report_dinamics
drop table #t_Summa
drop table #atr
drop table #atr_cur
drop table #atr_empty
drop table #report_tables
drop table #Res_atr
DROP TABLE #t_MDKS_PROC
DROP TABLE #t_PeriodType

--select * from #Rules

--drop table #Rules
GO
GRANT ALL ON dbo.[RO_CHECK_KS_OUTSIDE] 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.[BK_SAVE_DOC_INVOICE_COR_OUT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_SAVE_DOC_INVOICE_COR_OUT]

GO
CREATE PROCEDURE dbo.BK_SAVE_DOC_INVOICE_COR_OUT
	@intLINK	INT	OUTPUT,
	@strNUMBER	VARCHAR (30) = null,
	@dDOC_DATE	DATETIME = null,
	@dDOC_DATE_PROV	DATETIME = null,
	@nDOC_Summa	NUMERIC(19,2) = 0,
	@strComment	VARCHAR(254) = null,
	@intDEP_LINK	INT	=	NULL,

	@intOSNOV_LN    INT = null,
	@strCOR_NUM	VARCHAR(30) = '',
	@dCOR_DATE	DATETIME = NULL,
	@intINBOOK     TINYINT = 0
AS
BEGIN
	SET LOCK_TIMEOUT 30000
	SET IMPLICIT_TRANSACTIONS ON

	DECLARE @intERROR	tinyint,
		@strVALUE	varchar(7000),
		@strEventText	varchar(254),
		@inttrancount	int,
	
		@intDOC_SOBJ_LINK	INT,
		@intSOBJ_LINK	INT

	SET @inttrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	BEGIN TRAN
	COMMIT TRAN

	--Проверка рабочего периода
	IF @dDOC_DATE_PROV is not null and not exists(Select * from admin_info Where @dDOC_DATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	--Вставка/обновление G_PROV
	SET @intDOC_SOBJ_LINK = dbo.GetObjLink ('DOCUMENTS_INVOICE_COR_OUT')

	EXECUTE @intERROR = dbo.X_UPDATE_G_PROV
			@intLINK OUTPUT,
			@strNUMBER,
			@dDOC_DATE,
			@intDOC_SOBJ_LINK,
			@dDOC_DATE_PROV,
			@nDOC_Summa,
			@strComment,
			0,
			@intDEP_LINK,
			DEFAULT

	IF @intERROR <> 0
		RETURN @intERROR

	EXECUTE @intERROR = dbo.BK_UPDATE_G_PROV_INVOICE_COR
			@intDOC_LINK	=	@intLINK, 
			@intOSNOV	=	@intOSNOV_LN,
			@strCOR_NUM	=	@strCOR_NUM,
			@dCOR_DATE	=	@dCOR_DATE,
			@INBOOK		=	@intINBOOK

	IF @intERROR <> 0
		RETURN @intERROR

	--Событие системного журнала
	SET @strEventText = 'Корректировочный счет-фактура (выданный)' + ' №' + RTRIM(@strNUMBER) + ' от ' + convert(varchar, @dDOC_DATE, 104)
	EXECUTE dbo.WF_GENERATEEVENT 'Сохранение документа',
			@strEventText,
			@intDOC_SOBJ_LINK,
			'G_PROV',
			@intLINK

	IF @@TRANCOUNT > @inttrancount
		COMMIT TRAN

	RETURN 0
END






GO


GRANT EXECUTE ON dbo.[BK_SAVE_DOC_INVOICE_COR_OUT] 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_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 
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)
		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

		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,
				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		= PP.D_ACC_NUM,
				BIC_RCP		= PP.D_BIK,
				NAME_BIC_RCP = PP.D_BANK,
				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] = ''
		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


	if @iGroupKBK = 1
	-- Таблица 5 (PPST)
		select  LINK = GP.LINK,
				LINK_UP = GP.LINK,
				KBK = left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20),
				TYPE_KBK = case isnull(KBK1.[TYPE], KBK.[TYPE]) when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				ADD_KLASS = ISNULL(DCL.CODE,''),
				ADD_KLASS_RCP = '',
				[SUM] = sum(GP2.SUMMA),
				DIR_SUM	= '1',
				MES_FIN	= convert(char(2),month(GP.DATE)),
				REZERV	= '',
				KOD_FIN = case D.BUH_TYPE when '1' then SA.cSource else '' end,
				-- Поля для приема выписки
				NUM_BO = '',
				ОКАТО = ''

		from G_PROV GP 
		inner join dbo.BufferGetTableByID(@cBuffId) B on GP.LINK = B.LINK
		inner join G_PROV1 GP1 on GP1.LINK_UP = GP.LINK
		INNER JOIN G_PROV2 GP2 ON GP2.LINK_UP = GP1.LINK
		INNER JOIN G_PROV_AP GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
		INNER JOIN dbo.DEPARTMENTS D on GP.DEP = D.LINK
		INNER JOIN dbo.S_ACCOUNTS SA on GPA1.ACCOUNT = SA.LINK
		LEFT JOIN KL_KBK KBK ON GPA1.KBK = KBK.LINK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN KL_KBK KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		LEFT JOIN KOSGU SGU ON GPA1.EKR = SGU.LINK
		LEFT JOIN DOP_CLASSIF DCL ON GPA1.AP2 = DCL.LINK
		group by GP.LINK, convert(char(2),month(GP.DATE)), left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20), ISNULL(DCL.CODE,''), isnull(KBK1.[TYPE], KBK.[TYPE]),  D.BUH_TYPE, SA.cSource
	else
		select  LINK = GP2.LINK,
				LINK_UP = GP.LINK,
				KBK = left(replace(isnull(KBK1.CODE, KBK.CODE),'.','') + SGU.CODE ,20),
				TYPE_KBK = case isnull(KBK1.[TYPE], KBK.[TYPE]) when 1 then '10'
												 when 2 then '20'
												 when 4 then '31'
												 when 8 then '32'
												 else '' end,
				ADD_KLASS = ISNULL(DCL.CODE,''),
				ADD_KLASS_RCP = '',
				[SUM] = GP2.SUMMA,
				DIR_SUM	= '1',
				MES_FIN	= convert(char(2),month(GP.DATE)),
				REZERV	= '',
				KOD_FIN = case D.BUH_TYPE when '1' then SA.cSource else '' end,
				-- Поля для приема выписки
				NUM_BO = '',
				ОКАТО = ''

		from G_PROV GP 
		inner join dbo.BufferGetTableByID(@cBuffId) B on GP.LINK = B.LINK
		inner join G_PROV1 GP1 on GP1.LINK_UP = GP.LINK
		INNER JOIN G_PROV2 GP2 ON GP2.LINK_UP = GP1.LINK
		INNER JOIN G_PROV_AP GPA1 ON GP2.LINK = GPA1.LINK_UP AND DB_KR = 1
		INNER JOIN dbo.DEPARTMENTS D on GP.DEP = D.LINK
		INNER JOIN dbo.S_ACCOUNTS SA on GPA1.ACCOUNT = SA.LINK
		LEFT JOIN KL_KBK KBK ON GPA1.KBK = KBK.LINK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN KL_KBK KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		LEFT JOIN KOSGU SGU ON GPA1.EKR = SGU.LINK
		LEFT JOIN DOP_CLASSIF DCL ON GPA1.AP2 = DCL.LINK	


end
else
begin

	select
		P.link, 
		P.link as link_up,
		BK_IN_TGT,
		S_ACC_LINK,
		DATE,

		[NUM_PP] = NUMBER,
		[DATE_PP] = DATE,
		[VID_PL] = 
			CASE	
				WHEN KIND = 'почтой'     THEN '1'
				WHEN KIND = 'телеграфом' THEN '2'
				WHEN KIND = 'электронно' THEN '3'
				WHEN KIND = 'срочно' 	 THEN '4'
				ELSE '0' 
			END,
		[SUM_PP] = summa, 
		[INN_PAY] = P.S_INN,
		[KPP_PAY] = case P.PRINT_KPP when 1 then P.S_KPP else '' end,
		[KOD_BP_PAY] = P.S_BUDG,
		[NAME_BP_PAY] = convert(varchar(120), ltrim(rtrim(S_FNAME))),
		[NAME_PAY] = dbo.BB_DEP_NAME_FOR_SHABLON(isnull(APO.SHABLON_D,APOD.SHABLON_D), default, P.S_ACC_LINK), 
		[NUM_LS_PAY] = S_ACC_NUM,
		[KOD_TOFK_PAY] = P.S_KAZN_CODE,
		[INN_OK_PAY] = case P2.INN_OK_PAY when 1 THEN P.S_KAZN_INN ELSE '' END,
		[NM_OK_PAY] = CASE P2.NM_OK_PAY when 1 THEN convert(varchar(120), P.S_KAZN) ELSE '' END,
		[RS_PAY] = case P.S_ACC_TYPE when 1 then P.S_ACC_NUM else P.S_SCH_K end,
		[BIK_PAY] = P.S_BIK,
		[BANK_PAY] = P.S_BANK,
    	[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,
		[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] = convert(varchar(3), 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,
		convert(varchar(3), 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] = convert(varchar(3), 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on BB_EXPORT_PP 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_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(20), kbkcode2 varchar(20), kbkcode3 varchar(20), kbkcode4 varchar(20), 
		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_KPP VARCHAR(9))
INSERT INTO #S_OBOSOB (SUBDIV_LINK, O_OKATO, O_KPP)
SELECT SUBDIV_LINK, O_OKATO, O_KPP 
FROM [dbo].SUBDIVISION(@DATE) 
WHERE OBOSOB = 1

CREATE TABLE #P_OBOSOB (PERS_LINK INT, O_OKATO VARCHAR(14), O_KPP VARCHAR(9))
INSERT INTO #P_OBOSOB(PERS_LINK, O_OKATO, O_KPP)
SELECT E.PERS_LINK, SO.O_OKATO, SO.O_KPP 
FROM 
	#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
	INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK

-----------------------------------------------------------
	INSERT INTO #RES0 (
		LINK_FACE,
		SEX,
		INNFIZ, --NALOG,
		NUMB_SERT,
		STATUS,
		FIO,
		FM, IM, OT,
		KDVD,
		SERNOM, 
		BIRTH,
		GRAZD,
		KSTR,
		LINK_ADR,
		IND_ADR,
		REGION,
		RAION,
		GOROD,
		NASEL,
		STREET,
		HOUSE,
		KORP,
		FLAT, 
		KSTR_ino,
		Adr_ino,
		ERR,
		O_OKATO,
		O_KPP
	)

	SELECT 	distinct 
		P.LINK, P.SEX, P.INN, /*P.IFNS,*/ P.INSUR_NUM, 
		CASE 
			WHEN P.RESIDENT  IS NULL THEN ''
			WHEN P.RESIDENT = 1 THEN '1'
			WHEN P.RESIDENT = 0 THEN '2'
		END,
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT),
		RTRIM(P.FM), RTRIM(P.IM), RTRIM(P.OT),
		[KDVD] = (SELECT TOP 1 CODE FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
		P.DOC_NUM,
		P.BIRTHDATE,
		GRAZD= (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK),
		KSTR= (case when (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK) = '1' then '643' else '' END),
		ADR.LINK_ADDR,
		ADR.IND_ADR,
		ADR.REGION,
		ADR.RAION,
		ADR.GOROD,
		ADR.NASEL,
		ADR.STREET,
		ADR.HOUSE,
		ADR.KORP,
		ADR.FLAT,
		KSTR_ino = '',
		Adr_ino = '',
		0,
		PO.O_OKATO,
		PO.O_KPP
	FROM 
		#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

	--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(20), SUMMA numeric(18,2))

	INSERT INTO #PAYS_NDFL (LINK_FACE, LINK_PAYS, kbk_code, SUMMA)
	SELECT LINK_FACE, 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.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(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), @varKSPHONE VARCHAR(254), 
		@varKSGLBUH VARCHAR(254), 
		@varKSRESULT BIT

	SELECT 
		@varKScInn = INN, @varKScKPP = KPP,
		@varKSFULL_NAME = FULL_NAME, 
		@varKSNALOG = NALOG, @varKSOKATO = Replace(OKATO,' ',''), 
		@varKSPHONE = PHONE, 
		@varKSGLBUH  = GLBUH
	FROM #DEP
	
	IF LEN(@varKScInn) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан ИНН организации')
	ELSE BEGIN
		IF LEN(@varKScInn) <> 10 BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
		ELSE BEGIN
			EXEC SD_CHECK_INN @varKScInn, @varKSRESULT OUTPUT, 0
			IF @varKSRESULT = -1
				INSERT INTO #LOG (LINK, NUMBER, DETAIL)
				VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
	END

	
	IF LEN(@varKScKPP) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан КПП организации')
	ELSE BEGIN
		IF LEN(@varKScKPP) <>9  BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'КПП организации должен быть 9 знаков')
		END
	END

	IF LEN(@varKSNALOG) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан код ИФНС')
	ELSE BEGIN
		IF LEN(@varKSNALOG) <> 4  
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Код ИФНС должен быть 4 знака')

	END

	IF LEN(@varKSFULL_NAME) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано наименование организации-отправителя')


	IF LEN(@varKSOKATO) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)		VALUES (0, 'Общие ошибки', 'Не указан код ОКАТО')

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан код ОКАТО у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	FROM
		#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
		INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK
	WHERE
		LEN(O_OKATO) = 0
		
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан либо указан неверно код KPP у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	FROM
		#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
		INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK		
	WHERE
		LEN(O_KPP) <> 9

	IF LEN(@varKSPHONE) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан контактный телефон')

	IF LEN(@varKSGLBUH) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано ответственное лицо')

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT DISTINCT
		0, 'Общие ошибки', 'В настройках по зарплате не указан вычет с кодом ' + LTRIM(RTRIM(ISNULL(D.SNAME,'')))
	FROM
		dbo.TAX_DEDUCTIONS TD INNER JOIN DBO.DICTIONARY_TYP_DEDUCTION D ON D.LINK = TD.LINK_DICTION
	WHERE
		TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth
		AND
		TD.LINK_DICTION NOT IN (SELECT REF_PAY FROM dbo.Salary_deductions(@BEGIN_YEAR))

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указана фамилия' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(FM, '')) = 0 AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указано имя' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(IM, '')) = 0 AND OSD13 > 0 

/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано отчество' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(Ot, '')) = 0 AND OSD13 > 0 
*/
/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Неверный ИНН сотрудника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE dbo.IsValidINNFiz(INNFIZ) = 0
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан статус работника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE STATUS = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано гражданство' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE GRAZD IS NULL AND OSD13 > 0 
/*
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Не указан ИНН' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = ''
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо документ, удостоверяющий личность' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' and KDVD IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо номер документа' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND ISNULL(SERNOM, '') = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо дата рождения'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND BIRTH IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан адрес'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND link_adr IS NULL AND OSD13 > 0 

	SET @varKSCNT = 0
	SELECT @varKSCNT = COUNT(DISTINCT LINK) FROM #LOG WHERE LINK > 0

	UPDATE #RES0
	SET ERR = 1
	WHERE LINK_FACE IN (SELECT LINK_FACE FROM #LOG)

	/*заявленные имущественные вычеты*/
	Select LINK_PERSON, NUM_REF, DATE_REF, IFNS_CODE  into #td  from dbo.TAX_DEDUCTIONS td
	where TD.LINK_DEP = @DEP_LINK AND link = (select min(link) from dbo.TAX_DEDUCTIONS td1 where TD1.LINK_DEP = @DEP_LINK AND td1.LINK_PERSON =  td.LINK_PERSON and td1.[YEAR] = @varKSnYear and td1.Month1 <= @nMonth)

	declare @KBK_DEFAULT varchar(254)
	Set @KBK_DEFAULT = (select Top 1 CODE_KBK from dbo.sd_empl where LINK_KBK > 0)

	UPDATE #RES0 Set kbkcode1 = @KBK_DEFAULT, kbksum1 = 0 where ISNULL(kbksum1,0) = 0

	/*Контроль имущественных вычетов*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Указаны не все данные в уведомлении на имущественный вычет'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 inner join  #td on #RES0.LINK_FACE = #td.LINK_PERSON 
	WHERE rtrim(ltrim(ISNULL(NUM_REF,''))) = '' or rtrim(ltrim(ISNULL(IFNS_CODE,''))) = '' or DATE_REF is null AND OSD13 > 0 

	CREATE TABLE #RES_OUT (ID INT,LINK_FACE INT,mes INT,LINK_INC INT,CODE_INC VARCHAR(4),SUMMA_INC NUMERIC(18,2),LINK_DED INT,CODE_DED VARCHAR(3),SUMMA_DED NUMERIC(18,2),ID2 INT)

	INSERT INTO #RES_OUT (ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2)
	SELECT ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2 = 0 
	FROM #PAYS_0 
	ORDER BY LINK_FACE, MES, CODE_INC
	
	---СОРТИРОВКА
	CREATE TABLE #RES_OUT_ORD (NUM_PP INT IDENTITY(1,1), ID INT, LINK_FACE INT)
	INSERT INTO #RES_OUT_ORD (ID, LINK_FACE)
	SELECT ID, LINK_FACE FROM #PAYS_0 ORDER BY LINK_FACE, MES, CODE_INC
	--
	CREATE TABLE #RES_OUT_ORD2 (LINK_FACE INT, MIN_NUM INT)
	INSERT INTO #RES_OUT_ORD2 (LINK_FACE, MIN_NUM)
	SELECT LINK_FACE, MIN(NUM_PP) FROM #RES_OUT_ORD GROUP BY LINK_FACE
	---СОРТИРОВКА ДЛЯ КАЖДОГО ФИЗЛИЦА
	UPDATE R
	SET R.ID2 = O.NUM_PP - O2.MIN_NUM + 1
	FROM 
		#RES_OUT R 
		INNER JOIN #RES_OUT_ORD O ON O.ID = R.ID
		INNER JOIN #RES_OUT_ORD2 O2 ON O2.LINK_FACE = R.LINK_FACE

	CREATE TABLE #ORDERS (ID int)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'ALTER TABLE #ORDERS ADD [NOM_SPR] INT IDENTITY(' + RTRIM(str(ISNULL(@varKSnFirstNum,1))) + ',1)'
	EXEC(@SQL)

	INSERT INTO #ORDERS (ID) 
	SELECT DISTINCT ID 
	FROM #RES0 
	WHERE LINK_FACE IN ( Select DISTINCT LINK_FACE from #RES_OUT where [ID2]%2 = 1 )
			--AND ISNULL(OSD13,0) > 0
	ORDER BY ID

	--UPDATE #ORDERS SET NOM_SPR = NOM_SPR + @varKSnFirstNum - 1

	--- общее количество документов
	UPDATE #DEP SET DOCCOUNT = ISNULL((SELECT MAX(NOM_SPR) FROM #ORDERS),0)

	-------------------
	SELECT 
		R.ID, O.NOM_SPR, R.LINK_FACE, R.SEX, R.INNFIZ, R.NUMB_SERT, R.STATUS, 
		R.FIO, R.FM, R.IM, R.OT, R.KDVD, R.SERNOM, R.BIRTH, R.GRAZD, R.KSTR, 
		R.LINK_ADR, R.IND_ADR, R.REGION, R.RAION, R.GOROD, R.NASEL, R.STREET, 
		R.HOUSE, R.KORP, R.FLAT, R.KSTR_ino, R.Adr_ino, 
		R.ksv1, R.ssv1, R.ksv2, R.ssv2, R.ksv3, R.ssv3, R.ksv4, R.ssv4, R.ksv5, R.ssv5, R.ksv6, R.ssv6, 
		R.ksv7, R.ssv7, R.ksv8, R.ssv8, R.ksv9, R.ssv9, R.ksv10, R.ssv10, R.ksv11, R.ssv11, R.ksv12, R.ssv12, 
		R.ssv, R.siv, R.osd13, R.sdo13, R.nalogn13, R.nalogu13, R.nalog13s, R.err, R.S_5_6, R.S_5_7, R.dolg_np, R.dolg_na, 
		R.kbkcode1, R.kbkcode2, R.kbkcode3, R.kbkcode4, R.kbksum1, R.kbksum2, R.kbksum3, R.kbksum4, 
		R.VIFNSPL, R.ZSummPL, R.UdSumPL, R.VzkIFNS, 
		ndoc_td = NUM_REF,
		ddoc_td = DATE_REF,
		nalog	= @varKSNALOG,
		KPP1 = ISNULL(R.O_KPP,@varKScKPP),
		OKATO1 = replace(ISNULL(R.O_OKATO,@varKSOKATO),' ',''),
		OKATO2 = (Case when ISNULL(kbksum2,0) <> 0 then @varKSOKATO else '' end),
		OKATO3 = (Case when ISNULL(kbksum3,0) <> 0 then @varKSOKATO else '' end),
		OKATO4 = (Case when ISNULL(kbksum4,0) <> 0 then @varKSOKATO else '' end),
		T.M1, T.CINC1, T.SINC1, T.CDED1, T.SDED1, T.M2, T.CINC2, T.SINC2, T.CDED2, T.SDED2,
		#td.LINK_PERSON, #td.NUM_REF, #td.DATE_REF, #td.IFNS_CODE
	FROM #RES0 R 
		INNER JOIN #ORDERS O ON O.ID = R.ID
		INNER JOIN ( 
			Select	T1.LINK_FACE, M1= T1.MES, CINC1= T1.CODE_INC, SINC1= T1.SUMMA_INC, CDED1= T1.CODE_DED, SDED1= T1.SUMMA_DED, M2= T2.MES, CINC2= T2.CODE_INC, SINC2= T2.SUMMA_INC, CDED2= T2.CODE_DED, SDED2= T2.SUMMA_DED
			from	(Select * from #RES_OUT where [ID2]%2 = 1) T1 left join (Select * from #RES_OUT where [ID2]%2 = 0) T2 on T1.link_FACE = T2.LINK_FACE AND T1.[ID2] = (T2.[ID2]-1)
		) T on R.LINK_FACE = T.LINK_FACE
		left join  #td on R.LINK_FACE = #td.LINK_PERSON
	--where OSD13 > 0 
	ORDER BY O.NOM_SPR, T.M1, T.CINC1, T.M2, T.CINC2

	---
	SELECT *, CAST(  (CAST (DOCCOUNT AS INT) - @varKSCNT) AS VARCHAR(254) ) AS DOCCOUNT2 FROM #DEP 
	---	

	UPDATE L SET
		NUMBER = O.NOM_SPR
	FROM 
		#LOG L
		INNER JOIN #RES0 R ON L.LINK = R.LINK_FACE
		INNER JOIN #ORDERS O ON O.ID = R.ID
	
	SELECT * FROM #LOG ORDER BY LINK, ERR
	---
	EXEC dbo.BufferClear

	DROP TABLE #E_SUBDIV
	DROP TABLE #S_OBOSOB
	DROP TABLE #P_OBOSOB	
	DROP TABLE #LOG	
	DROP TABLE #RES0	
	DROP TABLE #ORDERS				
	
END




GO


GRANT EXECUTE ON dbo.[SD_REP_2NDFL] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_CALC_RRO_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_CALC_RRO_ITOG]
GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.[RT_CALC_RRO_ITOG]
	@Void int,
	@LSF int
AS
  IF OBJECT_ID('tempdb..#ks_protokol_HTML') IS NOT NULL AND OBJECT_ID('tempdb..#res') IS NOT NULL
      RETURN 0
      
	declare @PeriodCode datetime
	select @PeriodCode = begin_date from dbo.report_saved_forms where link_saved_form = @LSF
-------------------------------------------------------------------------------------------------------------------
delete from dbo.report_dinamics 
where link_sf = @LSF 
and
((	rtrim(SUBSTRING(RTRIM(CODE_ROW),8,9)) not in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(1,@PeriodCode)) 
	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 link_form from dbo.report_saved_forms where link_saved_form = @LSF
			) 
			and Orders = 1
		)
	)
)
or
(	rtrim(SUBSTRING(RTRIM(CODE_ROW),8,9)) not in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(2,@PeriodCode)) 
	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 link_form from dbo.report_saved_forms where link_saved_form = @LSF
			) 
			and Orders = 2
		)
	)
))
-------------------------------------------------------------------------------------------------------------------
delete from #report_dinamics 
where link_sf = @LSF 
and
((	rtrim(SUBSTRING(RTRIM(CODE_ROW),8,9)) not in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(1,@PeriodCode)) 
	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 link_form from dbo.report_saved_forms where link_saved_form = @LSF
			) 
			and Orders = 1
		)
	)
)
or
(	rtrim(SUBSTRING(RTRIM(CODE_ROW),8,9)) not in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(2,@PeriodCode)) 
	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 link_form from dbo.report_saved_forms where link_saved_form = @LSF
			) 
			and Orders = 2
		)
	)
))
-------------------------------------------------------------------------------------------------------------------
exec RT_CALC_RRO1_ITOG @LSF,@PeriodCode
exec RT_CALC_RRO2_ITOG @LSF,@PeriodCode
--exec dbo.RN_SPLIT_CODE_ROW @LSF

select 0
GO
GRANT EXECUTE ON dbo.[RT_CALC_RRO_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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 @varKSI int, @varKSRefDoc int
SET @varKSI = 0
SET @varKSRefDoc = @LINK_ARCH
WHILE @varKSI < 10
BEGIN
	SET @varKSI = @varKSI+1
	SET @varKSRefDoc = ISNULL((SELECT TOP 1 REF_DOC FROM DIS WHERE LINK = @varKSRefDoc), @varKSRefDoc)
END

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))

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)

 --если страховой стаж работника менее 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) 
			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 BETWEEN YEAR(@DATE_BEGIN_RP) AND YEAR(@DATE_END_RP) AND LINK_EMPL = @LINK_EMPL 

	--- Определим, делать ли расчет в разрезе КБК
	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 <= @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)
	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) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= YEAR(@DATE_BEGIN_RP) ))
				+ ',0)' ELSE ',0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_END_RP)) )
			THEN ', ISNULL(SUMMA_' 
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) <= YEAR(@DATE_END_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

-- Время
DECLARE @WTIME TABLE(Y INT)
INSERT INTO @WTIME (Y)
SELECT DISTINCT Y FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP)

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
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 * 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 = 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 = 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,4), 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

----
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, CJ.DAYS, 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.DAYS, CJ.HOURS, 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

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.[X_SAVE_DOCUMENTS_INVOICE_ISSUED]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_SAVE_DOCUMENTS_INVOICE_ISSUED]

GO


CREATE PROCEDURE dbo.X_SAVE_DOCUMENTS_INVOICE_ISSUED
	@varKSpLINK		int	OUTPUT,
	@varKSpNUMBER	char(25) = null,
	@varKSpDATE		datetime = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment	varchar(254) = null,
	@varKSpSEL_LINK       INT = null,
	@varKSpCONS1_SELF     BIT = null,
	@varKSpCONS1_LINK     INT = null,
	@varKSpPROD_LINK      INT = null,
	@varKSpBUY_LINK       INT = null,
	@varKSpCONS2_SELF     BIT = null,
	@varKSpCONS2_LINK     INT = null,
	@varKSpNUM_BASE       VARCHAR(6) = null,
	@varKSpDATE_BASE      DATETIME = null,
	@varKSpNALOG_DOC      NUMERIC(13,2) = null,
	@OSNOV       INT = null,
	@varKSpBOOK_SALES     BIT = null,
	@varKSpPAYS_LINK       INT = null,
	@pTAX_RATE		NUMERIC (4,2) = NULL,
	@COR_NUM	VARCHAR (30) = '',
	@COR_DATE	DATETIME = NULL

AS
	DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKStrancount	int,
		@varKSLinkObj	int,
		@varKS_param	int

SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	--Проверка рабочего периода
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	--Проверка обязательных реквизитов
	IF @varKSpSEL_LINK IS NULL OR @varKSpSEL_LINK = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END

	SELECT @varKSLinkObj = LINK
	FROM dbo.S_OBJECTS
	WHERE CODE = 'DOCUMENTS_INVOICE_ISSUED'

	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV
			@varKSpLINK OUTPUT,
			@varKSpNUMBER,
			@varKSpDATE, 
			@varKSLinkObj,
			@varKSpDATE_PROV,
			@varKSpSumma,
			@varKSpComment,
			0,
			@varKSpSEL_LINK

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_INVOICE
			@intDOC_LINK	= @varKSpLINK,
			@intSELLER	= @varKSpSEL_LINK,
			@intBUYER	= @varKSpBUY_LINK,
			@intSHIPPER	= @varKSpCONS1_LINK,
			@intRECEIVER	= @varKSpCONS2_LINK,
			@PRODUCER	= @varKSpPROD_LINK,
			@strPAY_NUM	= @varKSpNUM_BASE,
			@dPAY_DATE	= @varKSpDATE_BASE,
			@intOSNOV	= @OSNOV,
			@nTAX_RATE	= @pTAX_RATE, 
			@intINBOOK	= @varKSpBOOK_SALES,
			@SEL_SHIP	= @varKSpCONS1_SELF,
			@BUY_RECIVE	= @varKSpCONS2_SELF,
			@strCOR_NUM	= @COR_NUM,
			@dCOR_DATE	= @COR_DATE,
			@TAX_SUM	= @varKSpNALOG_DOC

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	SELECT @varKS_param = LINK
	FROM dbo.S_OBJECTS
	WHERE CODE = 'PAYS_LINK_ISSUED'

	--Ссылка на платежку
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_REF
			@varKSpLINK,
			@varKS_param,
			@varKSpPAYS_LINK

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	--Событие системного журнала
	SET @varKSEventText = 'Счет-фактура выданный' + ' №' + RTRIM(@varKSpNUMBER) + ' от ' + convert(varchar, @varKSpDATE, 104)
	EXECUTE dbo.WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSLinkObj, 'G_PROV', @varKSpLINK

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[X_SAVE_DOCUMENTS_INVOICE_ISSUED] TO PUBLIC

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 @varKSI int, @varKSRefDoc int
SET @varKSI = 0
SET @varKSRefDoc = @LINK_ARCH
WHILE @varKSI < 10
BEGIN
	SET @varKSI = @varKSI+1
	SET @varKSRefDoc = ISNULL((SELECT TOP 1 REF_DOC FROM DIS WHERE LINK = @varKSRefDoc), @varKSRefDoc)
END

SET @DATE_BEGIN_P = ISNULL((SELECT TOP 1 DATE1 FROM dbo.DIS WHERE LINK = @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

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 @DEFAULT_KBK INT
	SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)

	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

	--- Определим, делать ли расчет в разрезе КБК
	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
	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 = 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 = (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

----
Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, CJ.DAYS, 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.DAYS, CJ.HOURS, 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_BASE_SUM_PAY]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_BASE_SUM_PAY]

GO

CREATE PROCEDURE [dbo].SD_BASE_SUM_PAY
/*
Используется для расчета начислений процентом
*/

 @varKSRefPay 	int,
 @varKSlinkEmpl	 int,
 @varKSdDate1	datetime,
 @varKSdDate2	datetime,
 @LINK_KBK 	INT = NULL,
 @LINK_SOVM INT = -1	
AS  

SET @LINK_KBK = COALESCE(@LINK_KBK,0)

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

SELECT 	CODE_PAY = SJ.[CODE_PAYS],
	NAME_PAY = SJ.[NAME_PAYS],
	SJ.[WAY_CALC],
	LINK_PAY = SJ.LINK_PAYS,
	SUMMA = SUM(SJ.SUMMA)			
FROM 
	dbo.S_J_C_Short SJ INNER JOIN dbo.group_pays(@varKSRefPay) T  ON SJ.link_PAYS=T.PAY_LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
WHERE 
	SJ.LINK_EMPL = @varKSlinkEmpl 
	AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_BEGIN ELSE SJ.DATE1 END) >=@varKSdDate1 
		AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_END ELSE SJ.DATE2 END) <=@varKSdDate2
	AND
	(@LINK_KBK = 0 OR SJ.LINK_VKR = @LINK_KBK)
	AND
   --в целом по сотруднику или для конкреного вида работы
	(@LINK_SOVM = -1 OR SJ.LINK_SOVM = @LINK_SOVM)
GROUP BY  
	SJ.LINK_PAYS, SJ.[CODE_PAYS], SJ.[NAME_PAYS], SJ.[WAY_CALC]

GO


GRANT EXECUTE ON dbo.[SD_BASE_SUM_PAY] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_86N_001_ANALYZE]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_86N_001_ANALYZE]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2011
   
   Вход: Созданные таблицы и заполненные:
               CREATE TABLE #tabHead ( DATE DATETIME, -- дата и время формирования информационнного пакета 
                                       ID UNIQUEIDENTIFIER) -- глобальный идентификатор пакета
         
               CREATE TABLE #tab001 ([CODE] VARCHAR(50), [VALUE] VARCHAR(8000)) -- общая информация об учреждении
               CREATE TABLE #tab001_OKVED ([CODE] VARCHAR(50), [NAME] VARCHAR(8000)) -- основыне ОКВЕД
               CREATE TABLE #tab001_OKVED_ADD ([CODE] VARCHAR(50), [NAME] VARCHAR(8000)) -- дополнительные ОКВЕД       
               CREATE TABLE #tab001_BRANCH (ID UNIQUEIDENTIFIER, [CODE] VARCHAR(50), [FULL_NAME] VARCHAR(8000), [NAME] VARCHAR(8000), [TYPE] VARCHAR(50))
        
   Выход: Сообщения об ошибках

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_86N_001_ANALYZE]
   @bCancel          BIT  = NULL OUTPUT
AS
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#tabExportLog') IS NULL -- значит не экспорт

BEGIN
   RETURN -1
END
DECLARE @tabErrorLog TABLE([ID] UNIQUEIDENTIFIER, [TXT] VARCHAR(8000),[ORDER] INT IDENTITY(1,1))

DECLARE @cStr VARCHAR(254), @region VARCHAR(250), @cProtokol VARCHAR(8000), @ID UNIQUEIDENTIFIER, @i INT, @j INT, @cWord VARCHAR(8000)
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))


IF OBJECT_ID('tempdb..#listForms') IS NOT NULL
AND EXISTS(SELECT * FROM REPORT_KBK WHERE CODE_FORM = '86n001_SendFiles') 
-- значит проверка КС
BEGIN
   --DECLARE @vcPath      VARCHAR(1000)
   --SELECT @vcPath = [Val_Str]
   --FROM dbo.report_options
   --WHERE [Razdel] = '86N' AND [Code] = 'dir'

  -- IF OBJECT_ID('tempdb..##files86n001') IS NULL
    --  BEGIN
  --       -- заполним таблицу списком файлов
  --      CREATE TABLE ##files86n001(ORD INT IDENTITY (1,1), [filename] VARCHAR(8000), INN VARCHAR(8000), RAZDEL VARCHAR(8000))         
		--BEGIN TRY
 
  -- 	       EXEC  dbo.[RO_GetFilesImagesInTables] @vcPath, 'true', '_', true,'','##files86n001tmp'
  --         INSERT ##files86n001 ([filename], INN, RAZDEL)
  --         SELECT [filename], dbo.RN_GETWORDNUM([filename], 2,'_'), dbo.RN_GETWORDNUM([filename], 3,'_') FROM ##files86n001tmp
  --         DROP TABLE ##files86n001tmp

		--END TRY 
  --      BEGIN CATCH
  --          PRINT 'error'
  --      END CATCH 
  --    END
        CREATE TABLE #files86n001(ORD INT IDENTITY (1,1), [filename] VARCHAR(8000), INN VARCHAR(8000), RAZDEL VARCHAR(8000))

        INSERT #files86n001 ([filename], inn,razdel)
        SELECT long_name, CODE_STR, ADD_INFO FROM REPORT_KBK WHERE CODE_FORM = '86n001_SendFiles' AND 
        CODE_STR IN   
        (SELECT [VALUE] FROM #tab001  T 
        WHERE T.CODE = '000004')
  
   	    INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан копии документов'
		FROM #tab001 A WHERE CODE = '000004' AND 
         NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE)

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Неверное расширение файла '+RTRIM(B.Filename)+'(требуется jpg, tif, pdf)'
		FROM #tab001 A   
        INNER JOIN #files86n001 B ON B.INN = A.VALUE
        WHERE RIGHT(RTRIM(Filename),3) NOT IN ('jpg','tif','pdf') 
        AND A.CODE = '000004'
        
		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Неверно указан раздел '+RTRIM(B.Filename)+'(возможные значения F,G,E,S,L,I,J,V,H,W,Z,N,Y)'
		FROM #tab001 A   
        INNER JOIN #files86n001 B ON B.INN = A.VALUE
        WHERE (dbo.RN_GETWORDNUM(filename, 3,'_') NOT IN ('F','G','E','S','L','I','J','V','H','W','Z','N','Y')
              AND LEFT(dbo.RN_GETWORDNUM(filename, 3,'_'),1)<>'Y')
              AND RIGHT(RTRIM(Filename),3) IN ('jpg','tif','pdf') 
        AND A.CODE = '000004'

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Неверно указан статус документа '+RTRIM(B.Filename)+'(возможные значения Q, R)'
		FROM #tab001 A   
        INNER JOIN #files86n001 B ON B.INN = A.VALUE
        WHERE LEFT(dbo.RN_GETWORDNUM(filename, 4,'_'),1) NOT IN ('Q','R') AND 
                     RIGHT(RTRIM(filename),3) IN ('jpg','tif','pdf')
                     AND  LEFT(dbo.RN_GETWORDNUM(filename, 3,'_'),1) IN ('F','G','E','S','L','I','J','V','H','W','Z','N','Y')
        AND A.CODE = '000004'

        --  «Учредительные документы». 
		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан-копии учредительных документов (раздел F)'
		FROM #tab001 A  WHERE A.CODE = '000004' AND  
        NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE
        AND razdel ='F')

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан-копии Свидетельства о государственной регистрации (раздел E)'
		FROM #tab001 A  WHERE A.CODE = '000004' AND 
        NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE
        AND razdel ='E') 

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан-копии Решения учредителя о назначении руководителя (раздел S)'
		FROM #tab001 A  WHERE A.CODE = '000004' AND 
        NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE
        AND razdel ='S') 

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан-копии Положения о филиалах, представительствах (раздел L)'
		FROM #tab001 A  WHERE A.CODE = '000004' AND
        NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE
        AND razdel ='L')
        AND EXISTS(SELECT * FROM #tab001_BRANCH) 

		INSERT @tabErrorLog ([ID], [TXT])
		SELECT DISTINCT [ID], 'Не найдены скан-копии Сведения о назначении членов наблюдательного совета (раздел I)'
		FROM #tab001 A  WHERE A.CODE = '000004' AND
        NOT EXISTS(SELECT * FROM #files86n001 B WHERE B.INN = A.VALUE
        AND razdel ='I')
        AND EXISTS(SELECT * FROM #tab001 T1 WHERE A.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '') 
        
END

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Контактный телефон" (стр.26)'
FROM #tab001 T
WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '126000' AND T1.[VALUE] <> '')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не верно заполнено поле "Контактный телефон" (стр.26) "'+[VALUE]+'" (Пример: Код страны-Код города-Номер 8-495-1234567, в номере должны быть только цифры и знак "-")'
FROM #tab001 T
WHERE [CODE] = '126000' AND [VALUE] <> '' AND 
(dbo.RN_GETWORDCOUNT([VALUE],'-') IN (0,1,2,5,6,7,8,9) OR ISNUMERIC(REPLACE([VALUE],'-',''))=0) 

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Код вида учреждения"   (таблица "Вид учреждения")'
FROM #tab001 T
WHERE T.[CODE] = '116001' AND T.[VALUE]='' 


INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Длина поля "Код вида учреждения" должна равняться 7 знакам  (таблица "Вид учреждения")'
FROM #tab001 T
WHERE T.[CODE] = '116001' AND LEN(T.[VALUE])<>7 AND T.[VALUE]<>'' 

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код вида учреждения" (стр.16)'
--FROM #tab001 T
--WHERE T.[CODE] = '116001' AND T.[VALUE] = ''
--   AND EXISTS(SELECT * FROM #tab001 T1 WHERE T.ID = T1.ID and T1.[CODE] = '116000' AND T1.[VALUE] <> '')


--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Код публично-правового образования, создавшего учреждение"(стр.6)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '106000' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Поле "Код публично-правового образования, создавшего учреждение" должен быть равен 11 знакам (стр.6)'
--FROM #tab001 T
--WHERE T.[CODE] = '106000' AND LEN(T.[VALUE])<>11  AND T.[VALUE]<>''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "Код по ОКАТО публично-правового образования, создавшего учреждение" должен быть равен 11 знакам (стр.6)'
FROM #tab001 T
WHERE T.[CODE] = '106002' AND LEN(T.[VALUE])<>11 AND T.[VALUE] <> ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "Код по ОКТМО публично-правового образования, создавшего учреждение" должен быть равен 8 знакам (стр.6)'
FROM #tab001 T
WHERE T.[CODE] = '106003' AND LEN(T.[VALUE])<>8 AND T.[VALUE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Фамилия"(стр.12.1)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112010' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Имя"(стр.12.2)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112020' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Отчество"(стр.12.3)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112030' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Наименование должности"(стр.12.4)'
--FROM #tab001 T
--WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '112040' AND T1.[VALUE] <> '')

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнена таблица "Обособленные структурные подразделения"(стр.13)'
--FROM #tab001 T 
--WHERE T.[CODE] = '113000' AND T.[VALUE] <> '' AND T.VALUE NOT IN ('нет','отсутствуют') AND NOT EXISTS(SELECT TOP 1 * FROM #tab001_BRANCH T1 WHERE T.[ID] = T1.[ID])

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Тип филиала" в таблице "Обособленные структурные подразделения"'
FROM #tab001_BRANCH
WHERE [TYPE] = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "Тип филиала" в таблице "Обособленные структурные подразделения" может принимать только значения: 01, 02, 03'
FROM #tab001_BRANCH
WHERE [TYPE] NOT IN ('01', '02', '03')  AND [TYPE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Поле "ИНН органа государственной власти(местного самоуправления), осуществляющего функции и полномочия учредителя" не может превышать 10 знаков (стр.7)'
--FROM #tab001 T
--WHERE T.[CODE] = '107000' AND LEN(T.[VALUE])>10 AND T.[VALUE] <> ''
  
--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "ИНН органа государственной власти(местного самоуправления), осуществляющего функции и полномочия учредителя" (стр.7)'
--FROM #tab001 T
--WHERE T.[CODE] = '107001' AND  T.[VALUE] <> ''
--      AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '107000' AND T1.[VALUE] <> '')

     
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Вид правового акта" (стр.11.1)'
FROM #tab001 T
WHERE (EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000005') AND T1.[VALUE] = '4')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000007') AND T1.[VALUE] = '10')
) 
 AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111010' AND T1.[VALUE] <> '')


INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Наименование правового акта" (стр.11.5)'
FROM #tab001 T
WHERE (EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000005') AND T1.[VALUE] = '4')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000007') AND T1.[VALUE] = '10'))
   AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111050' AND T1.[VALUE] <> '')


INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Номер правового акта" (стр.11.4)'
FROM #tab001 T
WHERE (EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000005') AND T1.[VALUE] = '4')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000007') AND T1.[VALUE] = '10'))
   AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111040' AND T1.[VALUE] <> '')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Дата правового акта" (стр.11.3)'
FROM #tab001 T
WHERE (EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000005') AND T1.[VALUE] = '4')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000007') AND T1.[VALUE] = '10'))
   AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111030' AND T1.[VALUE] <> '')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено наименование организации осуществляющией функции учредителя (стр.11.2)'
FROM #tab001 T WHERE CODE = '111021' AND VALUE = ''
AND (EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000005') AND T1.[VALUE] = '4')
OR EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('000007') AND T1.[VALUE] = '10'))



--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "ИНН органа, осуществляющего функции и полномочия учредителя, принявшего решение о назначении членов наблюдательного совета" (стр.11.2)'
--FROM #tab001 T
--WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
--   AND NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '111020' AND T1.[VALUE] <> '')
   
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "ИНН органа, осуществляющего функции и полномочия учредителя, принявшего решение о назначении членов наблюдательного совета" (стр.11.2) не может превышать 10 знаков'
FROM #tab001 T
WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
   AND T.[CODE] = '111020' AND LEN(T.[VALUE]) > 10

SET DATEFORMAT ymd   

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверная дата в поле "Дата правового акта (ГГГГ-ММ-ДД) "'+RTRIM(T.[VALUE])+' (стр.11.3)'  
FROM #tab001 T
WHERE EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] IN ('111010','111050','111040','111030','111020') AND T1.[VALUE] <> '')
   AND T.[CODE] = '111030' AND (RTRIM(T.[VALUE]) NOT LIKE '[12][09][019][0-9]-[01][0-9]-[0123][0-9]' OR ISDATE(T.[VALUE]) <> 1 )
   
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], '"Дата правового акта" '+RTRIM(T.[VALUE])+' (стр.11.3) больше текущей'
FROM
(SELECT ID, VALUE
FROM #tab001 T
WHERE T.[CODE] = '111030' AND ISDATE(T.[VALUE]) = 1 AND RTRIM(T.[VALUE]) LIKE '[12][09][019][0-9]-[01][0-9]-[0123][0-9]') T
WHERE CASE WHEN ISDATE(T.[VALUE]) = 1 THEN  CONVERT(DATETIME,T.[VALUE]) ELSE GETDATE() END > GETDATE()      


SET DATEFORMAT ydm

-- Вид деятельности
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнена таблица "17 - Основные ОКВЭД"'
FROM #tab001 T
WHERE NOT EXISTS(SELECT * FROM #tab001_OKVED T1 WHERE T.[ID] = T1.[ID])

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Код" в таблице "17 - Основные ОКВЭД"'
FROM #tab001_OKVED
WHERE [CODE] = ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Наименование вида деятельности по уставу" в таблице "17 - Основные ОКВЭД"'
--FROM #tab001_OKVED
--WHERE [NAMEU] = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено поле "Код" в таблице "18 - Иные ОКВЭД"'
FROM #tab001_OKVED_ADD
WHERE [CODE] = ''


DECLARE @cCodeRegion  VARCHAR(100)
SET @cCodeRegion = ''
--проверка regnum
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не найден код ОГС для организации: '+[VALUE]+' '+(SELECT TOP 1 RTRIM(VALUE) FROM #tab001 B WHERE A.ID = B.ID AND CODE = '000003')
FROM #tab001 A WHERE CODE = '000000' AND 
dbo.rn_get_ogs_code([VALUE],@cCodeRegion,0) = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не найден код ОГС для организации: '+[CODE]+' '+[FULL_NAME]+' таблица (Обособленные структурные подразделения)'
FROM #tab001_BRANCH WHERE  
dbo.rn_get_ogs_code(RTRIM(CODE),@cCodeRegion,0) = ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для организации учредителя с кодом: '+[VALUE]+' (стр.7)'
--FROM #tab001 WHERE dbo.rn_get_ogs_code(RTRIM(VALUE),@cCodeRegion,0) = ''
--and CODE = '107000' AND [VALUE] <> ''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не найден код ОГС для учредителя с кодом: '+[VALUE]+ ' (стр.11.2)'
--FROM #tab001 WHERE dbo.rn_get_ogs_code(RTRIM(VALUE),@cCodeRegion,0) = ''
--and CODE = '111020' AND [VALUE] <> ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не верный код публично-правового образования, создавшего учреждение '+RTRIM(VALUE)+'(стр.6)'
FROM #tab001 A WHERE CODE = '106000' AND VALUE <>''
and NOT EXISTS (SELECT * FROM REPORT_KBK WHERE Code_Form = 'SPR_86n_PPO' AND CODE = VALUE)

 INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнен Код публично-правового образования, создавшего учреждение(стр.6)'
FROM #tab001 A WHERE CODE = '106000' AND VALUE = ''
and (select dbo.rn_get_ppo_code([VALUE]) FROM #tab001 B WHERE A.ID = B.ID AND CODE = '106002') = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не найден код публично-правового образования, создавшего учреждение по ОКАТО(стр.6)'
FROM #tab001 A WHERE CODE = '106000' AND VALUE = ''
and (select dbo.rn_get_ppo_code([VALUE]) FROM #tab001 B WHERE A.ID = B.ID AND CODE = '106002') = ''
AND (select [VALUE] FROM #tab001 B WHERE A.ID = B.ID AND CODE = '106002') <> ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверная длина кода публично-правового образования, создавшего учреждение. (должно быть 11 символов)'
FROM #tab001 WHERE CODE = '106000' AND VALUE <> '' AND LEN(VALUE)<>11

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнен код ОКВЭД (таблица "Основные ОКВЭД-17")'
FROM #tab001_OKVED WHERE CODE = ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнен код дополнительных ОКВЭД (таблица "Иные ОКВЭД-18")'
FROM #tab001_OKVED_ADD WHERE CODE = ''


INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено наименование вида деятельности по уставу у ОКВЭД '+RTRIM(CODE)+ ' (таблица "Основные ОКВЭД-17")'
FROM #tab001_OKVED WHERE NAMEU=''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнено наименование вида деятельности по уставу у ОКВЭД ' +RTRIM(CODE)+' (таблица "Иные ОКВЭД-18")'
FROM #tab001_OKVED_ADD WHERE NAMEU=''

--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено наименование учредителя (стр. 7)'
--FROM #tab001 WHERE CODE = '107001' AND VALUE=''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "Идентификационный номер налогоплательщика (ИНН)" должено быть 10 знаков (стр.3)'
FROM #tab001 T
WHERE T.[CODE] = '103000' AND LEN(T.[VALUE])<>10 AND [VALUE] <> ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Поле "Код причины постановки на учет (К1Ш)" должено быть 9 знаков (стр.4)'
FROM #tab001 T
WHERE T.[CODE] = '104000' AND LEN(T.[VALUE])<>9 AND [VALUE] <> ''

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Не заполнен код "ОКТМО" (стр.20)'
FROM #tab001 T
WHERE NOT EXISTS(SELECT * FROM #tab001 T1 WHERE T.[ID] = T1.[ID] AND T1.[CODE] = '120000' AND T1.[VALUE] <> '')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Длина кода "ОКТМО" ('+RTRIM([VALUE])+') (стр.20) должна быть 8 знаков'
FROM #tab001 T
WHERE T.[CODE] = '120000' AND T.[VALUE] <> '' AND LEN(T.VALUE)<>8 

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Код "ОКТМО" '+RTRIM(T.[VALUE])+' не найден в справочнике (стр.20)'
FROM #tab001 T
WHERE T.[CODE] = '120000' AND T.[VALUE] <> '' AND 
NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM = 'SPR_86n_OKTMO' AND A.CODE =T.VALUE) 
AND EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM = 'SPR_86n_OKTMO')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Код "ОКТМО" '+RTRIM(T.[VALUE])+' не найден в справочнике (стр.6)'
FROM #tab001 T
WHERE T.[CODE] = '106003' AND T.[VALUE] <> '' AND 
NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM = 'SPR_86n_OKTMO' AND A.CODE =T.VALUE) 
AND EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM = 'SPR_86n_OKTMO')

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Длина кода "Код главы ГРБС по бюджетной классификации"  ('+RTRIM([VALUE])+') (стр.9) должна быть 3 знака'
FROM #tab001 T
WHERE [CODE] = '109000' AND T.[VALUE] <> '' AND LEN(T.VALUE)<>3

INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT [ID], 'Неверно введен E-MAIL: '+ RTRIM(T.[VALUE])+ '(стр.27)'
FROM #tab001 T
WHERE [CODE] = '127000' AND T.[VALUE] <> '' AND T.[VALUE] NOT LIKE '%@%'

--
--0	Не определено
--1	Казенные
--2	Бюджетные
--4	Автономные
INSERT @tabErrorLog ([ID], [TXT])
SELECT DISTINCT T.[ID], 'Не заполнен код главы ГРБС по бюджетной классификации (стр.9)'
FROM #tab001 T, #tab001 T1 
WHERE T.ID = T1.ID AND  
T.[CODE] = '109000' AND T1.[CODE] = '000005' AND T.[VALUE] = '' AND T1.[VALUE] = '1'

-- Учредитель
--
 

CREATE TABLE #tmpOGS([ID] UNIQUEIDENTIFIER, OGS VARCHAR(200))
INSERT #tmpOGS (ID, OGS)
SELECT ID, dbo.rn_get_ogs_code([VALUE],@cCodeRegion,0)
FROM #tab001 A WHERE CODE = '000000' AND 
dbo.rn_get_ogs_code([VALUE],@cCodeRegion,0) <>''  

IF @region IN ('Чебоксары')
BEGIN	
	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT [ID], 'Должно быть указано наименование органа, осуществляющего функции и полномочия учредителя (НЕОБХОДИМО внести изменения в ЕГРЮЛ в налоговых органах)'
	FROM #tmpOGS B
	WHERE NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_FOUNDER' AND A.LONG_NAME<>'' AND A.CODE = B.OGS)

	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT [ID], 'Должна быть указана должность, имя, фамилия, отчество руководителя (НЕОБХОДИМО внести изменения в ЕГРЮЛ в налоговых органах)'
	FROM #tmpOGS B
	WHERE NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_CHIEF' AND A.CODE = B.OGS)

	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT [ID], 'Должно быть указано наименование главного распорядителя бюджетных средств (НЕОБХОДИМО внести изменения в ЕГРЮЛ в налоговых органах)'
	FROM #tmpOGS B
	WHERE NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_RBS' AND A.CODE = B.OGS AND A.LONG_NAME<>'')
	AND EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_RBS' AND A.CODE = B.OGS)

	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT [ID], 'Должно быть указано наименование распорядителя бюджетных средств (НЕОБХОДИМО внести изменения в ЕГРЮЛ в налоговых органах)'
	FROM #tmpOGS B
	WHERE NOT EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_RBS' AND A.CODE = B.OGS AND A.ADD_INFO<>'')
	AND EXISTS(SELECT * FROM REPORT_KBK A WHERE A.CODE_FORM ='SPR_86n_OGS_RBS' AND A.CODE = B.OGS)
	-- тестим оквэды
	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT T.[ID], 'Организация не связана с указанным ОКВЭД '+RTRIM(T1.CODE)
	FROM #tab001  T 
	LEFT JOIN #tab001_OKVED T1 ON T.ID = T1.ID
	LEFT JOIN REPORT_KBK B ON B.CODE_FORM = 'SPR_86n_OGS' AND B.CODE_STR = T.VALUE
	LEFT JOIN REPORT_KBK C ON C.CODE_FORM = 'SPR_86n_OGS_OKVED' AND B.CODE = C.CODE
	AND C.code_str = T1.CODE
	WHERE T1.CODE<>'' AND C.Code_str IS NULL AND T.CODE = '000004'

	INSERT @tabErrorLog ([ID], [TXT])
	SELECT DISTINCT T.[ID], 'Организация не связана с указанным ОКВЭД '+RTRIM(T1.CODE)
	FROM #tab001  T 
	LEFT JOIN #tab001_OKVED_ADD T1 ON T.ID = T1.ID
	LEFT JOIN REPORT_KBK B ON B.CODE_FORM = 'SPR_86n_OGS' AND B.CODE_STR = T.VALUE
	LEFT JOIN REPORT_KBK C ON C.CODE_FORM = 'SPR_86n_OGS_OKVED' AND B.CODE = C.CODE
	AND C.code_str = T1.CODE
	WHERE T1.CODE<>'' AND C.Code_str IS NULL AND T.CODE = '000004'

-- ОКАТО публично-правового образования не соответствует уровню субъекта (ОКАТО должен удовлетворять маске – XX 000 000 000, где XX – это значащие цифры) 
-- смотрим на ОКФС = 13
	declare @cPPO varchar(1000), @cOKFS varchar(10)
	set @cPPO = ''
	set @cOKFS = ''

	select top 1 @cPPO = RTRIM(VALUE) FROM #tab001 B WHERE CODE = '106000'

	SELECT @cOKFS = RTRIM(C.ADD_INFO)
	FROM #tab001  T 
	LEFT JOIN REPORT_KBK B ON B.CODE_FORM = 'SPR_86n_OGS' AND B.CODE_STR = T.VALUE
	LEFT JOIN REPORT_KBK C ON C.CODE_FORM = 'SPR_86n_OGS_ADD_INFO' AND B.CODE = C.CODE
	WHERE T.CODE = '000004'

IF @cPPO = ''
	BEGIN
		select top 1 @cPPO = dbo.rn_get_ppo_code([VALUE]) FROM #tab001 B WHERE CODE = '106002'

		if @cPPO <>'' AND @cOKFS = '13' AND RIGHT(@cPPO, 9)<>'000000000'
			INSERT @tabErrorLog ([ID], [TXT])
			SELECT DISTINCT T.[ID], 'ОКАТО публично-правового образования ' + RTRIM(@cPPO) + ' стр6. не соответствует уровню субъекта (ОКАТО должен удовлетворять маске – XX 000 000 000, где XX – это значащие цифры)'
			FROM #tab001  T 
			LEFT JOIN REPORT_KBK B ON B.CODE_FORM = 'SPR_86n_OGS' AND B.CODE_STR = T.VALUE
			LEFT JOIN REPORT_KBK C ON C.CODE_FORM = 'SPR_86n_OGS_ADD_INFO' AND B.CODE = C.CODE
			WHERE T.CODE = '000004' 
	END
ELSE	
		if @cPPO <>'' AND @cOKFS = '13' AND RIGHT(@cPPO, 9)<>'000000000'
			INSERT @tabErrorLog ([ID], [TXT])
			SELECT DISTINCT T.[ID], 'Код публично-правового образования ' + RTRIM(@cPPO) + ' стр6. не соответствует уровню субъекта (ОКАТО должен удовлетворять маске – XX 000 000 000, где XX – это значащие цифры)'
			FROM #tab001  T 
			LEFT JOIN REPORT_KBK B ON B.CODE_FORM = 'SPR_86n_OGS' AND B.CODE_STR = T.VALUE
			LEFT JOIN REPORT_KBK C ON C.CODE_FORM = 'SPR_86n_OGS_ADD_INFO' AND B.CODE = C.CODE
			WHERE T.CODE = '000004' 
END


   
 --  -- дублирование
	INSERT @tabErrorLog ([ID], [TXT])
   SELECT ID, 'Код по ОКВЕД '+RTRIM(CODE)+' должен быть уникальным'
   FROM
    (SELECT ID, [CODE],COUNT(*) CNT FROM 
    (SELECT ID, [CODE] FROM #tab001_OKVED UNION ALL SELECT ID, [CODE] FROM #tab001_OKVED_ADD) OKVED
       GROUP BY ID,[CODE]
       HAVING COUNT(*)>1) A  


	INSERT @tabErrorLog ([ID], [TXT])
   SELECT ID, 'Наименование вида деятельности по ОКВЕД должно быть уникальным: '+LEFT(nameu,500)
   FROM
    (SELECT ID, [NAMEU],COUNT(*) CNT FROM 
    (SELECT ID, [NAMEU] FROM #tab001_OKVED UNION ALL SELECT ID, [NAMEU] FROM #tab001_OKVED_ADD) OKVED
       GROUP BY ID,[NAMEU]
       HAVING COUNT(*)>1) A  



-- проверка файлов


--INSERT @tabErrorLog ([ID], [TXT])
--SELECT DISTINCT [ID], 'Не заполнено поле "Наименование вида деятельности по уставу" в таблице "18 - Иные ОКВЭД"'
--FROM #tab001_OKVED_ADD
--WHERE [NAMEU] = ''

-- протокол выгрузки
IF OBJECT_ID('tempdb..#listForms') IS NOT NULL
-- значит проверка КС
BEGIN
  
   SELECT TOP 1 @ID = ID,  @cProtokol = LEFT(F.add_info,900)
   FROM #tab001 T
   INNER JOIN report_kbk F ON  F.code_form = 'spr_info_send_razdel_1' AND F.code = T.VALUE
   WHERE T.[CODE] = '000000' 
   AND ISNULL(F.code_str,'')<>'Отчет успешно загружен'  
     
   SET @i = 1
   SET @j = dbo.RN_GETWORDCOUNT(@cProtokol, CHAR(13))  
   IF @j>0 
      BEGIN
	   INSERT @tabErrorLog ([ID], [TXT])
	   SELECT @ID, ''

	   INSERT @tabErrorLog ([ID], [TXT])
	   SELECT @ID, 'Ошибки при передаче на сервер BUS.GOV.RU: '
      END
   WHILE @i<=@j
      BEGIN
       SET @cWord = RTRIM(LTRIM(dbo.rn_getwordnum(@cProtokol, @i, CHAR(13)+CHAR(10)))) 
       IF @cWord <>'' AND @cWord <> 'failure' 
   	      INSERT @tabErrorLog ([ID], [TXT])
	      SELECT @ID, @cWord

       SET @i = @i + 1
      END
    
END   


IF EXISTS(SELECT * 
          FROM @tabErrorLog)
BEGIN
   SET @bCancel = 1

   INSERT #tabExportLog([TXT])
   SELECT [TXT]
   FROM 
      (SELECT -1 [order], T.[ID], 'Для организации с кодом ' + RTRIM(T.[VALUE]) + ' ИНН('+ISNULL(T1.VALUE,'')+') ' + ISNULL((SELECT d.name FROM dbo.departments d WHERE d.budg = T.[VALUE] AND 1 = (SELECT COUNT(*) FROM dbo.departments d1 WHERE d1.budg = T.[VALUE])), '') AS [TXT]  
      from #tab001 T
      LEFT JOIN  #tab001 T1 ON T.ID = T1.ID AND T1.CODE = '000004'
      WHERE T.[CODE] = '000000'
         AND EXISTS(SELECT * FROM   @tabErrorLog T1 WHERE T.[ID] = T1.[ID])
      UNION ALL
      SELECT [ORDER], [ID], [TXT]
      FROM @tabErrorLog) A
   ORDER BY [ID], [ORDER]

   INSERT #tabExportLog([TXT])
   VALUES ('Выгрузка отменена. Устраните ошибки и повторите выгрузку.')
END
ELSE BEGIN
   SET @bCancel = 0
END
  

RETURN 0


GO
GRANT ALL ON dbo.[RO_EXPORT_FORM_86N_001_ANALYZE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))
*/



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_152]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_152]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_152]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn    INT,
        @lvcTXT      VARCHAR(8000),
        @lvcWord1    VARCHAR(8000),
        @lvcWord2    VARCHAR(8000),
        @lvcKBP      VARCHAR(50),
        @lvcVB       VARCHAR(50),
        @liORDER     INT,
        @liORDER_END INT,
        @i           INT,
        @vcUK        VARCHAR(50)
        

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS(SELECT * 
          FROM #IMPORT_TABLE 
          WHERE TXT LIKE 'FK|%TXKS120101|%')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_152_CKS] @lbSvodWEB,
                                                 @liRepeatRequest,
                                                 @tIsAppend,
                                                 @bDinamicRows,
                                                 @iLINK_SELF,
                                                 @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] = 'ВФ=0')
BEGIN   
   SELECT @vcUK = REPLACE([TXT],'УК=','')
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3) IN ('УК=')
         
   SELECT @lvcKBP = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
         LEFT([TXT],3) IN ('KБ=')

   SELECT @lvcVB = [TXT]
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')
   
   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],'')      
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503152'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
      FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
      WHERE [UK] = @vcUK and form_code = '0503152'
   END

   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_KBP_152'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_VB_152'
   END
            
   DELETE #IMPORT_TABLE
   WHERE LEFT([TXT],2)='* ' OR
         [ORDER] IN (1,2)

   SET IDENTITY_INSERT #IMPORT_TABLE ON
     
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ=622',-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'KБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)

   SET IDENTITY_INSERT #IMPORT_TABLE OFF
        
   SELECT @liORDER = [ORDER]
   FROM #IMPORT_TABLE
   WHERE [TXT]='РД=80'
   
   SELECT @liORDER_END = [ORDER]
   FROM #IMPORT_TABLE
   WHERE [TXT]='#'

   UPDATE #IMPORT_TABLE 
   SET [TXT]='РД=4' 
   WHERE [ORDER] = @liORDER

   UPDATE #IMPORT_TABLE 
   SET [TXT]=RTRIM([TXT]) + '|Примечание' 
   WHERE ([ORDER] > @liORDER) AND 
         ([ORDER] < @liORDER_END)
            
   UPDATE #IMPORT_TABLE 
   SET [TXT]='РД=5'
   WHERE [ORDER] = @liORDER_END   

   UPDATE #IMPORT_TABLE 
   SET [TXT]=RTRIM([TXT]) + '|Необязательный комментарий|' 
   WHERE [ORDER] = @liORDER_END + 1

   SELECT @lvcTXT = [TXT]
   FROM #IMPORT_TABLE 
   WHERE [ORDER] = @liORDER_END + 2

   IF @lvcTXT IS NOT NULL
   BEGIN
      SELECT @lvcWord2 = REVERSE(dbo.[RA_GETWORDNUM](REVERSE(@lvcTXT),1,' ')),
             @lvcWord1 = REVERSE(dbo.[RA_GETWORDNUM](REVERSE(@lvcTXT),2,' ')),
             @lvcTXT = REPLACE(REPLACE(@lvcTXT,@lvcWord1,''),@lvcWord2,'') + '|Начальник|' + 
                       @lvcWord1 + ' ' + @lvcWord2 
   END

   UPDATE #IMPORT_TABLE 
   SET [TXT]=@lvcTXT
   WHERE [ORDER] = @liORDER_END + 2

   SELECT @lvcTXT = [TXT]
   FROM #IMPORT_TABLE 
   WHERE [ORDER] = @liORDER_END + 3

   IF @lvcTXT IS NOT NULL
   BEGIN
      SELECT @lvcWord2 = REVERSE(dbo.[RA_GETWORDNUM](REVERSE(@lvcTXT),1,' ')),
             @lvcWord1 = REVERSE(dbo.[RA_GETWORDNUM](REVERSE(@lvcTXT),2,' ')),
             @lvcTXT = REPLACE(REPLACE(@lvcTXT,@lvcWord1,''),@lvcWord2,'') + '|Главный бухгалтер|' + 
                       @lvcWord1 + ' ' + @lvcWord2 
   END

   UPDATE #IMPORT_TABLE 
   SET [TXT]=@lvcTXT
   WHERE [ORDER] = @liORDER_END + 3

   
--select * from #IMPORT_TABLE 
--SELECT * FROM  #IMPORT_TABLE 
   
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_152] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/

GO




GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RB_PRINT_0503128G]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RB_PRINT_0503128G]

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[RB_PRINT_0503128G]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [RB_PRINT_0503128G]

GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RB_PRINT_0503128G]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS

if isnull(@WEB_excel, 0) <> 1
	select '' as col1

declare @varKSiParam int, @iLF int, @iLT INT -- 0 - без подитогов, 1 бит - подитоги по ЭКР, 2 бит - подитоги по ВР, 3 бит - подитоги по ЦСР, 4 бит - подитоги по подразделу, 5 бит - подитоги по раздеру, 6 бит - подитоги по администратору
DECLARE @varKSiNoItog int

select @iLF = Link_Form from report_saved_forms where link_saved_form = @LSF

set @varKSiParam = 0

if object_id('tempdb..#Param_Print') is NOT NULL
	select @varKSiParam = convert(int, Value) from #Param_Print where Param = 'Poditog'
   select @varKSiNoItog = convert(int, Value) from #Param_Print where Param = 'NoPoditog'

	create table #all (OrderTable tinyint, CODE varchar(50), COL1 varchar(8000), COL2 varchar(10), COL3 varchar(50), COL4 float, COL5 float, COL6 float, COL7 float, COL8 float, COL9 float, COL10 float, COL11 float, COL12 float, orders int IDENTITY(1,1))
	declare @table varchar(100), @RunStr varchar(8000)

------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
	create table #rash (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 float, Col15 float, Col16 varchar(50))

	insert #rash (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1

	select * into #rash_itog from #rash where 0 > 1

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 1, '00096000000000000000', '1. Бюджетные обязательства по расходам, всего:', '200', '00096000000000000000', sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12), sum(COL13), sum(COL14), sum(COL15)
	from #rash 
	where right(rtrim(CODE),17) = '96000000000000000'

---------------------------------------------
/*col1 - наименование показателя
col2 - код строки
col3 - РЗПР
col4 - ЦСР
col5 - ВР
col6 - ЭКР
col15 - Код = АДМ(3) + РЗПР(4) + ЦСР(7) + ВР(3) + ЭКР(3)
*/
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 2
-- добавляем подитоги
if @varKSiParam & 2 = 2 -- подитоги по целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,14) + '000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,14) + '000000', left(Col16,14) + '000000'
end

if @varKSiParam & 4 = 4 -- подитоги по подразделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,7) + '0000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col16,7) + '0000000000000'
end

if @varKSiParam & 8 = 8 -- подитоги по разделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,5) + '000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col16,5) + '000000000000000',left(col3,2) + '00'
end

if @varKSiParam & 16 = 16 -- подитоги по администратору
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,3) + '00000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col16,3) + '00000000000000000'
end

if @varKSiParam & 32 = 32 -- обнуляем подпрограмму в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,12) + '00000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,12) + '00000000', left(Col16,12) + '00000000'
end

if @varKSiParam & 64 = 64 -- обнуляем программу в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,10) + '0000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col16,10) + '0000000000'
end

select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 1

exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,8,7)=0000000#COL3=SUBSTRING(CODE,4,4)=0000#RN_VIEW_KBK_ADM_M=LEFT(CODE,3)=000', '#rash_itog', @varKScNameCode = 'CODE', @varKScNameName = 'COL1'
----------------------------------------------
IF isnull(@varKSiNoItog, 0) = 1
BEGIN
   insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 1, R.CODE, COL1, COL2, CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash R
   where right(rtrim(R.CODE),17) <> '96000000000000000' AND right(rtrim(R.CODE),3) NOT IN ('200','000','210','220','230','240','250','260','300','500','600') 
   order by R.Code
END
ELSE BEGIN     
   insert #rash
   select checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16
   from #rash_itog

   insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 1, R.CODE, COL1, COL2, CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash R
   where right(rtrim(R.CODE),17) <> '96000000000000000'
   order by R.Code
END 
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(1000), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 varchar(1000))

	insert #ist (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13)
	exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 2, '00090000000000000000', '2. Бюджетные обязательства по выплатам источников финансирования дефицита бюджета, всего:', '510', '00090000000000000000', sum(COL4), sum(COL5), sum(COL6), sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12)
	from #ist 
	where right(rtrim(COL3),17) = '90000000000000000'

IF isnull(@varKSiNoItog, 0) = 1
BEGIN
	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 2, CODE, COL1, COL2, LEFT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist
	where RIGHT(RTRIM(CODE),17) not in (select RIGHT(RTRIM(CD), 17) from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@iLF ,1) where link_table=@iLT )
	     or code like '%510%01000000000000000%' or code like '%520%01000000000000000%' or code like '%620%02000000000000000%' or code like '%520%02000000000000000%' or code like '%700%01000000000000000%' or code like '%710%01050000000000500%' or code like '%720%01050000000000600%' or code like '%82%000000000000000%'
END
ELSE BEGIN
	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 2, CODE, COL1, COL2, LEFT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist
	where right(rtrim(COL3),17) <> '90000000000000000'
END           

	create table #itog (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float)

	insert #itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12)
	exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1


	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 2,max(CODE), max(COL1), max(COL2), '              Х', sum(COL4), sum(COL5), sum(COL6), sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12)
	from #itog

	drop table #ist
	drop table #itog

	select * from #all order by OrderTable, left(code,3), orders
	drop table #all

	if isnull(@WEB_excel, 0) <> 1
		select cells as style,style as value from report_print_style where link_form=@iLF order by cells
GO


GRANT EXECUTE ON dbo.[RB_PRINT_0503128G] 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_WEB_USER_ADD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_USER_ADD]
GO

/*
© Кейсистемс (Keysystems), 2012
*/


CREATE                       procedure dbo.RO_WEB_USER_ADD
	@vcNAME        VARCHAR(250),
   @vcPASSWORD    VARCHAR(250),
   @bIS_DB_OWNER  BIT               -- 1 - админ
AS
  
DECLARE @P1 INT, @DEP INT, @BUDG INT, @ERROR INT 
DECLARE @TABLE TABLE  ( DEP_LINK INT, BUDG_LINK INT, LINK INT  )

EXEC @ERROR = X_USER_SAVE @P1 OUTPUT,@vcNAME,@vcNAME,1,0,0,0,NULL,''

IF @P1 IS NOT NULL
BEGIN
   EXEC SP_PASSWORD @new = @vcPASSWORD, @loginame = @vcNAME   
   EXEC X_ROLEMEMBER @P1,'Свод-КС',1
   
   IF @bIS_DB_OWNER = 1
   BEGIN
      EXEC X_ROLEMEMBER @P1,'db_owner',1
   END       
   ELSE
   BEGIN
      INSERT INTO [dbo].[user_form_access]
      (
         [SID],
         [dep_link],
         [access],
         [budg_link]
      )
      SELECT SUSER_SID(@vcNAME),
            link_report_org,
            1,
            link_report_budg
      FROM dbo.[RO_SVOD_TREE] rst
      WHERE NOT EXISTS(SELECT * FROM dbo.[user_form_access] ufa WHERE ufa.[SID] = SUSER_SID(@vcNAME) AND ufa.[dep_link] = rst.[LINK_REPORT_ORG] AND ufa.[budg_link] = rst.[LINK_REPORT_BUDG])
      GROUP BY rst.[LINK_REPORT_ORG], rst.[LINK_REPORT_BUDG]       
   END 

   IF NOT EXISTS(SELECT TOP 1 * FROM DBO.USER_DATE WHERE SID = SUSER_SID(@vcNAME)) AND  SUSER_SID(@vcNAME)  IS NOT NULL
       INSERT USER_DATE (SID, LINK_TASK, BEGINDATE,WORKDATE, ENDDATE,AUTO_PERIOD, AUTO_WORK, PERIOD_TYPE) 
       SELECT SUSER_SID(@vcNAME), LINK, GETDATE(), GETDATE(), GETDATE(), 0, 0, 2
       FROM DBO.S_OBJECTS WHERE CODE = 'OUTPUTS'
END
ELSE BEGIN
   RETURN @ERROR 
END    


RETURN 0

GO
GRANT ALL ON dbo.[RO_WEB_USER_ADD] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_12_PFR_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_12_PFR_PREPARE]

GO


CREATE PROCEDURE dbo.RSA_RSV_1_12_PFR_PREPARE 
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT, @TFOMS_KT int

DECLARE --Для выравнивания погрешности
	@C3S NUMERIC(18,6), @C4S NUMERIC(18,6), @C5S NUMERIC(18,6), @C6S NUMERIC(18,6),
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N NUMERIC(18,6)

select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF

set @TFOMS_KT = (select  (case when TFOMS_KT = 0 then 1 else TFOMS_KT end)  from dictionary_department where link = @DEP_LINK)

set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, FACE_GROUP TINYINT, I TINYINT, E TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 
	( CASE WHEN P.RESIDENT = 0 THEN 3 
		   WHEN YEAR(birthdate)<= 1966 THEN 1 
		   WHEN YEAR(birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP, 
	dbo.is_invalid(REF_PHYS_PERS,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH_BASE,@nYEAR))),
	F.ENVD	 
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) S
	inner join PERSON P on S.REF_PHYS_PERS = P.link
	inner join dbo.SAL_SFIN F on F.LINK = S.LINK_VKR
WHERE WAY_CALC not in (5)

--Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, FACE_GROUP, I, E)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, 
	( CASE WHEN P.RESIDENT = 0  THEN 3
		   WHEN YEAR(birthdate)<= 1966 THEN 1 
		   WHEN YEAR(birthdate)>= 1967 THEN 2 END) AS FACE_GROUP , 
	dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@nYEAR))),F.ENVD
FROM 
	DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join PERSON P on GT.PERS_LINK = P.link
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  not in (5)
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK
	
DELETE FROM #SPR_ESN
WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)

CREATE TABLE #RES2(CODE_STR VARCHAR(10), C1 NUMERIC(18,2), C2 NUMERIC(18,2),  C3 NUMERIC(18,2), C4 NUMERIC(18,2), C5 NUMERIC(18,2), C6 NUMERIC(18,2))
/*
для заполнения показателя "количество застрахованных лиц", указывается количество застрахованных лиц,
за которых должны быть представлены сведения индивидуального (персонифицированного) учета за отчетный период.
*/

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @C1_PERIOD_BEG DATETIME, @C1_PERIOD_END DATETIME
IF @nYEAR = 2010
	SELECT @C1_PERIOD_BEG = CASE WHEN @nMONTH3 <= 6 THEN '20100101' ELSE '20100701' END,
		   @C1_PERIOD_END = CASE WHEN @nMONTH3 <= 6 THEN '20100630' ELSE '20101231' END
ELSE
	SELECT @C1_PERIOD_BEG = @START_DATE,
		   @C1_PERIOD_END = @END_DATE
		   
--------------
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int
SELECT @NAvgCount = COUNT(pers_link) 
FROM
(
	SELECT DISTINCT E.pers_link
	FROM 
		dbo.EMPL E inner join dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
		left join dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
	WHERE 
		P.DATE_BEGIN <= @C1_PERIOD_END
		and
		coalesce(U.DIS_DATE,'20990101') >= @C1_PERIOD_BEG
		And 
		E.DEP_LINK = @DEP_LINK
	UNION 
	Select DISTINCT
		DFG.link
	FROM PERSON DFG inner join SALARY_REESTR_DGH DGH on DFG.link = DGH.PERS_LINK
	WHERE 
		DGH.DATE1 = (
			Select max(DATE1)  from SALARY_REESTR_DGH as DGH0 
					where DGH.PERS_LINK = DGH0.PERS_LINK AND DGH0.DEP_LINK = DGH.DEP_LINK
						AND
						(
							ISNULL(DATE1, '19000101') between  @C1_PERIOD_BEG and @C1_PERIOD_END
							or ISNULL(DATE2, '20990101') between @C1_PERIOD_BEG and @C1_PERIOD_END
						)
					)
		And 
		DGH.DEP_LINK = @DEP_LINK
) AS T		

--
INSERT INTO #RES2(CODE_STR, C1)
SELECT '1', ISNULL(@NAvgCount,0)

/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
--
UPDATE #RES2 SET C2 = ISNULL(@NAvgCount,0) WHERE CODE_STR = '1'
--Раздел 2. Расчет страховых взносов по тарифу, установленному для плательщика страховых взносов
Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 6)

--Фактическая база для договорников
SELECT 
	GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 6
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK 
GROUP BY 
	GT.PERS_LINK, MONTH(G.[DATE]), F.ENVD

SELECT  PERS_LINK, MONTH_BASE, SUMMA_BASE = SUM(SUMMA_BASE)
INTO #DGH_FAKT_BASE1
FROM #DGH_FAKT_BASE
GROUP BY PERS_LINK, MONTH_BASE

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

------
CREATE TABLE #CALCULATE_JURNAL (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2))
INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA)
SELECT LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL CJ
WHERE
	Year(period_begin) = @nYEAR 
	and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
GROUP BY
	LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL

------	у кого была инвалидность в заданном периоде
SELECT DISTINCT PERS_LINK 
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate

--Заготовка для #SALARY_SUM2
CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), FACE_GROUP TINYINT, SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT)
--Сотрудники

INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, FACE_GROUP, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV)
select
	E.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	(  CASE WHEN P1.RESIDENT = 0  THEN 3 
		   WHEN YEAR(p1.birthdate)<= 1966 THEN 1 
		   WHEN YEAR(p1.birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP,
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END
from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	INNER JOIN DBO.PERSON P1 ON P1.LINK = E.PERS_LINK
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	E.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, P1.RESIDENT, p1.birthdate

--Договрники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, FACE_GROUP, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV)
select
	CJ.PERS_LINK, 
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA) - ISNULL((SELECT SUM(B1.SUMMA_BASE) FROM #DGH_FAKT_BASE1 B1 WHERE B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)),0), --на которые не начисляются страховые взносы
	(  CASE WHEN P1.RESIDENT = 0  THEN 3 
		   WHEN YEAR(p1.birthdate)<= 1966 THEN 1 
		   WHEN YEAR(p1.birthdate)>= 1967 THEN 2 END ) AS FACE_GROUP,
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END)  - ISNULL((SELECT SUM(B.SUMMA_BASE) FROM #DGH_FAKT_BASE B WHERE B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1),0),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END	
from 
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	--База по договорникам в разрезе ЕНВД
--	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1
	--Общая база по договорникам
--	LEFT JOIN #DGH_FAKT_BASE1 B1 ON B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = CJ.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	CJ.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, P1.RESIDENT, p1.birthdate

--корректировка в соотвествие с тем, в каком есяце кто был инвалидом
UPDATE D SET 
	SUMMA_ALL_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL ELSE 0 END), 
	SUMMA_NO_I = (CASE WHEN EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO ELSE 0 END), 
	SUMMA_ALL_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_ALL_E ELSE 0 END), 
	SUMMA_NO_E = (CASE WHEN NOT EXISTS (SELECT * FROM dbo.PERS_INVALID I1 WHERE I1.PERS_LINK = D.PERS_LINK AND dbo.DateEndOfMonth(PERIOD_BEGIN) BETWEEN ISNULL(I1.DATE_BEGIN,PERIOD_BEGIN) AND  ISNULL(I1.DATE_END,dbo.DateEndOfMonth(PERIOD_BEGIN))) THEN SUMMA_NO_E ELSE 0 END)
FROM #SALARY_SUM_DATA D
WHERE INV = 1 --которые имели инвалидность в каком-то месяце периода	

--Данные о начисленной зарплате
SELECT MON = Month(PERIOD_BEGIN), 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)
INTO #SALARY_SUM2
FROM #SALARY_SUM_DATA
GROUP BY
	Month(PERIOD_BEGIN), FACE_GROUP

--
DROP TABLE #SALARY_SUM_DATA	

--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
-- с 2012 года расчет ведется по физ лицам , инвалидам и ЕНВД вместе 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '201', 
			 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 1

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '202', 

			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 2



INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '203', 

			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 3


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '211',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0)) 
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '212',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6  AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND FACE_GROUP = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 12),0))			
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))
----
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '213',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 12),0))			
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH3),0))

----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ 
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов, 
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы, 
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки, 
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '221',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '222',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
----
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '223',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
-----


--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

--  тариф, применяемый  свыше установленного предела величины базы (%)
-- по наемным рабочим
DECLARE 
	@PERCENT1 NUMERIC(18,2), @PERCENT2 NUMERIC(18,2), @PERCENT3 NUMERIC(18,2), 
	@PERCENT1_N NUMERIC(18,2), @PERCENT2_N NUMERIC(18,2), @PERCENT3_N NUMERIC(18,2),
	@PERCENT_OMS NUMERIC(18,2), @IPERCENT_OMS NUMERIC(18,2) 
	
SELECT @PERCENT1 = S.PERCENT1,
	   @PERCENT2 = S.PERCENT2,
	   @PERCENT3 = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @PERCENT1 = ISNULL(@PERCENT1,0)	
SET @PERCENT2 = ISNULL(@PERCENT2,0)
SET @PERCENT3 = ISNULL(@PERCENT3,0)

SELECT @PERCENT1_N = S.PERCENT1,
	   @PERCENT2_N = S.PERCENT2,
	   @PERCENT3_N = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 7 
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 7 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT3 > 0
	
SET @PERCENT1_N = ISNULL(@PERCENT1_N,0)	
SET @PERCENT2_N = ISNULL(@PERCENT2_N,0)
SET @PERCENT3_N = ISNULL(@PERCENT3_N,0)

--
SELECT @PERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

--
SELECT @IPERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0	

SET @PERCENT_OMS = ISNULL(@PERCENT_OMS,0)	
SET @IPERCENT_OMS = ISNULL(@IPERCENT_OMS,0)

-- по инвалидам
   --- страховая часть 
DECLARE @IPERCENT1 NUMERIC(28,2), @IPERCENT2 NUMERIC(28,2), @IPERCENT3 NUMERIC(28,2)  
SELECT @IPERCENT1 = S.PERCENT1,
	   @IPERCENT2 = S.PERCENT2,
	   @IPERCENT3 = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERCENT1 = ISNULL(@IPERCENT1,0)
SET @IPERCENT2 = ISNULL(@IPERCENT2,0)
SET @IPERCENT3 = ISNULL(@IPERCENT3,0)
	
	--- накопительная часть 
DECLARE @IPERCENT1_N NUMERIC(28,2), @IPERCENT2_N NUMERIC(28,2), @IPERCENT3_N NUMERIC(28,2)  
SELECT @IPERCENT1_N = S.PERCENT1,
	   @IPERCENT2_N = S.PERCENT2,
	   @IPERCENT3_N = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 7 
WHERE
	predel = @LIMIT
	and tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 7 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	(S.PERCENT1 > 0 or  S.PERCENT2 > 0 or  S.PERCENT3 > 0)
SET @IPERCENT1_N = ISNULL(@IPERCENT1_N,0)
SET @IPERCENT2_N = ISNULL(@IPERCENT2_N,0)
SET @IPERCENT3_N = ISNULL(@IPERCENT3_N,0) 
-----



SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS, 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, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0

--1966 г.р. и старше
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '231',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))

--1967 г.р. и моложе
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '232',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = 12) ,0))										
	END,	
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))

-- иностранные граждане
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '233',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = 12) ,0))										
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE FACE_GROUP = 3 AND M = @nMONTH3) ,0))


--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '250',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))

---накопительная часть
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '251',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7  AND I = 1  ) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7  AND I = 1  AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1  AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1  AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1  AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1  AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 1  AND MONTH_BASE = @nMONTH3) ,0))	


DECLARE @PERC1 NUMERIC(28,2), @IPERC1 NUMERIC(28,2)
-- для рабочих
SELECT @PERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @PERC1 = ISNULL(@PERC1,0)	
-- для инвалидов
SELECT @IPERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERC1 = ISNULL(@IPERC1,0)	



--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '252',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2) ,0)) * @PERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0))) * @PERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH1) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0)) * @PERC1)/100	

update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '252' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '252' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '252' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '252' ))
 from #RES2 
 where code_str = '250'

-- Количество чел , чей лимит превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '260',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M <= @nMONTH3) ,0) 
	ELSE
		ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1) ,0) 
		+ ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2) ,0) 
		+ ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) ,0) 
	END,	
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) ,0) 	


----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '271', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '272',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))

---- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '273',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1M FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1M SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1M SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 1 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 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_ESN2M 
FROM 
	#SPR_ESN1M T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1M T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1M T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '274',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '276',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 1) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
IF ISNULL(@PERCENT3_N,0) > 0
BEGIN
	--Вычисление погрешности для накопительной части	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '222' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '232' THEN C3 ELSE 0 END)
				) * @PERCENT3_N/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '251')
			) / (@PERCENT3_N/100)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '222' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '232' THEN C4 ELSE 0 END)
				) * @PERCENT3_N/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '251')
			) / (@PERCENT3_N/100)	
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '222' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '232' THEN C5 ELSE 0 END)
				) * @PERCENT3_N/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '251')
			) / (@PERCENT3_N/100)			
		),
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '222' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '232' THEN C6 ELSE 0 END)
				) * @PERCENT3_N/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '251')
			) / (@PERCENT3_N/100)						
		)
	FROM #RES2
	WHERE
		CODE_STR IN ('202', '212', '222', '232')

	IF ISNULL(@PERCENT1,0) > 0
	BEGIN
		--Вычисление погрешности для страховой части	
		SELECT 
			@C3S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '201' THEN C3 ELSE 0 END)
						+(CASE WHEN CODE_STR = '203' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '211' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '213' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '221' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '231' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '233' THEN C3 ELSE 0 END)
					)) * @PERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6), (SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '222' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '232' THEN C3 ELSE 0 END)
					) - @C3N)) * @PERCENT3/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '250'))
				) / (@PERCENT1/100)	
			),

			@C4S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '201' THEN C4 ELSE 0 END)
						+(CASE WHEN CODE_STR = '203' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '211' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '213' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '221' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '231' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '233' THEN C4 ELSE 0 END)
					)) * @PERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6),(SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '222' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '232' THEN C4 ELSE 0 END)
					) - @C4N)) * @PERCENT3/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '250'))
				) / (@PERCENT1/100)	
			),
			
			@C5S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '201' THEN C5 ELSE 0 END)
						+(CASE WHEN CODE_STR = '203' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '211' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '213' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '221' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '231' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '233' THEN C5 ELSE 0 END)
					)) * @PERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6),(SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '222' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '232' THEN C5 ELSE 0 END)
					) - @C5N)) * @PERCENT3/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '250'))
				) / (@PERCENT1/100)	
			),		

			@C6S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '201' THEN C6 ELSE 0 END)
						+(CASE WHEN CODE_STR = '203' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '211' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '213' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '221' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '231' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '233' THEN C6 ELSE 0 END)
					)) * @PERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6), (SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '222' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '232' THEN C6 ELSE 0 END)
						) - @C6N)) * @PERCENT3/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '250'))
				) / (@PERCENT1/100)						
			)
		FROM #RES2
		WHERE
			CODE_STR IN ('201', '203', '211', '213', '221', '231', '233', '202', '212', '222', '232')

		---Корректируем необлагаемые суммы на копейки округления
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3S,0),
			C4 = C4 + ISNULL(@C4S,0),
			C5 = C5 + ISNULL(@C5S,0),
			C6 = C6 + ISNULL(@C6S,0)			 
		WHERE 
			CODE_STR = '211'
	
	END	

	UPDATE #RES2
	SET
		C3 = C3 + ISNULL(@C3N,0),
		C4 = C4 + ISNULL(@C4N,0),
		C5 = C5 + ISNULL(@C5N,0),
		C6 = C6 + ISNULL(@C6N,0)			 
	WHERE 
		CODE_STR = '212'

END		


IF ISNULL(@PERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '271' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '272' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '273' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '274' THEN C3 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '276')
			) / (@PERCENT_OMS/100)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '271' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '272' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '273' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '274' THEN C4 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '276')
			) / (@PERCENT_OMS/100)
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '271' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '272' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '273' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '274' THEN C5 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '276')
			) / (@PERCENT_OMS/100)
		),
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '271' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '272' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '273' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '274' THEN C6 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '276')
			) / (@PERCENT_OMS/100)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('271', '272', '273', '274')


	UPDATE #RES2
	SET
		C3 = C3 + ISNULL(@C3N,0),
		C4 = C4 + ISNULL(@C4N,0),
		C5 = C5 + ISNULL(@C5N,0),
		C6 = C6 + ISNULL(@C6N,0)			 
	WHERE 
		CODE_STR = '272'
END		

--->>>--->>>>>>>
	-----ПО ИНВАЛИДАМ 
--->>>--->>>>>>>
--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
-- с 2012 года расчет ведется по физ лицам , инвалидам и ЕНВД вместе 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2010', 
			 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 1

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '2020', 

			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 2

INSERT INTO #RES2(CODE_STR, C3,C4, C5, C6)
SELECT '2030', 

			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END)) 
FROM #SALARY_SUM2		 
WHERE FACE_GROUP = 3

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2110',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH3),0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2120',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6  AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND FACE_GROUP = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = 12),0))			
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 2 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 2 AND MON = @nMONTH3),0))
----
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2130',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = 12),0))			
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE FACE_GROUP = 3 AND MON = @nMONTH3),0))

----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ 
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов, 
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы, 
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки, 
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2210',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2220',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
----
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2230',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
-----


SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1I SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1I SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS, 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, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1I T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1I T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


-- Суммы превышающие величину базы 
--1966 г.р. и старше
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2310',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 1 AND M = @nMONTH3) ,0))

--1967 г.р. и моложе
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2320',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = 12) ,0))										
	END,	
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 2 AND M = @nMONTH3) ,0))

-- иностранные граждане
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2330',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = 12) ,0))										
	END,
		
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE FACE_GROUP = 3 AND M = @nMONTH3) ,0))


--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2500',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))




------------ Продолжаем считать по инвалидам
---накопительная часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2510',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7  AND I = 2  ) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7  AND I = 2  AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 2  AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 2  AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 2  AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 2  AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 7 AND I = 2  AND MONTH_BASE = @nMONTH3) ,0))	


--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2520',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I) ,0)) * @IPERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0))) * @IPERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH1) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0)) * @IPERC1)/100	


update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '2520' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '2520' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '2520' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '2520' ))
 from #RES2 
 where code_str = '2500'

-- Количество чел , чей лимит превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2600',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M <= @nMONTH3) ,0) 
	ELSE
		ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1) ,0) 
		+ ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2) ,0) 
		+ ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) ,0) 
	END,	
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) ,0) 	


----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2710', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2		 


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2720',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))

---- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2730',

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1IM FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1IM SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1IM SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS, FACE_GROUP

SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2IM 
FROM 
	#SPR_ESN1IM T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1IM T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1IM T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2740',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2760',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 2) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ИНВАЛИДАМ
IF ISNULL(@IPERCENT3_N,0) > 0
BEGIN
	--Вычисление погрешности для накопительной части	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2220' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2320' THEN C3 ELSE 0 END)
				) * @IPERCENT3_N/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2510')
			) / (@IPERCENT3_N/100)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2220' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2320' THEN C4 ELSE 0 END)
				) * @IPERCENT3_N/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2510')
			) / (@IPERCENT3_N/100)	
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2220' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2320' THEN C5 ELSE 0 END)
				) * @IPERCENT3_N/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2510')
			) / (@IPERCENT3_N/100)			
		),
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 241 = 
					(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2220' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2320' THEN C6 ELSE 0 END)
				) * @IPERCENT3_N/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2510')
			) / (@IPERCENT3_N/100)						
		)
	FROM #RES2
	WHERE
		CODE_STR IN ('2020', '2120', '2220', '2320')

	IF ISNULL(@IPERCENT1,0) > 0
	BEGIN
		--Вычисление погрешности для страховой части	
		SELECT 
			@C3S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '2010' THEN C3 ELSE 0 END)
						+(CASE WHEN CODE_STR = '2030' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2110' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2130' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2210' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2310' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2330' THEN C3 ELSE 0 END)
					)) * @IPERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6), (SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2220' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2320' THEN C3 ELSE 0 END)
					) - @C3N)) * @IPERCENT3/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2500'))
				) / (@IPERCENT1/100)	
			),

			@C4S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '2010' THEN C4 ELSE 0 END)
						+(CASE WHEN CODE_STR = '2030' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2110' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2130' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2210' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2310' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2330' THEN C4 ELSE 0 END)
					)) * @IPERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6),(SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2220' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2320' THEN C4 ELSE 0 END)
					) - @C4N)) * @IPERCENT3/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2500'))
				) / (@IPERCENT1/100)	
			),
			
			@C5S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '2010' THEN C5 ELSE 0 END)
						+(CASE WHEN CODE_STR = '2030' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2110' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2130' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2210' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2310' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2330' THEN C5 ELSE 0 END)
					)) * @IPERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6),(SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2220' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2320' THEN C5 ELSE 0 END)
					) - @C5N)) * @IPERCENT3/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2500'))
				) / (@IPERCENT1/100)	
			),		

			@C6S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 240 = 
						(CASE WHEN CODE_STR = '2010' THEN C6 ELSE 0 END)
						+(CASE WHEN CODE_STR = '2030' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2110' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2130' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2210' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2310' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2330' THEN C6 ELSE 0 END)
					)) * @IPERCENT1/100
					+ 
					CONVERT(NUMERIC(18,6), (SUM( --Стр 241 = 
						(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2220' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '2320' THEN C6 ELSE 0 END)
						) - @C6N)) * @IPERCENT3/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2500'))
				) / (@IPERCENT1/100)						
			)
		FROM #RES2
		WHERE
			CODE_STR IN ('2010', '2030', '2110', '2130', '2210', '2310', '2330', '2020', '2120', '2220', '2320')

		---Корректируем необлагаемые суммы на копейки округления
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3S,0),
			C4 = C4 + ISNULL(@C4S,0),
			C5 = C5 + ISNULL(@C5S,0),
			C6 = C6 + ISNULL(@C6S,0)			 
		WHERE 
			CODE_STR = '2110'
	
	END	

	UPDATE #RES2
	SET
		C3 = C3 + ISNULL(@C3N,0),
		C4 = C4 + ISNULL(@C4N,0),
		C5 = C5 + ISNULL(@C5N,0),
		C6 = C6 + ISNULL(@C6N,0)			 
	WHERE 
		CODE_STR = '2120'

END		


IF ISNULL(@IPERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '2710' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2720' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2730' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2740' THEN C3 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2760')
			) / (@IPERCENT_OMS/100)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '2710' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2720' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2730' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2740' THEN C4 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2760')
			) / (@IPERCENT_OMS/100)
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '2710' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2720' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2730' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2740' THEN C5 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2760')
			) / (@IPERCENT_OMS/100)
		),
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 276 = 
					(CASE WHEN CODE_STR = '2710' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2720' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2730' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2740' THEN C6 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2760')
			) / (@IPERCENT_OMS/100)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('2710', '2720', '2730', '2740')


	UPDATE #RES2
	SET
		C3 = C3 + ISNULL(@C3N,0),
		C4 = C4 + ISNULL(@C4N,0),
		C5 = C5 + ISNULL(@C5N,0),
		C6 = C6 + ISNULL(@C6N,0)			 
	WHERE 
		CODE_STR = '2720'
END		


/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @Date1M datetime, @Date2M datetime, @Date3M datetime

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

if @nMONTH3 =3
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0101')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0201')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0301')
end
if @nMONTH3 =6
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0401')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0501')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0601')
end
if @nMONTH3 =9
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0701')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0801')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0901')
end
if @nMONTH3 =12
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1001')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1101')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1201')
end


/* Среднесписочная численность всего */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '331',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))	

/* Среднесписочная численность работников инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '332',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))	




/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferClear
EXEC dbo.BufferPush -116, @Table_Razd1

DROP TABLE #RES2







GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_12_PFR_PREPARE] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_DELETE_REPORT_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_DELETE_REPORT_KBK]
GO

/*
c Кейсистемс (Keysystems), 2006
*/
--сохранение REPORT_KBK
CREATE        PROCEDURE dbo.RN_DELETE_REPORT_KBK
	@iLINK	int =null
AS

declare @tmp table(link int)	
declare @icount int,@link_parent int
select @link_parent=link_self from REPORT_KBK where link=@iLink
insert @tmp (link) values (@iLink)
set @iCount=0
while @iCount<(select count(*) from @tmp)
begin
   select @iCount=count(*) from @tmp
   insert @tmp (link)         
     select link from REPORT_KBK A where A.Link_Self in (select link from @tmp) and not exists(select * from @tmp B where A.link=B.link)
end

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT 3000 -- Время ожидания разблокировки ресурсов 3 сек.

BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.


--DELETE FROM REPORT_KBK where Link=

 
DECLARE @liRowCount   INT, -- Число обработанных строк.
        @liError      INT  -- Код ошибки.
   -- Сохранение количества обработанных строк и кода ошибки. 
   SELECT @liRowCount = @@ROWCOUNT, 
          @liError    = @@ERROR

   delete from REPORT_KBK where link in (select link from @tmp)     
   -- Восстановление точки сохранения при ошибке.
  IF @liError <> 0 BEGIN
    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
    RETURN 7 -- Возврат кода ошибки.
  END

  UPDATE REPORT_KBK 
  SET childrens=case when exists(select * from REPORT_KBK A where A.link_self=REPORT_KBK.link) then 0 else 1 end
  WHERE link=@Link_parent
  
  DELETE dbo.report_kbk_cashe WHERE link_up IN (select link from @tmp)     

 
COMMIT TRANSACTION -- Фиксация транзакции.
RETURN 0 -- Ошибок нет.




GO
GRANT ALL ON dbo.[RN_DELETE_REPORT_KBK] 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].[RO_WEB_SAVE_FORMRRO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_SAVE_FORMRRO]
GO






CREATE         PROCEDURE dbo.[RO_WEB_SAVE_FORMRRO]
	@iLinkSF	int output,
	@bExcess tinyint = 0 output,	-- FOR WEB only
	@cText	varchar(50) = '' output,	-- FOR WEB only
	@RepeatRequest	int = NULL	-- повторный запуск
AS

declare @doc int, @LinkTable int, @orderTable tinyint, @orderRow int, @LinkCol int, @LSF int, @DocCode varchar(20), @cStrExec varchar(8000), @cReturnString varchar(8000), @rzpr varchar(1000), @pnum varchar(10), @orderRow1 VARCHAR(50)
set @cText = 'Результат'
-- преобразуем табличку и проверим, а дальше все как обычно
if object_id('tempdb..#REP_TABLE_1') is NOT NULL
begin
	if exists(select top 1 * from #REP_TABLE_1)
	begin
		create table #Doc (Doc int, Link_Table int) -- сделано, т.к. не всегда эти поля есть
		insert #Doc execute ('select Doc, Link_Table from #REP_HEAD')
		select @doc = Doc, @LinkTable = Link_Table from #DOC
		drop table #Doc

		select @LSF = Link_Saved_Form from #REP_HEAD

		select @orderTable = orders from report_tables where Link_Table = @LinkTable
		select * into #REP_TABLE_TEMP from #REP_TABLE_1 where 0 > 1
		if @orderTable < 3 
		begin
			alter table #REP_TABLE_TEMP
			add nn int IDENTITY(0,1)

			insert #REP_TABLE_TEMP execute('select * from #REP_TABLE_1 where col7 is NULL')

			insert #REP_TABLE_TEMP execute('select * from #REP_TABLE_1 where col7 is NOT NULL')

			if @orderTable = 1 
			begin
				select @DocCode = Code, @pnum = pnum from RT_FORM_RRO_PNUM where link = @doc
				select @LinkCol = Link_Col from report_coloumns where Link_Table = @LinkTable and orders = 36
				set @orderRow = isnull(convert(int, (select max(Str_Val) from report_dinamics_all where Link_SF = @LSF and Link_Col = @LinkCol and CHARINDEX(left(@DocCode + '          ', 9), Code_Row) > 0)), -1)
            set @orderRow1 = (select min(Str_Val) from report_dinamics_all where Link_SF = @LSF and Link_Col = @LinkCol  AND SUBSTRING(code_row, 8,9) = @DocCode )
            
            IF NOT EXISTS (SELECT * FROM dbo.report_dinamics rd JOIN dbo.report_coloumns rc ON rc.[Link_Col] = rd.[Link_Col] WHERE rd.[Link_SF] = @LSF AND SUBSTRING(rd.code_row, 8,9) = @DocCode AND rc.[Link_Table] =@LinkTable AND RIGHT(RTRIM(rd.code_row),3) = '000' ) 
            BEGIN
				   set @cStrExec = 'update #REP_TABLE_TEMP
				   set col36 = ''000''
				   where col36 = ''' + @orderRow1 + ''''

				   execute(@cStrExec)
               
            END                          
	
				set @cStrExec = 'update #REP_TABLE_TEMP
				set col7 = pnum, col8 = short_name, col9 = P.code, col36 = RIGHT(''000'' + LTRIM(RTRIM(STR(nn + ' + STR(@orderRow) + ' + 1))),3), upd_cells_mask = ''111111111111111111111111111111111111111111111111''
				from RT_FORM_RRO_PNUM P
				where P.Link = ' + STR(@doc) + ' and col36 is NULL'

				execute(@cStrExec)
			end
			if @orderTable = 2
			begin
				select @DocCode = Code, @pnum = pnum from RT_FORM_RRO_PNUM2 where link = @doc
				select @LinkCol = Link_Col from report_coloumns where Link_Table = @LinkTable and orders = 48
				set @orderRow = isnull(convert(int, (select max(Str_Val) from report_dinamics_all where Link_SF = @LSF and Link_Col = @LinkCol and CHARINDEX(left(@DocCode + '          ', 9), Code_Row) > 0)), -1)
            set @orderRow1 = (select min(Str_Val) from report_dinamics_all where Link_SF = @LSF and Link_Col = @LinkCol  AND SUBSTRING(code_row, 8,9) = @DocCode )
            
            IF NOT EXISTS (SELECT * FROM dbo.report_dinamics rd JOIN dbo.report_coloumns rc ON rc.[Link_Col] = rd.[Link_Col] WHERE rd.[Link_SF] = @LSF AND SUBSTRING(rd.code_row, 8,9) = @DocCode AND rc.[Link_Table] =@LinkTable AND RIGHT(RTRIM(rd.code_row),3) = '000' ) 
            BEGIN
				   set @cStrExec = 'update #REP_TABLE_TEMP
				   set col48 = ''000''
				   where col48  = ''' + @orderRow1 + ''''


				   execute(@cStrExec)
               
            END                          

				set @cStrExec = 'update #REP_TABLE_TEMP
				set col7 = pnum, col8 = short_name, col9 = P.code, col48 = RIGHT(''000'' + LTRIM(RTRIM(STR(nn + ' + STR(@orderRow) + '+ 1))),3), upd_cells_mask = ''1111111111111111111111111111111111111111111111111''
				from RT_FORM_RRO_PNUM2 P
				where P.Link = ' + STR(@doc) + ' and col48 is NULL'

				execute(@cStrExec)

			end

			-- данные должны быть только в первой строке
			set @cStrExec = 'if exists(select top 1 * from #REP_TABLE_TEMP where col' + case when @orderTable = 1 then '36' else '48' end + ' <> ''000'') update #REP_TABLE_TEMP
			set COL1= c1, COL2 = c2, COL3 = c3, COL4 = c4, COL5 = c5, COL6 = c6
			from (select sum(COL1) as c1, sum(COL2) as c2, sum(COL3) as c3, sum(COL4) as c4, sum(COL5) as c5, sum(COL6) as c6 from #REP_TABLE_TEMP) A
			where col' + case when @orderTable = 1 then '36' else '48' end + ' = ''000''
			update #REP_TABLE_TEMP
			set COL1= 0, COL2 = 0, COL3 = 0, COL4 = 0, COL5 = 0, COL6 = 0
			where col' + case when @orderTable = 1 then '36' else '48' end + ' <> ''000'''

			execute(@cStrExec)

			-- уточнение, НПА нам тут не нужен, т.е. нужна только одна строчка
			if isnull(@pnum, '') = '' --(REPLACE(SUBSTRING(@DocCode + '0000000', 8, 2), ' ', '0') <> '00' and @orderTable = 1) or (len(@DocCode)<9 and @orderTable = 2)
			begin
				set @cStrExec = 'delete #REP_TABLE_TEMP where col' + case when @orderTable = 1 then '36' else '48' end + '<>''000'' and del = 0
				update #REP_TABLE_TEMP
				set COL10=NULL,COL11=NULL,COL12=NULL,COL13=NULL,COL14=NULL,COL15=NULL,COL16=NULL,COL17=NULL,COL18=NULL,COL19=NULL,COL20=NULL,COL21=NULL,COL22=NULL,COL23=NULL,COL24=NULL,COL25=NULL,COL26=NULL,COL27=NULL,COL28=NULL,COL29=NULL,COL30=NULL,COL31=NULL,COL32=NULL,COL33=NULL,COL34=NULL,COL35=NULL'+
				case when @orderTable = 1 then '' else ',COL36=NULL,COL37=NULL,COL38=NULL,COL39=NULL,COL40=NULL,COL41=NULL,COL42=NULL,COL43=NULL,COL44=NULL,COL45=NULL,COL46=NULL,COL47=NULL' end
				execute(@cStrExec)		
			end
			else begin
				if exists(select top 1 * from #REP_TABLE_TEMP where dbo.ro_web_rro_check_rzpr(col10) <> 0)
				begin
					set @bExcess = 1
					select 'Неправильно заполнено поле <I> КБК(РзПр) </I>' as res
					return 0
				end
			end

			drop table #REP_TABLE_1
			select * into #REP_TABLE_1 from #REP_TABLE_TEMP
			set @orderTable = @orderTable - 1
			delete #REP_TABLE_TEMP where del = 1
			exec dbo.RT_RRO_CHECK_NPA_DUBLICATE_ON_SAVE @cReturnString output, '#REP_TABLE_TEMP', @orderTable
			drop table #REP_TABLE_TEMP
			if isnull(@cReturnString, '') <> ''
			begin
				set @bExcess = 1
				select @cReturnString as Res
				return -1
			end
		end
		else begin -- служебная информация
			create table #RRO3 (code varchar(50), COL1 varchar(8000), COL2 varchar(8000))
			insert #RRO3
			select Code, RTRIM(COL1), isnull(RTRIM(COL2),'') from #REP_TABLE_1
			exec dbo.[ro_check_rro3] @cReturnString output
			if isnull(@cReturnString, '') <> ''
			begin
				set @bExcess = 1
				select REPLACE(@cReturnString, CHAR(13), '<br>') as Res
				return -1
			end
		end
	end
		
end

exec dbo.[RN_WEB_SAVE_TABLES_CELLS] @iLinkSF output, @bExcess output, @cText output, @RepeatRequest



GO
GRANT ALL ON dbo.[RO_WEB_SAVE_FORMRRO] 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.[RO_KS_DETAIL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RO_KS_DETAIL]

GO


/*******************************************************************************

	c Кейсистемс (Keysystems), 2010
	Анализ ячейки, как она досчитывается, в какие КС она входит

*******************************************************************************/
CREATE PROCEDURE [dbo].[RO_KS_DETAIL] 
	@varKSiLSF		INT,
	@varKSiLT		INT = NULL,
	@varKSiOrderCol	INT = 0, -- внутренний порядок
	@varKScCodeRow	varchar(50) = '',
	@varKSiType	tinyint = 0 -- 0 - вернуть правила к этой ячейки, 1 - досчет (из чего получилась ячейка), 2 - проверить КС для данной ячейки
AS

DECLARE @LF		int, @LT int,
		@tmpStr		varchar(8000),
		@LC			int,
		@CodeForm	varchar(30),
		@orderCol	tinyint,
		@LinkRow	int,
		@round		tinyint

set @round = 4

create table #t_Col (Link_Col int primary key, Name varchar(254), Link_Table int, Val_Len int, Col_Type tinyint, OrderCol int, cOrderCol varchar(10))
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_Result (Link_Rule int, CodeRow varchar(50), orderCol tinyint)
create table #t_Rules_region (Link_Rule int, orderRule int)
	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(50), 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_Rows_Static(Link_Row int primary key, Code varchar(50), Link_Table int, orders int, Dop_Col varchar(1000))
create table #report_dinamics(Link_SF int, Code_Row varchar(50), 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(50), summa float)
create table #t_Tables (Link_Table int, orders tinyint, Name varchar(254), Val_Type tinyint, Dop_Col int)

------------------------------------------------------------------------------------------
-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА

select @LF = RSF.Link_Form, 
		@CodeForm	= RF.Code
from report_saved_forms RSF join report_forms RF on RSF.Link_Form = RF.Link_Form and RSF.link_saved_form = @varKSiLSF

if @varKSiLT is NULL or isnull(@varKSiOrderCol,0) = 0
begin
	insert #t_Col (Link_Col, Name, Link_Table, Val_Len, Col_Type, OrderCol, cOrderCol)
	select Link_Col, RC.Name, RC.Link_Table, Val_len, Col_Type, RC.orders, '№' + LTRIM(STR(Export_Order))
	from report_coloumns RC join report_tables RT on RC.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF

	insert #t_Rows_Static(Link_Row, Code, Link_Table, orders)
	select Link_Row, Code, RR.Link_Table, RR.orders
	from i_report_rows RR join report_tables RT on RR.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF and RT.Val_Type = 0

	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, round(RD.float_val,@round), RD.str_val, C.Link_Table
	from report_dinamics_all RD (NOLOCK) inner join #t_Col C on RD.Link_Col = C.Link_Col
	where RD.Link_SF = @varKSiLSF --and  float_val <> 0 
   
   insert #t_Tables (Link_Table, orders, Name, Val_Type, Dop_Col)
	select Link_Table, orders, Name, Val_Type, (select top 1 Link_Col from report_coloumns RC where RT.Link_Table = RC.Link_Table and IsEdited = 0 and RT.Link_Code_Col <> RC.Link_Col and RC.Val_len < 50 and Col_type = 1)
	from report_tables RT 
	where Link_Form = @LF 
   
end
else
begin
	insert #t_Col (Link_Col, RC.Name, RC.Link_Table, Val_Len, Col_Type, OrderCol, cOrderCol)
	select Link_Col, Name, Link_Table, Val_len, Col_Type, orders, '№' + LTRIM(STR(Export_Order))
	from report_coloumns where link_table = @varKSiLT and (orders = @varKSiOrderCol or isnull(@varKSiOrderCol, 0) = 0)
   
   insert #t_Tables (Link_Table, orders, Name, Val_Type, Dop_Col)
	select Link_Table, orders, Name, Val_Type, (select top 1 Link_Col from report_coloumns RC where RT.Link_Table = RC.Link_Table and IsEdited = 0 and RT.Link_Code_Col <> RC.Link_Col and RC.Val_len < 50 and Col_type = 1)
	from report_tables RT 
	where link_table = @varKSiLT   

	if not exists(select top 1 * from #t_Col)
		return

	if @varKScCodeRow <> ''
	begin
		select @LinkRow = Link_Row
		from dbo.i_report_rows
		where Link_Table = @varKSiLT and Code =  @varKScCodeRow

		insert #t_Rows_Static(Link_Row, Code, Link_Table, orders)
		select Link_Row, Code, RR.Link_Table, RR.orders
		from i_report_rows RR join report_tables RT on RR.Link_Table = RT.Link_Table
		where RT.Link_Form = @LF and RT.Val_Type = 0

		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, round(RD.float_val,@round), RD.str_val, C.Link_Table
		from report_dinamics_all RD (NOLOCK) inner join #t_Col C on RD.Link_Col = C.Link_Col
		where RD.Link_SF = @varKSiLSF --and  float_val <> 0 
	end
END


insert #t_summa (lsf, link_col, link_row, code, summa)
select RS.link_saved_form, RS.link_col, RS.link_row, R.code, round(RS.summa, @round)
from (select * from report_summa_all (NOLOCK) where Link_Saved_Form = @varKSiLSF) RS inner join #t_Rows_Static R on RS.Link_Row = R.Link_Row

---------------------------------------------------------------------
----- ПОЛУЧАЕМ КС
insert #t_Rules_region exec dbo.[I_CONTROL_RULES_LIST] @varKSiLSF, 0


if @varKSiType = 1 -- нам нужен только досчет этой ячейки
begin
	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(REPLACE(cols,' ', ''),'-',''), [rows], Str_Rule, Comment, Ru.OrderRule, IsDoschet
	from report_control_rules Ru  (NOLOCK) inner join #t_Rules_region R on Ru.Link_Rule = R.Link_Rule
		join report_control_rows Ro on R.Link_Rule = Ro.Link_Rule and Ro.part = 0
	where isDoschet&1=1 and Ro.Link_Table = @varKSiLT
			and (Link_Col in (select Link_Col from #t_Col) or (Link_Col is NULL and (exists(select top 1 * from #t_Col where CHARINDEX(','+LTRIM(RTRIM(STR(orderCol)))+',', ',' + replace(replace(cols,'-',''),' ', '') + ',') > 0) or Cols = '')))
			and (@varKScCodeRow = '' or (isnull(Ro.Link_Row, 0) = isnull(@LinkRow, 0) and @LinkRow is NOT NULL) or Ro.Code_Row = @varKScCodeRow or (Link_Row is NULL and Code_Row = '' and Val_Type in (0,3))or Val_Type = 4)

	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], cOrderTable, cOrderCol, [property])
	select Ro.Link_Rule, 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
end
else begin-- нам нужны все правила, в которые попадает данная ячейка
	insert #t_Rules (Link_Rule, Calc_orders, algorithm, [sign_sr], cols, [rows], Str_Rule, Comment, OrderRule, IsDoschet) 
	select distinct Ru.Link_Rule, Ru.Calc_orders, algorithm, sign_sr, REPLACE(cols,' ', ''), [rows], Str_Rule, Comment, Ru.OrderRule, IsDoschet
	from report_control_rules Ru  (NOLOCK) inner join #t_Rules_region R on Ru.Link_Rule = R.Link_Rule
		join report_control_rows Ro on R.Link_Rule = Ro.Link_Rule 
	where   Ro.Link_Table = @varKSiLT and (Link_Col in (select Link_Col from #t_Col) or (Link_Col is NULL and (exists(select top 1 * from #t_Col where CHARINDEX(','+LTRIM(RTRIM(STR(orderCol)))+',', ',' + cols + ',') > 0) or Cols = '')))
			and (@varKScCodeRow = '' or (isnull(Ro.Link_Row, 0) = isnull(@LinkRow, 0) and @LinkRow is NOT NULL) or Ro.Code_Row = @varKScCodeRow or (Link_Row is NULL and Code_Row = '' and Val_Type in (0,3)) or Val_Type = 4)


	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], cOrderTable, cOrderCol, [property])
	select Ro.Link_Rule, 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
end


update #t_KS set algorithm = 0 where algorithm = 4


if @varKSiType = 1
	exec dbo.RO_RAZMNOJ_KS_INSIDE 1
else
	exec dbo.RO_RAZMNOJ_KS_INSIDE 0

---------------------------------------------------------------------
-- ВОЗВРАЩАЕМ ПРАВИЛА ОТНОСЯЩИЕСЯ К ЭТОЙ ЯЧЕЙКИ
insert #t_Rules_Result (Link_Rule, CodeRow, orderCol)
select distinct Link_Rule, '', @varKSiOrderCol
from #t_KS
where algorithm = 2

insert #t_Rules_Result (Link_Rule, CodeRow, orderCol)
select distinct Link_Rule, @varKScCodeRow, 0
from #t_KS
where algorithm = 3

insert #t_Rules_Result (Link_Rule, CodeRow, orderCol)
select distinct Link_Rule, CodeRow, orderCol
from #t_KS
where (part = 0 or @varKSiType<> 1) and algorithm in (0, 1) and Link_COl in (select Link_Col from #t_Col) and ((isnull(Link_Row, 0) = isnull(@LinkRow, 0) and @linkRow is NOT NULL) or Code_Row = @varKScCodeRow)

insert #t_Rules_Result (Link_Rule, CodeRow, orderCol)
select -1, @varKScCodeRow, @varKSiOrderCol

if @varKSiType = 0
begin
	select * from #t_Rules_Result
	return
end

exec dbo.RO_CHECK_KS_INSIDE @LSF = @varKSiLSF, @varKSiNotAllRules = @varKSiType

GO


GRANT EXECUTE ON dbo.[RO_KS_DETAIL] 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.[RT_EXPORT_RRO_TREE]') AND  OBJECTPROPERTY([ID], N'IsProcedure') = 1)
   DROP PROCEDURE dbo.[RT_EXPORT_RRO_TREE]
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
-- Процедура экспорта групп междокументных правил и самих правил в них входящих.
CREATE PROCEDURE dbo.[RT_EXPORT_RRO_TREE]   
	@code_form varchar(4) = NULL,
	@period_val datetime
AS


IF len(@code_form)=0 RETURN -1


DECLARE @link INT
SELECT @link = link FROM dbo.[REPORT_KBK] rk WHERE code = @code_form AND code_form = 'HEADER'
CREATE TABLE #tabEXPORT ([ORDER] INT IDENTITY, [TEXT] VARCHAR(8000))

INSERT #tabEXPORT ([TEXT])
EXEC dbo.[RN_EXPORT_REPORT_KBK] @link, 1, 0

SELECT [TEXT]
FROM #tabEXPORT
ORDER BY [ORDER]

DROP TABLE #tabEXPORT
 
/*

DECLARE @tabEXPORT TABLE([ORDER] INT IDENTITY, [TEXT] VARCHAR(8000))

INSERT @tabEXPORT([TEXT]) VALUES('-- Сгенерировано х.п. RT_EXPORT_DICT_RRO. (' +  CONVERT(VARCHAR(100),GETDATE(),109) + ')')
INSERT @tabEXPORT([TEXT]) VALUES('-- Параметры выгрузки: ' + @code_form)
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('SET NOCOUNT               ON')
INSERT @tabEXPORT([TEXT]) VALUES('SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.')
INSERT @tabEXPORT([TEXT]) VALUES('SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.')
INSERT @tabEXPORT([TEXT]) VALUES('SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.')
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('BEGIN TRANSACTION         -- Начало новой транзакции.')
INSERT @tabEXPORT([TEXT]) VALUES('SAVE TRANSACTION SaveTran -- Создание точки сохранения.')
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('DELETE')
INSERT @tabEXPORT([TEXT]) VALUES('FROM dbo.REPORT_KBK')
INSERT @tabEXPORT([TEXT]) VALUES('WHERE code_form = '''+@code_form+'''')
INSERT @tabEXPORT([TEXT]) VALUES('')
---------------------------------------------------------------------------------------
-- select * from dbo.report_kbk where code_form = 'РРО'
declare @link int,
		@link2 int

declare @t table (link int, code varchar(250), link_self int)
insert into @t (link, code, link_self) select link, code, link_self from dbo.report_kbk where code_form = @code_form and (((@period_val >= begin_date or begin_date is NULL) and (@period_val <= end_date or end_date is NULL)) or @period_val is null) and link_self = 0

declare @t2 table (link int, code varchar(250), link_self int)

INSERT @tabEXPORT([TEXT])
select '
declare @iLink_Self int,
		@iLink_Self2 int
'

while exists(select * from @t) begin
	select top 1 @link = link from @t
	---------------------------------
	INSERT @tabEXPORT([TEXT])
	select
		replace('insert into dbo.report_kbk (code,link_self,code_form,childrens,[name],orders,long_name,begin_date,end_date) values ('''+code+''','+cast(link_self as varchar)+','''+code_form+''','+cast(childrens as varchar)+','''+rtrim([name])+''','+cast(orders as varchar)+','''+rtrim(Long_Name)+''','''+isnull(rtrim(convert(varchar,begin_date,112)),'<NUL>')+''','''+isnull(rtrim(convert(varchar,end_date,112)),'<NUL>')+''')','''<NUL>''','NULL')
	from dbo.report_kbk
	where link = @link

	INSERT @tabEXPORT([TEXT])
	select '
set @iLink_Self = @@IDENTITY
' 
	INSERT @tabEXPORT([TEXT])
	select
		replace('insert into dbo.report_kbk (code,link_self,code_form,childrens,[name],orders,long_name,begin_date,end_date) values ('''+code+''',@iLink_Self,'''+code_form+''','+cast(childrens as varchar)+','''+rtrim([name])+''','+cast(orders as varchar)+','''+rtrim(Long_Name)+''','''+isnull(rtrim(convert(varchar,begin_date,112)),'<NUL>')+''','''+isnull(rtrim(convert(varchar,end_date,112)),'<NUL>')+''')','''<NUL>''','NULL')
	from dbo.report_kbk
	where link_self = @link and Childrens = 1
	
	insert into @t2(link, code, link_self) select link, code, link_self from dbo.report_kbk where link_self = @link and Childrens = 0
	while exists(select * from @t2) begin
		select top 1 @link2 = link from @t2
		----------------------------------
		INSERT @tabEXPORT([TEXT])
		select
			replace('insert into dbo.report_kbk (code,link_self,code_form,childrens,[name],orders,long_name,begin_date,end_date) values ('''+code+''',@iLink_Self,'''+code_form+''','+cast(childrens as varchar)+','''+rtrim([name])+''','+cast(orders as varchar)+','''+rtrim(Long_Name)+''','''+isnull(rtrim(convert(varchar,begin_date,112)),'<NUL>')+''','''+isnull(rtrim(convert(varchar,end_date,112)),'<NUL>')+''')','''<NUL>''','NULL')
		from dbo.report_kbk
		where link = @link2
		INSERT @tabEXPORT([TEXT])
		select '
set @iLink_Self2 = @@IDENTITY
' 
		INSERT @tabEXPORT([TEXT])
		select
			replace('insert into dbo.report_kbk (code,link_self,code_form,childrens,[name],orders,long_name,begin_date,end_date) values ('''+code+''',@iLink_Self2,'''+code_form+''','+cast(childrens as varchar)+','''+rtrim([name])+''','+cast(orders as varchar)+','''+rtrim(Long_Name)+''','''+isnull(rtrim(convert(varchar,begin_date,112)),'<NUL>')+''','''+isnull(rtrim(convert(varchar,end_date,112)),'<NUL>')+''')','''<NUL>''','NULL')
		from dbo.report_kbk
		where link_self = @link2 and Childrens = 1
		----------------------------------
		delete from @t2 where link = @link2
	end


	---------------------------------
	delete from @t where link = @link
end

---------------------------------------------------------------------------------------
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('IF @@ERROR <> 0')
INSERT @tabEXPORT([TEXT]) VALUES('BEGIN')
INSERT @tabEXPORT([TEXT]) VALUES('   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.')
INSERT @tabEXPORT([TEXT]) VALUES('END')
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('COMMIT TRANSACTION -- Фиксация транзакции.')
INSERT @tabEXPORT([TEXT]) VALUES('GO')
INSERT @tabEXPORT([TEXT]) VALUES('')
INSERT @tabEXPORT([TEXT]) VALUES('exec EXEC dbo.[RO_KBK_CASHE_UPDATE] [@vcCodeForm] = ''РРО''')
INSERT @tabEXPORT([TEXT]) VALUES('EXEC dbo.[RO_KBK_CASHE_UPDATE] [@vcCodeForm] = ''РРО2''')
INSERT @tabEXPORT([TEXT]) VALUES('GO')
INSERT @tabEXPORT([TEXT]) VALUES('')


SELECT [TEXT]
FROM @tabEXPORT
ORDER BY [ORDER]
*/
RETURN 0

GO
GRANT EXECUTE ON dbo.[RT_EXPORT_RRO_TREE] 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].[web_sign_DocsList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[web_sign_DocsList]
GO


/*
Хранимка формирует из документа 1 строку с данными для ЭЦП
*/

CREATE   PROCEDURE dbo.web_sign_DocsList
	@cDocCode varchar(200), -- код документа
	@xmlLinks text, -- xml с линками
	@cTableLinks varchar(200) = '', -- название таблицы с линками если не передали в @xmlLinks
	@From bit = 0 -- 0 - с подписывания, 1 - С проверки
AS
begin


create table #docs(LSF int)
create table #result_sign (link_doc int, value varchar(8000), link int)
create table #result_text (link int, [text] text)

DECLARE @hDoc int
if (@xmlLinks is not null)
begin
	exec sp_xml_preparedocument @hDoc OUTPUT, @xmlLinks
	insert #docs (LSF)
	select link
	FROM OPENXML(@hDoc, 'Links/Link', 2)
	WITH (link int '@Link') 
	EXEC sp_xml_removedocument @hDoc
end
else

begin
	exec('insert #docs (LSF) select link from ' + @cTableLinks)
end

IF ltrim(rtrim(@cDocCode))= '' or isnull(@cDocCode,'')=''
begin
 return -1
end


-- Если линки документов отчетности
IF @cDocCode = 'REPORT_FORMS_LIST' or @cDocCode = 'REPORT_SVOD'
Begin
	insert #result_text
	select LSF, ''
	from #docs
	
	if object_id('tempdb..#tabExportLog') is not null begin  drop table #tabExportLog end create table #tabExportLog([TXT] VARCHAR(8000),[ORDER] INT IDENTITY(1,1))
	exec dbo.RO_EXPORT_REPORT '#docs',3


   IF @From = 0
   BEGIN 
      DELETE #result_sign
      WHERE VALUE LIKE '%ПО=Свод-КС%'
      
      DELETE #result_sign
      WHERE LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'КФ=%' AND LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'РД=%'))
      
   END
--   ELSE 
--   BEGIN
--      UPDATE #result_sign
--      SET VALUE = (SELECT TOP 1 SUBSTRING(convert(varchar(8000), text_for_sign),CHARINDEX('ПО=Свод-КС',convert(varchar(8000), text_for_sign)), 21)   
--                   FROM  dbo.report_sign S WHERE S.[lsf] = #result_sign.link_doc AND CHARINDEX('ПО=Свод-КС',convert(varchar(8000), text_for_sign)) > 0)    
--      WHERE VALUE LIKE '%ПО=Свод-КС%'
--
--      UPDATE #result_sign
--      SET VALUE = (SELECT TOP 1 SUBSTRING(convert(varchar(8000), text_for_sign),1, CHARINDEX('КФ=',convert(varchar(8000), text_for_sign)) - 3)   
--                   FROM  dbo.report_sign S WHERE S.[lsf] = #result_sign.link_doc AND CHARINDEX('ВФ=',convert(varchar(8000), text_for_sign)) > 0)    
--      WHERE LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'КФ=%' AND LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'РД=%'))
--
--      DELETE #result_sign
--      WHERE link <> (SELECT MAX(link)
--                     FROM #result_sign
--                     WHERE LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'КФ=%' AND LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'РД=%')))
--            AND  LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'КФ=%' AND LINK < (SELECT MIN(LINK) FROM #result_sign WHERE VALUE LIKE 'РД=%'))                                    
--            
--      DELETE #result_sign
--      WHERE VALUE IS NULL
--          
--   END

	update #result_sign
	set value = value + CHAR(13) + CHAR(10)

	exec varchar2text
		@cTableSour ='#result_sign',
		@cValueSour ='value',
		@cKeySour ='link',
		@cKeyUpSour ='link_doc',
		
		@cTableDest ='#result_text',
		@cValueDest ='text',
		@cKeyDest ='link'


	
 End

	drop table #result_sign

	delete REPORT_SIGN_TXT
	where sid = suser_sid() and LSF in (select Link from #result_text)

	insert REPORT_SIGN_TXT (LSF, txt) -- для сохранения строки для подписи
	select link, [text]
	from #result_text

	if @From = 0
		select * from #result_text
	drop table #result_text

RETURN 0

END

GO

GRANT ALL ON dbo.[web_sign_DocsList] 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.[RO_EXPORT_FORM_625_2011]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_625_2011]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_625_2011]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла	
	@iMODE	         INT=1,                  -- Формат: 1-внутренний, 2-минфиновский
	@vcFILE_NAME_ARH  VARCHAR(100)='' OUTPUT
AS

SET NOCOUNT ON

DECLARE @i		 INT,
		@lvcKBP VARCHAR(500),
		@lvcVB	 VARCHAR(500),
		@vcNEW_FILE_NAME	   VARCHAR(100),
      @vcVersion	VARCHAR(50)
      
      SELECT @vcVersion = [VERSION] FROM #tabExportOutput

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM = @iLINK_SAVED_FORM,
                                   @vcFILE_NAME = @vcFILE_NAME OUTPUT,
                                   @vcFILE_NAME_ARH = @vcFILE_NAME_ARH OUTPUT,
                                   @iMODE = @iMODE

IF @iMODE = 2
BEGIN

--   UPDATE #FileExportReport
--   SET [TXT] = dbo.[RA_GETWORDNUM]([TXT],1,'|') + '|' +
--			   dbo.[RA_GETWORDNUM]([TXT],2,'|') + '|' +
--			   dbo.[RA_GETWORDNUM]([TXT],3,'|') + '|' +
--               dbo.[RA_GETWORDNUM]([TXT],4,'|') + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],5,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],6,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],7,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],8,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],9,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],10,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],11,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],12,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],13,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],14,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],15,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],16,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],17,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],18,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],19,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],20,'|') AS NUMERIC(20,2)),0,0))) + '|'
--   WHERE [TXT] LIKE '%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%'
--
--   UPDATE #FileExportReport
--   SET [TXT] = dbo.[RA_GETWORDNUM]([TXT],1,'|') + '|' +
--			   dbo.[RA_GETWORDNUM]([TXT],2,'|') + '|' +
--			   dbo.[RA_GETWORDNUM]([TXT],3,'|') + '|' +
--               dbo.[RA_GETWORDNUM]([TXT],4,'|') + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],5,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],6,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],7,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],8,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],9,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],10,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],11,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],12,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],13,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],14,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],15,'|') AS NUMERIC(20,2)),0,0))) + '|' +
--               LTRIM(STR(ROUND(CAST(dbo.[RA_GETWORDNUM]([TXT],16,'|') AS NUMERIC(20,2)),0,0))) + '|'
--      WHERE [TXT] NOT LIKE '%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%'
--			and [TXT] LIKE '%|%|%|%|%|%|%|%|%|%|%|%|%|%|%|%'

   
   UPDATE #FileExportReport
   SET TXT = REPLACE(TXT, '0804|0015300|012', '0801|0015300|012')
   WHERE TXT LIKE '0804|0015300|012%'

   UPDATE #FileExportReport
   SET TXT = REPLACE(TXT, '0302|2020100|014|650', '0302|2025800|014|660')
   WHERE TXT LIKE '0302|2020100|014|650%'

   UPDATE #FileExportReport
   SET TXT = REPLACE(TXT, '0302|2020100|014|660', '0302|2026700|014|660')
   WHERE TXT LIKE '0302|2020100|014|660%'

	SELECT @lvcKBP = [VAL_STR]
	FROM dbo.[REPORT_OPTIONS]
	WHERE [RAZDEL] = 'FORM_625' AND
			[CODE] = 'EXPORT_KBP_625'

	SET @lvcKBP = ISNULL(@lvcKBP,'')

	IF LEN(@lvcKBP)>0
	BEGIN
		UPDATE #FileExportReport
		SET [TXT]='ИСТ='+RTRIM(@lvcKBP)
		WHERE [NameFile] = @vcFILE_NAME AND
			   [TXT] LIKE 'ИСТ=%'
	END

	SELECT @lvcVB = [VAL_STR]
	FROM dbo.[REPORT_OPTIONS]
	WHERE [RAZDEL] = 'FORM_625' AND
			[CODE] = 'EXPORT_VB_625'

	SET @lvcVB = ISNULL(@lvcVB,'')

	IF LEN(@lvcVB)>0
	BEGIN
		UPDATE #FileExportReport
		SET [TXT]='ВИД='+RTRIM(@lvcVB)
		WHERE [NameFile] = @vcFILE_NAME AND
			   [TXT] LIKE 'ВИД=%'

	END

	SELECT @vcNEW_FILE_NAME = RTRIM([B].[CODE]) + 'Y' + RTRIM(@vcVersion) + '.txt',
	        @vcFILE_NAME_ARH = RTRIM(@lvcVB) + '0' + RTRIM(@lvcKBP) + RIGHT(CONVERT(VARCHAR(100),[A].[BEGIN_DATE],104),1) + RTRIM(@vcVersion) + '.zip'
	FROM dbo.[REPORT_SAVED_FORMS] [A]
	JOIN dbo.[REPORT_FORMS]       [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
	WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

   UPDATE #FileExportReport
   SET [NameFile] = @vcNEW_FILE_NAME,
       [NameFileArh] = @vcFILE_NAME_ARH
   WHERE [NameFile] = @vcFILE_NAME
	
END                                   


GO
GRANT ALL ON dbo.[RO_EXPORT_FORM_625_2011] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_125]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_125]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_125]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS

	if isnull(@WEB_excel, 0) <> 1
		select '' col1 
	declare  @atr varchar(254), @atr_value varchar(254)
	if YEAR((select begin_date from dbo.report_saved_forms where link_saved_form = @LSF)) > 2010
		set @atr = 'REPORTS_ATR_ACC_2011'
	else
		set @atr = 'REPORTS_ATR_ACC'
	set @atr_value = dbo.RN_GET_ATR_Value(@LSF, @atr)
	create table #all (ATR varchar(100), COL1 varchar(8000), COL2 varchar(8000), COL3 varchar(8000), COL4 varchar(8000), COL5 varchar(8000), COL6 float, COL7 float, COL8 varchar (8000), CODE varchar(50), DEL bit, ITOG int, orders int IDENTITY(1,1))
	create table #doh (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(8000), Col2 varchar(8000), Col3 varchar(8000), Col4 varchar(8000), Col5 varchar(8000), Col6 varchar(8000), Col7 float, Col8 float, col9 varchar(8000), col10 varchar(8000), col11 varchar(8000), col12 varchar(8000), atr varchar(250) )
	create table #rash (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(8000), Col2 varchar(8000), Col3 varchar(8000), Col4 varchar(8000), Col5 varchar(8000), Col6 varchar(8000), Col7 varchar(8000), Col8 varchar(8000), col9 float, col10 float, col11 varchar(8000), col12 varchar(8000), col13 varchar(8000), col14 varchar(8000), atr varchar(250) )
	create table #ist (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(8000), Col2 varchar(8000), Col3 varchar(8000), Col4 varchar(8000), Col5 varchar(8000), Col6 varchar(8000), Col7 float, Col8 float, col9 varchar(8000), col10 varchar(8000), col11 varchar(8000), col12 varchar(8000), atr varchar(250) )
	create table #itog (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(8000), Col2 varchar(8000), Col3 varchar(8000), Col4 varchar(8000), Col5 varchar(8000), Col6 float, Col7 float, col8 varchar(8000), col9 varchar(8000), atr varchar(250))

	insert #doh exec dbo.ro_get_all_atr_table @LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #rash exec dbo.ro_get_all_atr_table @LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #ist exec dbo.ro_get_all_atr_table @LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #itog exec dbo.ro_get_all_atr_table @LSF, 4, @bDeleteEmptyRows, @AtrInOnePage, @atr

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5+COL6,COL7,COL8,COL9,CODE, 0 as DEL, 0 from #doh ORDER BY 1,3,4,5,6

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5+COL6+COL7+COL8,COL9,COL10,COL11,CODE, 0 as DEL, 0 from #rash ORDER BY 1,3,4,5,6

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5+COL6,COL7,COL8,COL9,CODE, 0 as DEL, 0 from #ist ORDER BY 1,3,4,5,6
   
	if not exists(select top 1 * from #all)
		insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
		select atr, '', '', '', '', NULL, NULL, '', '', '', 0, 0
		from #itog 
		group by atr

	if not exists(select top 1 * from #all)
		insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
		select @atr_value, '', '', '', '', NULL, NULL, '', '', '', 0, 0

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, 'Итого:', 'X' AS COL2, 'X' AS COL3, 'X' AS COL4, 'X' AS COL5, max(COL6) , max(COL7), 'X' AS COL8, max(CODE) AS CODE, 0 as DEL, 1  
	from #itog WHERE RTRIM(LTRIM(CODE)) = 'Итого'
	group by atr

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, 'Итого:', 'X' AS COL2, 'X' AS COL3, 'X' AS COL4, 'X' AS COL5, 0 as COL6 , 0 as COL7, 'X' AS COL8, '' AS CODE, 0 as DEL, 1  
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RTRIM(LTRIM(A1.CODE)) = 'Итого')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	select atr, 'в том числе по', '', '', '', '', NULL, NULL, '', '', 0, 1
	from #all
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	SELECT atr, 'номеру (коду) счета:', COL2, COL3, COL4, COL5,COL6,COL7,'X' AS COL8, CODE, 0 as DEL, 1  from #itog 
	WHERE RIGHT(RTRIM(CODE),2) = 'ИП' ORDER BY 1, 2, 3, 4, 5,6

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	select atr, 'номеру (коду) счета:', '', '', '', '', NULL, NULL, 'X', '', 0, 1
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(A1.CODE),2) = 'ИП')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	select atr, 'номеру (коду) счета:', '', '', '', '', NULL, NULL, 'X', '', 0, 1
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(A1.CODE),2) = 'ИП')
	group by atr

	update A
	set col1 = ''
	from #all A
	where col1 = 'номеру (коду) счета:' and exists(select top 1 * from #all A1 where A.atr = A1.atr and A1.col1 = 'номеру (коду) счета:' and A1.orders < A.orders)

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	select atr, 'из них:', '', '', '', '', NULL, NULL, '', '', 0, 1
	from #all 
	group by atr
	
	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	SELECT atr, 'денежные расчеты', '', '', '', '',COL6,COL7, '', CODE, 0 as DEL, 1   from #itog 
	WHERE RTRIM(LTRIM(CODE)) = 'итог_денежные_рассчёты'

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, 'денежные расчеты', '', '', '', '',0 as COL6,0 as COL7, '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RTRIM(LTRIM(A1.CODE)) = 'итог_денежные_рассчёты')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	SELECT atr, '', COL2,COL3,COL4,COL5,COL6, COL7,COL8, CODE, 0 as DEL, 1 from #itog WHERE RIGHT(RTRIM(LTRIM(CODE)),2) = 'ИД'  ORDER BY 1, 2, 3, 4, 5,6
   
	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, '', '', '', '', '',0 as COL6,0 as COL7, '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(LTRIM(A1.CODE)),2) = 'ИД')
	group by atr


	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	SELECT atr, 'неденежные расчеты', '', '', '', '',COL6,COL7, '',CODE, 0 as DEL,1  
	from #itog WHERE LTRIM(RTRIM(CODE)) = 'итог_неденежные_рассчёты'

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr,'неденежные расчеты', '', '', '', '',0 as COL6,0 as COL7, '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and LTRIM(RTRIM(A1.CODE)) = 'итог_неденежные_рассчёты')
	group by atr
	
	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, CODE, DEL, ITOG)
	SELECT atr, '', COL2,COL3,COL4,COL5,COL6,COL7,COL8,CODE, 0 as DEL, 1  from #itog WHERE RIGHT(LTRIM(RTRIM(CODE)),2) = 'ИН'  ORDER BY 1, 2, 3, 4, 5,6

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog)
	SELECT atr, '', '', '', '', '',0 as COL6,0 as COL7, '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(LTRIM(A1.CODE)),2) =  'ИН')
	group by atr

	select atr as colatr, col1, col2, col3, col4, col5, col6, col7, col8, code, del, itog as colitog, orders from #all order by atr, orders

	drop table #all
	drop table #ist
	drop table #doh
	drop table #rash
	drop table #itog

	if isnull(@WEB_excel, 0) <> 1
	select cells as style,style as value from report_print_style where 1=0 order by cells


GO
GRANT ALL ON dbo.[RO_PRINT_125] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_SAVE_FORMA_RRO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_SAVE_FORMA_RRO]
GO
/*
c Кейсистемс (Keysystems), 2008
*/
CREATE  PROCEDURE dbo.[RT_SAVE_FORMA_RRO]
	@varKSintLINK	int	OUTPUT,
	@varKScPNUM	varchar(8),
	@varKScNAME	varchar(250) = NULL,
	@varKScFNAME varchar(4000) = NULL,
	@varKScCODE	varchar(250) = NULL,
	@varKSiLink_self int = NULL,
	@varKSperiod varchar(6) = NULL, -- не будет использоваться
	@varKSdBeginDate datetime = NULL,
	@varKSdEndDate datetime = NULL,
	@varKStab tinyint = 1
AS
DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR	 	int,
	@varKSRowCount	int,
	@link int,
	@looks_like_error int,
	@Orders int,
	@kodop char(1),
	@begin_date datetime,
	@end_date datetime,
	@sqlquery varchar(8000)

	set @varKScFNAME = REPLACE(@varKScFNAME, '»', '"')
	set @varKScFNAME = REPLACE(@varKScFNAME, '«', '"')
	set @varKScFNAME = REPLACE(@varKScFNAME, '–', '-')

	declare @t_reports table (LSF int)
	insert @t_reports (LSF) -- отчеты для обновления
	select Link_Saved_Form
	from report_saved_forms RSF join report_forms RF on RSF.link_form = RF.link_form where	RF.Code = 'RRO'
		and begin_date >= isnull(@varKSdBeginDate, '19000101') and begin_date <= isnull(@varKSdEndDate, '21000101')

	set @kodop = left(@varKScPNUM,1) -- код операции -- 0 - добавление, 1 - редактирование, 2 - удаление
	set @varKScPNUM = right(rtrim(@varKScPNUM),LEN(@varKScPNUM)-1)
	
	if exists(
		select * 
		from dbo.report_kbk 
		where code_form = (case @varKStab when 1 then 'РРО' else 'РРО2' end) 
		and substring(ltrim(rtrim(code)),patindex('%@@%',ltrim(code))+2,9) = ltrim(rtrim(@varKScCODE)) 
		and ((begin_date <= @varKSdBeginDate) and (@varKSdBeginDate <= end_date or end_date is NULL))
		and (@varKSintLINK is null  OR @varKSintLINK = 0 OR @varKSintLINK <> LINK)
		and @kodop in ('0', '1')
	)
		set @looks_like_error = 1
	else
		set @looks_like_error = 0

	IF @looks_like_error = 1
		RETURN 8

SET LOCK_TIMEOUT 5000
SET IMPLICIT_TRANSACTIONS ON


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	IF (@varKSintLINK is null  OR @varKSintLINK = 0) 
	BEGIN
		select @Orders = max(Orders)+1 from dbo.report_kbk where Code_Form = (case @varKStab when 1 then 'РРО' else 'РРО2' end) and Link_Self = isnull(@varKSiLink_self,0)
		insert into  [dbo].[REPORT_KBK] (Code,link_self,Code_Form,Childrens,[Name],Long_name,Orders,begin_date,end_date)
			VALUES (ltrim(rtrim(@varKScPNUM))+'@@'+ltrim(rtrim(@varKScCODE)), isnull(@varKSiLink_self,0), (case @varKStab when 1 then 'РРО' else 'РРО2' end), 1, @varKScNAME, @varKScFNAME, isnull(@Orders,0), @varKSdBeginDate, @varKSdEndDate)
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		if isnull(@varKSiLink_self,0) <> 0 begin
			update [dbo].[REPORT_KBK]
			set Childrens = 0
			where Link = @varKSiLink_self
		end
	END
	ELSE
	BEGIN
		UPDATE [dbo].[REPORT_KBK]
			SET Code = ltrim(rtrim(@varKScPNUM))+'@@'+ltrim(rtrim(@varKScCODE)),
				Link_Self = isnull(@varKSiLink_self,0),
				[Name] = @varKScNAME,
				Long_name = @varKScFNAME,
				begin_date = @varKSdBeginDate,
				end_date = @varKSdEndDate
		from [REPORT_KBK]
		WHERE LINK = @varKSintLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
	-- удаление всех потомков
	if @varKSdEndDate is NOT NULL and exists (select * from report_kbk where link_self = @varKSintLINK)
	begin
		update REPORT_KBK
		set end_date = @varKSdEndDate
		where link_self = @varKSintLINK and isnull(end_date, '21000101') > @varKSdEndDate
	end


	-- удаление всех РО из отчётов с кодом удалённого узла --
	if @kodop = '2' begin
		if @varKSdEndDate is not null begin
			if exists(select * from dbo.RT_GET_RECORDS_RRO(@varKStab,null) where rtrim(code) = rtrim(@varKScCODE) and datediff(day,@varKSdEndDate,begin_date)>1) begin
				-- если этот код (РО) был открыт где-то в будущем, то удаляем код из отчётов между этими датами
				set @begin_date = @varKSdEndDate + 1
				select @end_date = begin_date - 1 
				from dbo.RT_GET_RECORDS_RRO(@varKStab,null) 
				where rtrim(code) = rtrim(@varKScCODE) 
				and datediff(day,@varKSdEndDate,begin_date) = (
					select min(datediff(day,@varKSdEndDate,begin_date)) 
					from dbo.RT_GET_RECORDS_RRO(@varKStab,null) 
					where rtrim(code) = rtrim(@varKScCODE)
					and datediff(day,@varKSdEndDate,begin_date)>1)	
			end 
			else begin 
				-- иначе удаляем код из всех отчётов до 2100 года
				set @begin_date = @varKSdEndDate + 1
				set @end_date = '2100-01-01'
			end
			set @sqlquery = '
				delete from dbo.report_dinamics
				where link_sf in (
					select link_saved_form 
					from dbo.report_saved_forms 
					where link_form = (select link_form from dbo.report_forms where code = ''RRO'')
					and begin_date between '''+rtrim(convert(varchar,@begin_date,112))+''' and '''+rtrim(convert(varchar,@end_date,112))+'''
				)
				and link_col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where orders = '+cast(@varKStab as char(1))+' and link_form = (select link_form from dbo.report_forms where code = ''RRO'')))
				and substring(rtrim(code_row),8,9) = '''+rtrim(@varKScCODE)+'''
			'
			execute(@sqlquery)
		end
	end

	-- изменение всех РО в отчетах
	if @kodop = 1
	begin
		update report_dinamics
		set Code_Row = left(isnull(@varKScPNUM,'') + '        ', 7) + substring(Code_Row,8,12)
		where Link_SF in (select LSF from @t_reports)
			and Link_Col in (select link_col from report_coloumns RC join report_tables RT on RC.Link_Table =RT.Link_Table and RT.orders = @varKStab join report_forms RF on RT.Link_Form = RF.Link_Form where RF.Code = 'RRO')
			and substring(Code_Row,8,9) = @varKScCODE

		-- номер пункта меняем
		update report_dinamics
		set Str_Val = left(isnull(@varKScPNUM,'') + '        ', 7)
		where Link_SF in (select LSF from @t_reports)
			and Link_Col in (select link_col from report_coloumns RC join report_tables RT on RC.Link_Table =RT.Link_Table and RC.orders = 7 and RT.orders = @varKStab join report_forms RF on RT.Link_Form = RF.Link_Form where RF.Code = 'RRO')
			and substring(Code_Row,8,9) = @varKScCODE

		-- меняем наименование РО
		update report_dinamics
		set Str_Val = @varKScFNAME
		where Link_SF in (select LSF from @t_reports)
			and Link_Col in (select link_col from report_coloumns RC join report_tables RT on RC.Link_Table =RT.Link_Table and RC.orders = 8 and RT.orders = @varKStab join report_forms RF on RT.Link_Form = RF.Link_Form where RF.Code = 'RRO')
			and substring(Code_Row,8,9) = @varKScCODE
	end

	-- удаление дубликатов из дерева
	if @kodop = '2' begin
		-- удаление узлов для которых выполняется условие: begin_date > end_date
		delete from dbo.report_kbk
		where code_form = (case @varKStab when 1 then 'РРО' else 'РРО2' end)
		and isnull(begin_date, '19000101') > isnull(end_date, '22000101')

		declare @the_table table (the_code varchar(254),begin_year smallint, end_year smallint, min_link int)

		-- удаляем одинаковые в одном периоде
		insert into @the_table (the_code,begin_year, end_year, min_link)
		select rtrim(ltrim(code)),YEAR(isnull(begin_date,'19000101')) as begin_year, YEAR(isnull(end_date,'22001231')) as end_year,min(link)
		from dbo.report_kbk 
		where code_form = (case @varKStab when 1 then 'РРО' else 'РРО2' end)
		group by code,YEAR(isnull(begin_date,'19000101')),YEAR(isnull(end_date,'22001231'))
		having count(*) > 1
		
		delete from dbo.report_kbk 
		where code_form = (case @varKStab when 1 then 'РРО' else 'РРО2' end)
		and exists(select top 1 * from @the_table T where rtrim(ltrim(T.the_code)) = rtrim(ltrim(report_kbk.code)) and begin_year = YEAR(isnull(begin_date,'19000101')) and end_year = YEAR(isnull(end_date,'22001231')))
		and link not in (select min_link from @the_table)
	
	END
   
      DELETE dbo.report_kbk_cashe WHERE link_up = @varKSintLINK
       
      INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
      SELECT K.[LINK], 
            [begin_date] = isnull((case when isnull(K.[begin_date],'19000101') > isnull(KH.date_begin,'19000101') then K.[begin_date] ELSE KH.date_begin END), '19000101'),
            [end_date] = ISNULL((case when isnull(K.[end_date],'30000101') > isnull(KH.date_end,'30000101') then KH.[date_end] ELSE K.end_date END),'30000101'),
            isnull(KH.[NAME], K.Name),
            isnull(KH.[LONG_NAME], K.[LONG_NAME])
      FROM dbo.report_kbk K
         LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
      WHERE K.link = @varKSintLINK
         
   
   INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
   SELECT K.[LINK], 
         isnull(K.[begin_date], '19000101'),
         KH.[date_begin]-1,
         K.[NAME],
         K.[LONG_NAME]
   FROM dbo.report_kbk K
          LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   WHERE isnull(K.begin_date, '19000101') < KH.date_begin
         AND KH.date_begin = (SELECT MIN(KH1.DATE)
                              FROM dbo.[REPORT_KBK_HIST] KH1
                              WHERE KH1.[LINK_UP] = K.[link])
      AND K.link = @varKSintLINK


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO
GRANT EXECUTE ON dbo.[RT_SAVE_FORMA_RRO] 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.[SD_BASE_SUM_PAY_Buffer]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_BASE_SUM_PAY_Buffer]

GO


CREATE PROCEDURE dbo.SD_BASE_SUM_PAY_Buffer

 @varKSRefPay 	int,
 @varBurrerCode	varchar(100),
 @varKSdDate1	datetime,
 @varKSdDate2	datetime,
 @LINK_KBK 	INT = NULL			 
AS  
SET @LINK_KBK = COALESCE(@LINK_KBK,0)

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

SELECT 		REF_EMPL 	= SJ.LINK_EMPL,
		CODE_PAY 	= SJ.[CODE_PAYS],
		NAME_PAY 	= SJ.[NAME_PAYS],
		SJ.[WAY_CALC],
		LINK_PAY 	= SJ.LINK_PAYS,
		base 		= SUM(SJ.summa)
FROM S_J_C_Short SJ INNER JOIN dbo.group_pays(@varKSRefPay) T  ON SJ.link_PAYS=T.PAY_LINK
	INNER JOIN dbo.Buffer B on SJ.LINK_EMPL = B.link
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
WHERE 
	(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_BEGIN ELSE SJ.DATE1 END) >=@varKSdDate1 
	AND 
	(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_END ELSE SJ.DATE2 END) <=@varKSdDate2
	AND	
	RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@varBurrerCode))
	AND
	(@LINK_KBK = 0 OR SJ.LINK_VKR = @LINK_KBK)
GROUP BY  
	SJ.LINK_EMPL, SJ.LINK_PAYS, SJ.[CODE_PAYS], SJ.[NAME_PAYS], SJ.[WAY_CALC]




GO


GRANT EXECUTE ON dbo.[SD_BASE_SUM_PAY_Buffer] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_VAC_FILL1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_VAC_FILL1]

GO

CREATE    PROCEDURE dbo.SA_N_VAC_FILL1 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @OBJ_CODE VARCHAR(50), --Код объекта
 @SR_VID TINYINT = 1, -- Прочие расчеты по среднему 1 - Компенсация за отпуск, 2 - прочее
 @LINK_VAC INT, --Ссылка на приказ
 @SR_LINK_EMPL INT  = NULL, --Прочие расчеты по среднему  Ссылка на сотрудника
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT  = NULL, --Тип расчетного периода: 1- 3 месяца, 2 - 12 месяцев
 @VID_DAYS TINYINT  = NULL,-- Способ расчета 1 - в рабочих днях, 2 - в календарных днях
 @SR_DATE1 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала
 @SR_DATE2 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата окончания
 @SR_DATE DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала расчетного периода
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

-- Определение типа расчетного периода
SET @TYP_PERIOD = CASE WHEN COALESCE(@TYP_PERIOD,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT2')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT1')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 1
				ELSE NULL
			END
		ELSE @TYP_PERIOD END
-- Определение способа расчета
SET @VID_DAYS = CASE WHEN COALESCE(@VID_DAYS,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT3')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT2')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 2
				ELSE NULL
			END
		ELSE @VID_DAYS END
---инит
DECLARE 
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало отпуска, командировки
 @DATE_BEGIN2 DATETIME, --Начало отпуска, командировки
 @DATE_END DATETIME, --Окончание отпуска, командировки
 @REF_TYP INT, --Ссылка на вид отпуска, командировки
 @order_link int, 
 @NEW_DATE_END DATETIME,
 @NEW_DATE_BEG DATETIME,
 @UCHET_PREM TINYINT,
 @comment varchar(100),
 @HOLIDAY TINYINT,
 @NO_RAION TINYINT

DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN COALESCE(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@DATE_BEGIN = DATE_BEGIN,
		@SR_DATE = COALESCE(@SR_DATE, (select min(DATE_BEGIN) from dbo.ITEM_VACATION IV1 WHERE IV1.order_link = IV.order_link and IV1.EMPL_LINK = IV.EMPL_LINK)), 
		@DATE_END = DATE_END,
		@REF_TYP = IV.TYPE_LINK, @order_link = order_link,
		@comment = @UNAME + 'Начисл.отпускных:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(VV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@HOLIDAY = VV.HOLIDAY, --С учетом праздничных
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_VACATION IV ON IV.ORDER_LINK = O.LINK
		INNER JOIN dbo.VACATION_VID VV ON IV.TYPE_LINK = VV.LINK WHERE IV.LINK = @LINK_VAC

	DECLARE	@DATE_BREAK DATETIME	-- дата отзыва из отпуска
	DECLARE	@DATE_BREAK_NEW_BEGIN DATETIME	-- дата отзыва из отпуска

	-- Уменьшение: об отзыве, о выходе из отпуска по уходу за ребенком
	IF EXISTS(SELECT * FROM ITEM_VACATION_BREAK IVB WHERE IVB.ACTIVE = 1 AND ISNULL(BREAK_WORK_DAYS,0) != 0 AND IVB.VAC_LINK = @LINK_VAC) BEGIN

		DECLARE @BREAK_WORK_DAYS INT	-- количество рабочих дней отзва
		DECLARE @LEN_KAL_DAYS INT	-- количество календарных дней продления
		DECLARE @EMPL_LINK INT		-- ссылка на сотрудника
		--
		SELECT	TOP 1
			@EMPL_LINK = EMPL_LINK,
			@DATE_BREAK = DATE_BREAK,
			@BREAK_WORK_DAYS = BREAK_WORK_DAYS,
			@LEN_KAL_DAYS = LEN_KAL_DAYS
		FROM	ITEM_VACATION_BREAK IVB
		WHERE	IVB.ACTIVE = 1
			AND ISNULL(BREAK_WORK_DAYS,0) != 0
			AND IVB.VAC_LINK = @LINK_VAC
		--
		SET ROWCOUNT @BREAK_WORK_DAYS
		SELECT	T.DATE
		INTO	#TEMP_TABLE
		FROM
		(
		SELECT	[DATE]  = dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)),
			[HOURS] = MAX(HOURS)
		FROM	GRAPHICS G INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE	G.GRAPH_LINK = dbo.kd_GetEmplGr(@EMPL_LINK)
			AND dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)) BETWEEN @DATE_BREAK AND @DATE_BREAK + @BREAK_WORK_DAYS + @LEN_KAL_DAYS
		GROUP	BY dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD))
		) T
		WHERE	T.HOURS > 0
			AND T.DATE >= @DATE_BREAK
		SET ROWCOUNT 0
		--
		SET @DATE_BREAK_NEW_BEGIN = (SELECT TOP 1 DATE + 1 FROM #TEMP_TABLE ORDER BY DATE DESC)
		SET @NEW_DATE_END = @DATE_END + @LEN_KAL_DAYS - 1 + 1  -- расчет окончания отпуска с учетом отзыва
	
		DROP TABLE #TEMP_TABLE
		SET @DATE_END = COALESCE(@NEW_DATE_END,@DATE_END)

	END 
	ELSE BEGIN
		SET @NEW_DATE_END = (SELECT MIN(ivb.DATE_BREAK - 1) FROM dbo.item_vacation iv inner join dbo.item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
		SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) <  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)
	END
	-- Увеличение: о продлении по болезни
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE  ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END


IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL'
BEGIN
	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@SR_DATE = COALESCE(@SR_DATE, DATE_BEGIN), 
		@DATE_BEGIN = DATE_BEGIN, @DATE_END = DATE_END, 
		@REF_TYP = IT.TYPE_LINK,
		@comment = @UNAME + 'Начисл.командир.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.item_travel IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN dbo.KOMAND_VID KV ON IT.TYPE_LINK = KV.LINK WHERE IT.LINK = @LINK_VAC

	-- Увеличение: о продлении 
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END

DECLARE @PDAY NUMERIC(5,2)
SET @PDAY = 0

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, 
		@SR_DATE = COALESCE(@SR_DATE, DIS_DATE), 
		@DATE_BEGIN = DIS_DATE + 1, 
		@DATE_END = (DIS_DATE + 1) + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@PDAY = CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN VAC_KOMPENS_DAY - CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@REF_TYP = IT.REASON,
		@comment = @UNAME + 'Компенс.за неисп.отпуск:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK), 
		@SR_DATE1 = DIS_DATE + 1, 
		@SR_DATE2 = DIS_DATE + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_DIS_FACE IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN [dbo].[DICTION] KV ON IT.REASON = KV.LINK 
	WHERE IT.LINK = @LINK_VAC AND ISNULL(VAC_KOMPENS_DAY,0) > 0

	IF @LINK_EMPL IS NULL
		SELECT @LINK_EMPL = @SR_LINK_EMPL, @comment = @UNAME + 'Начисл.средн.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(P.[NAME])),30)
		FROM dbo.PAYS P WHERE LINK = @LINK_PAYS

	SELECT @LINK_DEP = DEP_LINK FROM DBO.USER_DEP WHERE @LINK_DEP IS NULL
END

--- Учет премии в расчете
IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT8'),1)
ELSE
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('CALC_TRAVEL_OPT5'),1)

---

DECLARE 
 @SystPay INT,
 @RP INT, --Размер расчетного периода 
 @DATE_BEGIN_RP DATETIME, --Начало расчетного периода
 @DATE_END_RP DATETIME, --Конец расчетного периода
 @DATE_BEGIN_WRK DATETIME, --Дата приема сотрудника
 @DATE_END_WRK DATETIME, --Дата увольнения сотрудника
 @LINK_PERS INT, --Ссылка на физ.лицо
 @DEP_LINK INT,
 @MAX_DATE DATETIME,
 @I INT,
 @varKSsoLink INT

SET @RP = (CASE @TYP_PERIOD WHEN 1 THEN 3 WHEN 2 THEN 12 ELSE 0 END)

SELECT TOP 1 
 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = DEP_LINK, 
 @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), 
 @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN), 
 @MAX_DATE = '29990101',
 @NO_RAION = ISNULL(NO_RAION,0) 
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

declare @EmplNumStake numeric(5,2)
Set @EmplNumStake = Coalesce(dbo.ku_GetEmplNumStake(@LINK_EMPL,DEFAULT),0)

---Определение расчетного периода
IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
	SELECT @DATE_BEGIN_RP = @SR_DATE, @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)), @DATE_BEGIN = @SR_DATE1, @DATE_END = @SR_DATE2, @LINK_EMPL = @SR_LINK_EMPL
ELSE
	SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > @SR_DATE THEN @DATE_BEGIN_RP ELSE @SR_DATE END),
	@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) END ),
	@SR_VID = 1

---
DECLARE @MINROT NUMERIC(18,2)
SET @MINROT = dbo.minrot2(@DATE_BEGIN) * @EmplNumStake

--- Если новый расчет, то получить линк документа
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME
IF COALESCE(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, @OBJ_CODE
	SET @DATE_DOC = (Select top 1 WORKDATE from USER_DATES)
	exec dbo.SD_N_VACATION_SAVE @LINK_DOC OUT,@OBJ_CODE, @NUMBER, @DATE_DOC, @LINK_PAYS, @comment, 0, @LINK_EMPL, 0, 0, @TYP_PERIOD, 
			@DATE_BEGIN, @DATE_END, 0, @VID_DAYS, @LINK_VAC, 0, @SR_VID, @DATE_BEGIN_RP, @LINK_DEP
END
ELSE
	SET @DATE_DOC = (SELECT [DATE] FROM SDOC WHERE LINK = @LINK_DOC)

--
UPDATE dbo.SDOC_AVAC 
SET INSTR = 1
WHERE LINK_UP = @LINK_DOC

--
IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN

	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		NADB NUMERIC(18,2),
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		SUM0 NUMERIC(18,2),
		KOEF  NUMERIC(18,4),
		CV	NUMERIC(18,2),
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)


	DECLARE @DEFAULT_KBK INT
	SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)

	INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
	exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

	IF COALESCE((SELECT SUM(SUMMA) FROM #BASE1),0) = 0 BEGIN

		SELECT TOP 1  @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN)
		FROM dbo.EMPL WHERE LINK = @LINK_EMPL
		---	
		IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
			SELECT @DATE_BEGIN_RP = DATEADD(MONTH,-@RP,@SR_DATE), @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, (@RP-1)+@RP,@SR_DATE))
		ELSE 
			SELECT @DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > DATEADD(MONTH, -(@RP+@RP),@DATE_BEGIN) THEN @DATE_BEGIN_RP ELSE DATEADD(MONTH, -@RP*2,@DATE_BEGIN) END),
			@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) END )

		IF COALESCE(@DATE_END_RP,@MAX_DATE) < @DATE_BEGIN_RP
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN_RP)
		---
		INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
		exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

		IF COALESCE((SELECT SUM(SUMMA) FROM #BASE1),0) = 0 BEGIN
			SET @DATE_BEGIN_RP = dbo.DateBeginOfMonth(@DATE_BEGIN)
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN)
	
			INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
			SELECT @DATE_BEGIN, 0, P.CODE, P.NAME, P.WAY_CALC, S.LINK_PAY, S.SUMMA,S.SUMMA, 1, 0, S.LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN) 
			FROM 
				dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEGIN, DEFAULT, @LINK_DEP) S
				inner join dbo.pays P on s.link_pay = p.link
			WHERE s.link_pay IN (SELECT T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)
	
		END
		
	END

	---
	UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @KBK_OPT TINYINT
	IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
		SET @KBK_OPT = dbo.sa_get_option_by_code('FURLOUGH_OPT7')
	ELSE			
		SET @KBK_OPT = dbo.sa_get_option_by_code('CALC_TRAVEL_OPT4')

	DECLARE @isMATER tinyint
	SET @isMATER = dbo.sa_get_option_by_code('FURLOUGH_OPT12')

	IF @KBK_OPT <> 1
	BEGIN
		--- Заменить на общий коэф. индексации, если есть за один период несколько одинаковых начислений с разными источниками и разными коэффициентами индексации
		CREATE TABLE #GRP_KOEF (PERIOD DATETIME, LINK_PAY INT, GRP_KOEF NUMERIC(18,4))
		
		INSERT INTO #GRP_KOEF (PERIOD, LINK_PAY, GRP_KOEF)
		SELECT PERIOD, LINK_PAY, ROUND(SUM(SUMMA) / SUM(SUM0),4) FROM #BASE1 GROUP BY PERIOD, LINK_PAY HAVING(SUM(SUM0)) > 0
		
		UPDATE #BASE1
		SET KOEF = (SELECT TOP 1 GRP_KOEF FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		WHERE EXISTS (SELECT * FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		
		DROP TABLE #GRP_KOEF
	END	

	--------------------------------------------------------------------------------------------------------------
	DECLARE 
		@FURLOUGH_OPT_REG_KOEF INT, -- Расчет с учетом районного коэффициента
		@FURLOUGH_OPT_NORTH_KOEF INT -- Расчет с учетом северного коэффициента

	--Если у сотрудника указано "Не начислять районный", то рассчитываем без районного
	SET @FURLOUGH_OPT_REG_KOEF = 
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('FURLOUGH_OPT15') END)
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') END)
				WHEN 'DOCUMENTS_CALC_AVG' THEN (CASE WHEN @NO_RAION = 1 
													THEN 0 
													ELSE 
														CASE WHEN @SR_VID = 1 
															THEN dbo.sa_get_option_by_code('FURLOUGH_OPT15') 
															ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') 
														END	
												END)				
				ELSE 0
			END		

	SET @FURLOUGH_OPT_NORTH_KOEF =
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 	CASE WHEN @SR_VID = 1 
													THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16') 
													ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8') 
												END	
				ELSE 0
			END		 

	DECLARE @NORTH_KOEF NUMERIC(6,2), @REG_KOEF NUMERIC(6,2)
	
	IF @FURLOUGH_OPT_REG_KOEF = 1 OR @FURLOUGH_OPT_NORTH_KOEF = 1
	BEGIN
	
		SET @NORTH_KOEF = DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEGIN,2) / 100
		SET @REG_KOEF = DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEGIN,1) / 100

		UPDATE #BASE1
		SET 
			SUMMA = ISNULL(SUMMA,0)
				---Накручиваем районный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_REG_KOEF = 1 AND @REG_KOEF > 0 THEN ISNULL(SUMMA,0) * @REG_KOEF ELSE 0 END)
				---Накручиваем северный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_NORTH_KOEF = 1 AND @NORTH_KOEF > 0 THEN ISNULL(SUMMA,0) * @NORTH_KOEF ELSE 0 END),

			SUM0 = ISNULL(SUM0,0)
				---Накручиваем районный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_REG_KOEF = 1 AND @REG_KOEF > 0 THEN ISNULL(SUM0,0) * @REG_KOEF ELSE 0 END)
				---Накручиваем северный коэффициент, если надо
				+ (CASE WHEN @FURLOUGH_OPT_NORTH_KOEF = 1 AND @NORTH_KOEF > 0 THEN ISNULL(SUM0,0) * @NORTH_KOEF ELSE 0 END)

	END
	--------------------------------------------------------------------------------------------------------------

	---
	Select PERIOD = MIN(PERIOD), PERIOD1 = (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC in (6,7) AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUM0 * --В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END,
								CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1)
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE
					CASE WHEN WAY_CALC = 12 
					THEN
						CONVERT(NUMERIC(18,2), SUM0 * 
							CASE @isMATER
								WHEN 1 THEN 1 --1) Полностью
								WHEN 2 THEN --2) В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
									CONVERT(NUMERIC(18,2), (DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END, 
									CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1))
									/ (DATEDIFF(MONTH,DATE1, DATE2) + 1)
								WHEN 3 THEN 0 --3) Вообще не включать
							ELSE 1 END)
					ELSE SUM0 
					END
			END), 
		SUM0 = SUM(SUM0),	
		KOEF, 
		LINK_VKR = (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 
	INTO #BASE
	from #BASE1 
	where (@isMATER = 3 and WAY_CALC <> 12 or @isMATER <> 3)
	group by (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 

	-- Перевенем таблицу 
	DECLARE @PAYS_MONTS VARCHAR(100)
	EXEC X_GET_TABLE_NAME @PAYS_MONTS OUTPUT

	---
	EXEC M_CROSS_TABLE
		'LINK_PAY, LINK_VKR',
		'PERIOD1', 'INT',
		'SUMMA', 'NUMERIC(18,2)', 'SUM(SUMMA) AS SUMMA',
		'#BASE', @PAYS_MONTS

	DECLARE @PAYS_MONTS1 VARCHAR(100)
	SET @PAYS_MONTS1 = @PAYS_MONTS + '1'

	EXEC M_CROSS_TABLE
		'LINK_PAY, LINK_VKR',
		'PERIOD1', 'INT',
		'KOEF', 'NUMERIC(18,4)', 'MAX(KOEF) AS KOEF',
		'#BASE', @PAYS_MONTS1

	DELETE FROM dbo.SDOC_AVAC_TABLE3  WHERE LINK_UP = @LINK_DOC
	
	DECLARE @SCRIPT VARCHAR(8000)
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_AVAC_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, KOEF1, SUMMA2, KOEF2, SUMMA3, KOEF3, SUMMA4, KOEF4, SUMMA5, KOEF5, SUMMA6, KOEF6, 
				SUMMA7, KOEF7, SUMMA8, KOEF8,  SUMMA9, KOEF9, SUMMA10, KOEF10, SUMMA11, KOEF11,  SUMMA12, KOEF12)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, P1.LINK_PAY, P1.LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
		+ ' from ' + @PAYS_MONTS + ' P1 LEFT JOIN ' + @PAYS_MONTS1 + ' P2 ON P1.LINK_PAY = P2.LINK_PAY AND P1.LINK_VKR = P2.LINK_VKR' 

	exec (@SCRIPT)

	SET @I = 0
	UPDATE dbo.SDOC_AVAC_TABLE3  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC
	
END -- IF @RECALC = 0


IF @RECALC < = 1 --- Расчет сумм по месяцам
BEGIN
	---- Время
	DECLARE @WTIME TABLE(M INT, Y INT, DAYS NUMERIC(18,2), HOURS NUMERIC(18,2), DAYS_NORM NUMERIC(18,2), HOURS_NORM NUMERIC(18,2), KDAYS NUMERIC(18,2), KDAYS_N NUMERIC(18,2))

	DECLARE @LINK_GRAPH INT
	SET @LINK_GRAPH = (SELECT TOP 1 GRAPH_LINK FROM DBO.EMPL WHERE LINK = @LINK_EMPL)

	INSERT INTO @WTIME (M,Y,DAYS,HOURS,DAYS_NORM,HOURS_NORM,KDAYS,KDAYS_N)
	---Данные по табелям 
	SELECT  M, Y,
		DAYS = COALESCE(CONVERT(NUMERIC(4,0), DBO.SA_GET_EMPL_WD (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		HOURS = COALESCE(CONVERT(NUMERIC(10,2), DBO.SA_GET_EMPL_WH (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		DAYS_NORM = ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL,M,Y)),0),
		HOURS_NORM = ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(@LINK_EMPL,M,Y)),0),
		0,0
	FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) M
	WHERE NOT EXISTS (SELECT * FROM @WTIME W WHERE (W.Y = M.Y AND W.M = M.M) )

	---
	IF  @VID_DAYS <> 1 BEGIN-- В календарных днях
		UPDATE @WTIME
		SET KDAYS = ISNULL(CONVERT(NUMERIC(4,0),dbo.SA_CALENDAR_DAYS_FN(@LINK_EMPL,M,Y)),0),
			KDAYS_N = ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1, M, Y)))),0)

	END

	Declare @KBK_DEF INT
	SET @KBK_DEF = (Select top 1 link_kbk from dbo.KU_EmplStafKBK(default) where link_empl = @LINK_EMPL)

	---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), SUMMA_MAT NUMERIC(18,2), DAYS INT, HOURS NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2), KDAYS INT, KDAYS_N INT)
	INSERT INTO @TABLE2
	SELECT  
		T.Y,
		T.M,
		COALESCE(B.LINK_KBK,@KBK_DEF),
		SUMMA_ZP = SUM( CASE WHEN coalesce(PAYMENT,0) not in (7,12) THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_PR = SUM( CASE WHEN coalesce(PAYMENT,0) = 7 THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_MAT = SUM( CASE WHEN coalesce(PAYMENT,0) = 12 THEN coalesce(SUMMA,0) ELSE 0 END),
		COALESCE(DAYS,0),COALESCE(HOURS,0),COALESCE(DAYS_NORM,0),COALESCE(HOURS_NORM,0), COALESCE(KDAYS,0), COALESCE(KDAYS_N,0)
	FROM 
		@WTIME T LEFT JOIN 
		(
		Select PERIOD = DATEADD(MONTH,0,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA1,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,1,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA2,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA2,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,2,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA3,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA3,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,3,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA4,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA4,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,4,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA5,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA5,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,5,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA6,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA6,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,6,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA7,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA7,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,7,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA8,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA8,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,8,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA9,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA9,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,9,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)),	

			SUMMA = COALESCE(T3.KSUMMA10,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA10,0) <> 0 
	UNION ALL
		Select PERIOD = DATEADD(MONTH,10,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA11,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA11,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,11,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA12,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3 WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA12,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD) AND T.M = MONTH(B.PERIOD)
	GROUP BY
		T.Y, T.M, B.LINK_KBK, DAYS,HOURS, DAYS_NORM, HOURS_NORM, KDAYS, KDAYS_N	

	-----
	DELETE FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE2 (LINK_UP, ORDERS, PERIOD, LINK_KBK, SUMMA, PREM, DAYS, HOURS, DAYS_N, HOURS_N, KDAYS, KDAYS_N, MATER)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), 
	LINK_KBK, SUMMA_ZP, SUMMA_PR, DAYS,HOURS,DAYS_NORM,HOURS_NORM, KDAYS, KDAYS_N, SUMMA_MAT
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

	SET @I = 0
	UPDATE dbo.SDOC_AVAC_TABLE2  
	SET @I = @I+1, ORDERS = @I
	WHERE LINK_UP = @LINK_DOC

END	--IF @RECALC < = 1

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		
	---Периоды отпуска

	DECLARE @PERIODY TABLE (DATE_BEGIN DATETIME, DATE_END DATETIME, DH_NORM NUMERIC(18,2))
	
	--- 1. Разбивка на периоды по плательщикам и календарным месяцам
	if @DATE_BREAK IS NULL
		INSERT INTO @PERIODY (DATE_BEGIN, DATE_END)
		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)
		from dbo.months_ex(@DATE_BEGIN, @DATE_END)
	ELSE
	BEGIN
		SET @DATE_BREAK = @DATE_BREAK -1
		INSERT INTO @PERIODY (DATE_BEGIN, DATE_END)
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN  @DATE_BREAK < dbo.DateEndOfMonth(DATE_BEGIN) THEN  @DATE_BREAK ELSE dbo.DateEndOfMonth(DATE_BEGIN) END)
		from dbo.months_ex(@DATE_BEGIN, @DATE_BREAK)

		INSERT INTO @PERIODY (DATE_BEGIN, DATE_END)
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BREAK_NEW_BEGIN > DATE_BEGIN THEN @DATE_BREAK_NEW_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END)
		from dbo.months_ex(@DATE_BREAK_NEW_BEGIN, @DATE_END)

	END

	----
	UPDATE @PERIODY
	SET DH_NORM = 
			  CASE WHEN @VID_DAYS = 1 
				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAY_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  ELSE	
				DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1 - (CASE WHEN @HOLIDAY = 1 THEN dbo.SA_HOLIDAY_COUNT_FN(DATE_BEGIN,DATE_END) ELSE 0 END) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  END

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @PNORM NUMERIC(18,2), @PWORK NUMERIC(18,2), 
		@SR_ZP NUMERIC(18,2), @AvgDays NUMERIC(18,2), @DAYS_SZ NUMERIC(18,2)
	SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29.4)
	
	--- Время за расчетный период
	SELECT  [PERIOD],
		[DAYS_N] = MAX(DAYS_N),
		[HOURS_N] = MAX(HOURS_N),
		[DAYS] = MAX(DAYS),
		[HOURS] = MAX(HOURS),
		[KDAYS] = MAX(KDAYS),
		[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
	INTO #TMP
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
	GROUP BY [PERIOD]

	SELECT  
		@PNORM = SUM(CASE WHEN @SystPay = 1 THEN DAYS_N ELSE  HOURS_N END),
		@PWORK = SUM(CASE WHEN @SystPay = 1 THEN DAYS ELSE HOURS END),
		@DAYS_SZ = SUM(
			CASE WHEN @VID_DAYS = 1 THEN--В рабочих днях 
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(DAYS,0.00) >= COALESCE(DAYS_N,0.00) THEN COALESCE(DAYS_N,0.00) else COALESCE(DAYS,0.00) * 1.2 END
				ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END
			ELSE --В календарных днях
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
				ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END				
			END)
	FROM #TMP

	---	
	SELECT 
		@SUMMA_ZP = SUM(SUMMA) + SUM(MATER), 
		@SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END,
		@REP_SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC

	---	
	SET @SR_ZP = CASE WHEN @DAYS_SZ <> 0 THEN (@SUMMA_ZP + @SUMMA_PR) / @DAYS_SZ ELSE 0 END
		
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @S NUMERIC(18,2)
	SET @S = COALESCE((SELECT SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END) FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

	INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
	SELECT LINK_KBK, CASE WHEN @S <> 0 THEN (SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END)) / @S ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC 
	GROUP BY LINK_KBK
	
	---
	DELETE FROM dbo.SDOC_AVAC_TABLE1  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, DAYS, HOURS, SR_ZP, SUMMA, LINK_KBK, KOEF_KBK)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		DH_NORM,
		ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOUR_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0),
		SR_ZP = @SR_ZP,
		0,
		K.LINK_KBK,	
		K.KOEF
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	ORDER BY DATE_BEGIN

	UPDATE sdoc_avac WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SUMMA_TOTAL = @SUMMA_ZP, SR_PREM=@SUMMA_PR, 
			TYP_PERIOD=@TYP_PERIOD, SUMMA_BASE = @SR_ZP, 
			PAYMENT=@VID_DAYS, REF_DOC = @LINK_VAC, DATE1 = @DATE_BEGIN, DATE2 = @DATE_END, TYPE = @SR_VID
	WHERE LINK_UP = @LINK_DOC

	--Дневное пособие не может быть менее дневного пособия, рассчитанного исходя из МРОТ
	IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	BEGIN
		IF @VID_DAYS = 1 --Если расчет в рабочих днях
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = (case when 
		 			(CASE WHEN @SystPay = 1 
		 				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
		 				ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
		 			END)  > 0
		 
		 		then 
						case when SR_ZP < CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
												(CASE WHEN @SystPay = 1 
													THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
													ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
												END) )
							then	
								CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
									(CASE WHEN @SystPay = 1 
										THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
										ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
									END) )
							else SR_ZP end
		 		else SR_ZP end)
			WHERE LINK_UP = @LINK_DOC
		ELSE	--Если расчет в календарных днях
			IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = case when SR_ZP < dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1) 
				then	
					dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1)
				else	
					SR_ZP 
				end
			WHERE LINK_UP = @LINK_DOC	
	END
END --@RECALC <= 2 


Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, CJ.DAYS, CJ.HOURS, SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_AVAC SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	COALESCE(@LINK_VAC,0) > 0
	AND
	SA.REF_DOC = @LINK_VAC
	and
	d.object = (Select top 1 link from s_objects where code = @OBJ_CODE)
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.DAYS, CJ.HOURS, CJ.LINK_VKR


---- сопоставить старые
UPDATE dbo.SDOC_AVAC_TABLE1
SET SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.DAYS * KOEF_KBK), SUMMA_OLD = COALESCE(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM dbo.sdoc_avac A INNER JOIN dbo.SDOC_AVAC_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR
WHERE T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

-- добавить старые, которых теперь нет
insert into dbo.SDOC_AVAC_TABLE1 (link_up, ORDERS, DATE1, DATE2, DAYS, HOURS, SUMMA, LINK_KBK, SR_ZP, KOEF_KBK, SUMMA_OLD, SUMMA_NEW)
Select @LINK_DOC, 0, DATE_BEGIN, DATE_END, -DAYS, -HOURS, 0, LINK_VKR, 0, 1, SO.SUMMA, 0
from #SUM_OLD SO
where 
	NOT EXISTS (Select * from dbo.SDOC_AVAC_TABLE1 T where T.LINK_UP = @LINK_DOC and T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR)

---- сравнить
UPDATE dbo.SDOC_AVAC_TABLE1
SET SUMMA = COALESCE(SUMMA_NEW,0) - COALESCE(SUMMA_OLD,0)
WHERE LINK_UP = @LINK_DOC

---
SET @I = 0
UPDATE dbo.SDOC_AVAC_TABLE1  
SET @I = @I+1, ORDERS = @I
WHERE LINK_UP = @LINK_DOC

---
DECLARE @SUMMA NUMERIC(18,2)
SELECT @SUMMA = COALESCE((SELECT SUM(SUMMA) FROM dbo.SDOC_AVAC_TABLE1 WHERE LINK_UP = @LINK_DOC),0), @SUMMA_ZP = COALESCE(@SUMMA_ZP,0), @SUMMA_PR = COALESCE(@SUMMA_PR,0)
---
SELECT @NUMBER = NUMBER,  @DATE_DOC = [DATE] from dbo.SDOC WHERE LINK = @LINK_DOC
--- Сохрание расчета
SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = @OBJ_CODE
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA, @LINK_DEP

IF @OPER = 1 
	exec dbo.SD_N_VACATION_PROV @LINK_DOC, @OBJ_CODE
	
SET NOCOUNT OFF



GO


GRANT EXECUTE ON dbo.[SA_N_VAC_FILL1] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_SVOD_0503125M_2011]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_SVOD_0503125M_2011]
GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.[RT_SVOD_0503125M_2011]
	@varKSsFLink		int            -- экземпляр формы, куда сводим все из списка
AS

declare @LSF int,
        @rowcount int,
        @cAccount varchar(9),
        @cNameform varchar(8000),
        @IS_RBS int,
        @j int,
        @jj int,
        @i int,
        @iLink_col int,
        @code_row varchar(50),
        @float_val numeric(20,4),
        @str_val varchar(250),
		@varKSLinkF int,
		@iLink_Table int,
		@nowTab tinyint

create table #report_dinamics (Link_SF	int,Link_Col	int,Code_Row	varchar(50),Float_Val	numeric(20,4),Str_Val	varchar(8000))
Create index #IX_report_dinamics on #report_dinamics (Link_SF,link_col,code_row)

insert into #report_dinamics (Link_SF,Link_Col,Code_Row,Float_Val,Str_Val) 
select Link_SF,Link_Col,Code_Row,Float_Val,Str_Val 
from dbo.report_dinamics_all 
where link_sf = @varKSsFLink

insert into #report_dinamics (Link_SF,Link_Col,Code_Row,Float_Val,Str_Val) 
select Link_SF,Link_Col,Code_Row,Float_Val,Str_Val 
from dbo.report_dinamics_all 
where link_sf in (select linksf from #A)

-- во временной таблице #A содержатся линки сводимых таблиц
-- присваиваем новой формочке нужные атрибуты
--delete from report_atribut_values where link_saved_form = @varKSsFLink
--INSERT report_atribut_values (code_atr,link_saved_form,str_val)
--SELECT code_atr,@varKSsFLink,str_val from dbo.report_atribut_values where link_saved_form = (select top 1 LinkSF from #A)

select @varKSLinkF = link_form from dbo.report_saved_forms where link_saved_form = @varKSsFLink

select @cAccount = rtrim(rav.str_val)/*, @cNameform = rav2.str_val*/
from #A as a inner join dbo.report_atribut_values as rav 
    on a.LinkSF = rav.link_saved_form and rav.code_atr = 'REPORTS_ATR_ACC_2011'
    /*inner join dbo.report_atribut_values as rav2 
    on a.LinkSF = rav2.link_saved_form and rav2.code_atr = 'REPORTS_ATR_NAFO'*/
    inner join dbo.report_saved_forms as rsf
    on a.LinkSF = rsf.link_saved_form and rsf.link_form = @varKSLinkF
group by rav.str_val/*,rav2.str_val */

--select @IS_RBS = (case when IS_RBS = 4 then 0 else 1 end) from dbo.Departments where link = (select Link_Organization from report_saved_forms where link_saved_form = @varKSsFLink)
select @IS_RBS = 1
-- прошу запомнить крепко-накрепко! IS_RBS это ПБС,РБС,ГРБС,Финорган. 4 - это Финорган (упоминаемый в приказе 72н в описалове про свод 125)

-- создаём временную табличку в которую будем помещать данные всех форм
declare @table2 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), dnd tinyint, link varchar(254), wTab tinyint, org_synth varchar(8))
declare @table3 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), dnd tinyint, link varchar(254), wTab tinyint, org_synth varchar(8))

declare the_cursor cursor local static for
select * from #A
open the_cursor
fetch next from the_cursor into @LSF
while @@fetch_status = 0
begin
	set @i = 1 -- начинаем с первой таблицы
	while @i !> 4 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 = @i
		if @i in (1,3) begin
			insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab, org_synth)
			select coalesce(rd1.Str_Val,''),substring(coalesce(rd2.Str_Val,''),1,3),substring(coalesce(rd3.Str_Val,''),1,11),substring(coalesce(rd4.Str_Val,''),1,2),left(ltrim(coalesce(rd5.Str_Val,'')),3)+left(ltrim(coalesce(rd6.Str_Val,'')),14),@cAccount,isnull(rd7.Float_Val,0.00),isnull(rd8.Float_Val,0.00),substring(coalesce(rd9.Str_Val,''),1,9),case when cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) not in ('0','1') then NULL else cast(rtrim(isnull(rd10.Str_Val,'0')) as tinyint) end,srows.Code_Row, @i, right(rtrim(srows.Code_Row),8)
			from (
					select Code_Row from #report_dinamics
					where link_sf = @LSF 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)
		end
		if @i = 2 begin
			insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab)
			select 
				coalesce(rd1.Str_Val,''),
				substring(coalesce(rd2.Str_Val,''),1,3),
				substring(coalesce(rd3.Str_Val,''),1,11),
				substring(coalesce(rd4.Str_Val,''),1,2),
				left(ltrim(coalesce(rd5.Str_Val,'')),3)+left(ltrim(coalesce(rd6.Str_Val,'')),4)+left(ltrim(coalesce(rd7.Str_Val,'')),7)+left(ltrim(coalesce(rd8.Str_Val,'')),3),
				@cAccount,
				isnull(rd9.Float_Val,0.00),
				isnull(rd10.Float_Val,0.00),
				substring(coalesce(rd11.Str_Val,''),1,9),
				case 
					when 
						cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) not in ('0','1') 
					then 
						NULL 
					else 
						cast(rtrim(isnull(rd12.Str_Val,'0')) as tinyint) 
				end,
				srows.Code_Row, 
				@i
			from (
					select Code_Row from #report_dinamics
					where link_sf = @LSF and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
					group by Code_Row
				 ) as srows
			left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd11 on rd11.link_sf = @LSF and rd11.Code_Row = srows.Code_Row and 11 = (select Orders from dbo.report_coloumns where link_col = rd11.link_col) and rd11.link_col = (select link_col from dbo.report_coloumns where Orders = 11 and Link_Table = @iLink_Table)
			left join #report_dinamics as rd12 on rd12.link_sf = @LSF and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12 and Link_Table = @iLink_Table)
		end
		if @i = 4 begin
			insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, wTab)
			select coalesce(rd1.Str_Val,''),substring(coalesce(rd2.Str_Val,''),1,3),substring(coalesce(rd3.Str_Val,''),1,11),substring(coalesce(rd4.Str_Val,''),1,2),'',@cAccount,isnull(rd6.Float_Val,0.00),isnull(rd7.Float_Val,0.00),substring(coalesce(rd8.Str_Val,''),1,9),NULL,srows.Code_Row, @i
			from (
					select Code_Row from #report_dinamics
					where link_sf = @LSF 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)
		end
		set @i = @i + 1
	end
    fetch next from the_cursor into @LSF
end
close the_cursor
deallocate the_cursor

--в таблице @table2 строчки данных всех форм. 
if @IS_RBS = 0 begin
    if right(rtrim(@cAccount),8) = '30404000' /*and @cNameform = 'ф.0503125 по коду счета 030404000'*/ begin 
        -- итоговые. в том числе по номеру (коду) счета
        insert into @table3 (Code_Acc,summa_db,summa_kr,link,wTab)
        select Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'ИП',wTab from @table2
        where right(link,2) = 'ИП'
        group by Code_Acc,wTab
        -- итоговые по неденежным
        insert into @table3 (Code_Acc,summa_db,summa_kr,korr_acc,link,wTab)
        select Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),korr_acc,'ИН',wTab from @table2
        where right(link,2) = 'ИН'
        group by Code_Acc,korr_acc,wTab
        -- итоговая строчка суммы по итоговым неденежным
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'итог_неденежные_рассчёты',wTab from @table3
        where link = 'ИН'
		group by wTab
        -- итоговые по денежным
        insert into @table3 (Code_Acc,summa_db,summa_kr,korr_acc,link,wTab)
        select Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),korr_acc,'ИД',wTab from @table2
        where right(link,2) = 'ИД'
        group by Code_Acc,korr_acc,wTab
        -- итоговая строчка суммы по итоговым денежным
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'итог_денежные_рассчёты',wTab from @table3
        where link = 'ИД'
		group by wTab
        -- общая итоговая строчка
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'Итого',wTab from @table3
        where left(link,5) = 'итог_'
		group by wTab
    end    

    if  
		right(rtrim(@cAccount),8) in ('40120241','40110180','40120251','20651560','20651660','20721540','20731540','30101810','30121810','30251830','30251000','40110151','20551560','20551660','30111810','30131810','20731640','20551000','20651000','20711000','20721000','20731000','30111000','30131000','30141000','30151000','30221000')
		/*
		@cNameform = 'ф.0503125 по коду КОСГУ 241' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 180' or
        @cNameform = 'ф.0503125 по коду КОСГУ 251' or  
        @cNameform = 'ф.0503125 по коду счета 120612560(660)' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 540' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 810' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 830' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 151' or 
        @cNameform = 'ф.0503125 по коду счета 120505560(660)' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 710' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 640' or 
        @cNameform = 'ф.0503125 по коду счета 120505000,120612000,120702000' or
        @cNameform = 'ф.0503125 по коду счета 130101000'*/
    begin --Name_bp, ppp, okato, el_bud, Numb_Acc, summa_db, summa_kr, korr_acc, link
        -- итоговые. в том числе по номеру (коду) счета
        insert into @table3 (ppp,okato,el_bud,Code_Acc,summa_db,summa_kr, link,wTab)
        select ppp,okato,el_bud,Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'ИП',wTab from @table2
        where right(link,2) = 'ИП'
        group by ppp,okato,el_bud,Code_Acc,wTab
        -- итоговые по неденежным
        insert into @table3 (ppp,okato,el_bud,Code_Acc,summa_db,summa_kr,korr_acc,link,wTab)
        select ppp,okato,el_bud,Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),korr_acc,'ИН',wTab from @table2
        where right(link,2) = 'ИН'
        group by ppp,okato,el_bud,Code_Acc,korr_acc,wTab
        -- итоговая строчка суммы по итоговым неденежным
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'итог_неденежные_рассчёты',wTab from @table3
        where link = 'ИН'
		group by wTab
        -- итоговые по денежным
        insert into @table3 (ppp,okato,el_bud,Code_Acc,summa_db,summa_kr,korr_acc,link,wTab)
        select ppp,okato,el_bud,Code_Acc,coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),korr_acc,'ИД',wTab from @table2
        where right(link,2) = 'ИД'
        group by ppp,okato,el_bud,Code_Acc,korr_acc,wTab
        -- итоговая строчка суммы по итоговым денежным
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'итог_денежные_рассчёты',wTab from @table3
        where link = 'ИД'
		group by wTab
        -- общая итоговая строчка
        insert into @table3 (summa_db,summa_kr,link,wTab)
        select coalesce(SUM(summa_db),0.0),coalesce(SUM(summa_kr),0.0),'Итого',wTab from @table3
        where left(link,5) = 'итог_'
		group by wTab
    end
    if  right(rtrim(@cAccount),8) in ('21100560','21100660','30800730','30800830','21200560','21200660','30900730','30900830')
/*		(@cNameform = 'ф.0503125 по коду КОСГУ 560(660)') or
        (@cNameform = 'ф.0503125 по коду КОСГУ 730(830)')*/
    begin 
        insert into @table3 (Name_bp, ppp, okato, el_bud, Code_Acc, summa_db, summa_kr, korr_acc,wTab)
        select Name_bp, ppp, okato, el_bud, Code_Acc, coalesce(SUM(summa_db),0.0), coalesce(SUM(summa_kr),0.0), korr_acc,wTab
        from @table2
        where right(rtrim(link),1) like '[0-9]'
        group by Name_bp, ppp, el_bud, okato, Code_Acc, korr_acc,wTab
    end
end

if @IS_RBS = 1 begin
-- внимание, следующий код закомментирован. Поскольку на 2010.10.05 была утрачена его логика. Счета перенесены ниже
/*
    if  right(rtrim(@cAccount),8) in ('30404000','21100560','21100660','21200560','21200660','30800730','30800830','30900730','30900830')
/*		(@cAccount = '130404000' and @cNameform = 'ф.0503125 по коду счета 030404000') or
        (@cNameform = 'ф.0503125 по коду КОСГУ 560(660)') or
        (@cNameform = 'ф.0503125 по коду КОСГУ 730(830)') */
    begin 
        insert into @table3 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd,wTab)
        select 
		z.Name_bp, 
		z.ppp, 
		z.okato, 
		z.el_bud,
		'', 
		z.Code_Acc, 
		coalesce(SUM(z.summa_db),0.0), 
		coalesce(SUM(z.summa_kr),0.0), 
		z.korr_acc,
		(case
			when(
				select count(*) from (select x.dnd from @table2 as x where x.Name_bp = z.Name_bp and x.ppp = z.ppp and x.el_bud = z.el_bud and x.okato = z.okato and x.Code_Acc = z.Code_Acc and x.korr_acc = z.korr_acc and x.wTab = z.wTab group by x.dnd) as y
				) > 1 then ''
			else max(z.dnd)
		end) as dnd,
		z.wTab
        from @table2 as z
        where right(rtrim(link),1) like '[0-9]'
        group by z.Name_bp, z.ppp, z.el_bud, z.okato, z.Code_Acc, z.korr_acc, z.wTab
    end
*/
    if  right(rtrim(@cAccount),8) in ('40120241','40110180')
/*		(@cNameform = 'ф.0503125 по коду КОСГУ 241') or
        (@cNameform = 'ф.0503125 по коду КОСГУ 180')*/
    begin 
--declare @table3 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), dnd tinyint, link varchar(254), wTab tinyint)

        insert into @table3 (Name_bp, ppp, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, wTab, okato, el_bud)
        select 
		/*(case 
			when(
				select count(*) from (select x.Name_bp from @table2 as x where x.ppp = z.ppp and x.KBK = z.KBK and x.Code_Acc = z.Code_Acc and x.korr_acc = z.korr_acc and x.wTab = z.wTab and x.okato = z.okato and x.el_bud = z.el_bud and x.org_synth = z.org_synth group by x.Name_bp) as y
				) > 1 then ''
			else max(*/z.Name_bp/*)
		end) as Name_bp*/,
		z.ppp, 
		z.KBK,
		z.Code_Acc, 
		coalesce(SUM(z.summa_db),0.0), 
		coalesce(SUM(z.summa_kr),0.0), 
		z.korr_acc, 
		(case
			when(
				select count(*) from (select x.dnd from @table2 as x where x.ppp = z.ppp and x.KBK = z.KBK and x.Code_Acc = z.Code_Acc and x.korr_acc = z.korr_acc and x.wTab = z.wTab and x.okato = z.okato and x.el_bud = z.el_bud and x.name_bp = z.name_bp group by x.dnd) as y
				) > 1 then ''
			else max(z.dnd)
		end) as dnd,
		z.wTab, z.okato, z.el_bud
        from @table2 as z
        where right(rtrim(z.link),1) like '[0-9]'
        group by z.ppp, z.KBK, z.Code_Acc, z.korr_acc, z.wTab, z.okato, z.el_bud, z.name_bp  -- имени контрагента не должно быть по инструкции
    end

    if  right(rtrim(@cAccount),8) in ('40120251','20651560','20651660','20721540','20731540','30101810','30212830','40110151','20551560','20551660','30111810','30111810','20731640','20551000','20651000','20711000','20721000','20731000','30111000','30131000','30141000','30151000','30221000','30251830','30251000','30111710',/*внимание! счета перечисленные далее привнесены из закомментированного выше куска кода*/'30404000','21100560','21100660','21200560','21200660','30800730','30800830','30900730','30900830','20711540','20711640', '30406000')
/*		/*@cNameform = 'ф.0503125 по коду КОСГУ 180' or
		@cNameform = 'ф.0503125 по коду КОСГУ 241' or*/

		@cNameform = 'ф.0503125 по коду КОСГУ 251' or  
        @cNameform = 'ф.0503125 по коду счета 120612560(660)' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 540' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 810' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 830' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 151' or 
        @cNameform = 'ф.0503125 по коду счета 120505560(660)' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 710' or 
        @cNameform = 'ф.0503125 по коду КОСГУ 640' or 
        @cNameform = 'ф.0503125 по коду счета 120505000,120612000,120702000' or
        @cNameform = 'ф.0503125 по коду счета 130101000'*/
    begin --Name_bp, ppp, okato, el_bud, Numb_Acc, summa_db, summa_kr, korr_acc, link
        insert into @table3 (Name_bp,ppp,okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, wTab)
        select 
		/*(case 
			when(
				select count(*) from (select x.Name_bp from @table2 as x where x.ppp = z.ppp and x.okato = z.okato and x.el_bud = z.el_bud and x.KBK = z.KBK and x.Code_Acc = z.Code_Acc and x.korr_acc = z.korr_acc and x.wTab = z.wTab and x.org_synth = z.org_synth group by x.Name_bp) as y
				) > 1 then ''
			else max(*/z.Name_bp/*)
		end) as Name_bp*/, 
		z.ppp, 
		z.okato, 
		z.el_bud, 
		z.KBK,
		z.Code_Acc, coalesce(SUM(z.summa_db),0.0), coalesce(SUM(z.summa_kr),0.0),
		z.korr_acc, 
		(case
			when(
				select count(*) from (select x.dnd from @table2 as x where x.ppp = z.ppp and x.el_bud = z.el_bud and x.okato = z.okato and x.KBK = z.KBK and x.Code_Acc = z.Code_Acc and x.korr_acc = z.korr_acc and x.wTab = z.wTab and x.name_bp = z.name_bp group by x.dnd) as y
				) > 1 then ''
			else max(z.dnd)
		end) as dnd,
		z.wTab
        from @table2 as z
        where right(rtrim(z.link),1) like '[0-9]'
        group by z.ppp, z.okato, z.el_bud, z.KBK, z.Code_Acc, z.korr_acc, z.wTab, z.name_bp
    end
end

-- расстановка линков
update @table3
set link =  case
                when link = 'ИП' or link = 'ИН' or link = 'ИД' then
                    replicate('0',9 - len(rtrim(ltrim(cast(nn as varchar(9)))))) + rtrim(ltrim(cast(nn as varchar(9)))) + coalesce(link,'')
                else LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,''))+'           ',11)+RIGHT('00'+RTRIM(LTRIM(ISNULL(el_bud,''))),2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000'+LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
            end
where left(upper(coalesce(link,'')),4) not like 'ИТОГ'

-- select * from @table3

select @j = MIN(nn) from @table3
select @jj = MAX(nn) from @table3

delete from dbo.report_dinamics where link_sf = @varKSsFLink
while @j <= @jj begin
	select @nowTab = wTab from @table3 where nn = @j
    set @i = 1
        if @nowTab in (1,3) begin -- пишем в доходы и источники
            while @i < 11 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 = @nowTab and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @varKSsFLink))
                select 
                    @code_row = link,
                    @float_val =
                    (case when @i in (1,2,3,4,5,6,9,10) 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(ppp,'') as varchar (250))
                          when @i = 3  then cast(coalesce(okato,'') as varchar (250))
                          when @i = 4  then cast(coalesce(el_bud,'') as varchar (250))
                          when @i = 5  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),1,3)
                          when @i = 6  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),4,14)
                          when @i = 9  then cast(coalesce(korr_acc,'') as varchar (250))
                          when @i = 10  then cast(isnull(dnd,'') as varchar (250))
                    end)
                from @table3  
                where nn = @j
        
                insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
                values (@varKSsFLink,@iLink_col,@code_row,@float_val,@str_val)
        
                set @i = @i + 1
            end
        end
        if @nowTab = 2 begin -- пишем в расходы
            while @i < 13 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 = @nowTab and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @varKSsFLink))
                select 
                    @code_row = link,
                    @float_val =
                    (case when @i in (1,2,3,4,5,6,7,8,11,12) then 0.0000 
                          when @i = 9  then coalesce(summa_db,0.0000)
                          when @i = 10 then coalesce(summa_kr,0.0000)
                    end), 
                    @str_val = 
                    (case when @i in (9,10) then '' 
                          when @i = 1  then cast(coalesce(Name_bp,'') as varchar (250))
                          when @i = 2  then cast(coalesce(ppp,'') as varchar (250))
                          when @i = 3  then cast(coalesce(okato,'') as varchar (250))
                          when @i = 4  then cast(coalesce(el_bud,'') as varchar (250))
                          when @i = 5  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),1,3)
                          when @i = 6  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),4,4)
                          when @i = 7  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),8,7)
                          when @i = 8  then substring(rtrim(cast(coalesce(KBK,'') as varchar(250))),15,3)
                          when @i = 11 then cast(coalesce(korr_acc,'') as varchar (250))
                          when @i = 12 then cast(isnull(dnd,'') as varchar (250))
                    end)
                from @table3  
                where nn = @j
        
                insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
                values (@varKSsFLink,@iLink_col,@code_row,@float_val,@str_val)
        
                set @i = @i + 1
            end
        end
        if @nowTab = 4 begin -- /*пишем в итоги*/
            while @i < 9 begin
                select @iLink_col = link_col from dbo.report_coloumns where Orders = @i and Link_Table = (select link_table from dbo.report_tables where Orders = @nowTab and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @varKSsFLink))
                select 
                    @code_row = link,
                    @float_val =
                    (case when @i in (1,2,3,4,5,8) then 0.0000 
                          when @i = 6 then coalesce(summa_db,0.0000)
                          when @i = 7 then coalesce(summa_kr,0.0000)
                    end), 
                    @str_val = 
                    (case when @i in (6,7) then '' 
                          when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
                          when @i = 2 then cast(coalesce(ppp,'') as varchar (250))
                          when @i = 3 then cast(coalesce(okato,'') as varchar (250))
                          when @i = 4 then cast(coalesce(el_bud,'') as varchar (250))
                          when @i = 5 then cast(coalesce(Code_acc,'') as varchar (250))
                          when @i = 8 then cast(coalesce(korr_acc,'') as varchar (250))
                    end)
                from @table3 
                where nn = @j
        
                insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
                values (@varKSsFLink,@iLink_col,@code_row,@float_val,@str_val)
        
                set @i = @i + 1
            end
        end


    set @j = @j + 1
end

--обновим atr
--declare @cstr varchar(250),@cstr2 varchar(250)
--set @cstr=left(dbo.rn_get_atr_val(@varKSsFLink,0,0),250) 
--set @cstr2=left(dbo.rn_get_atr_val(@varKSsFLink,0,1),250) 
--update report_saved_forms
--set atr =@cstr,atr_code=@cstr2
--where link_saved_form=@varKSsFLink

exec RN_SPLIT_CODE_ROW @varKSsFLink

drop table #report_dinamics

return 0
GO
GRANT EXECUTE ON dbo.[RT_SVOD_0503125M_2011] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_DATA]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_DATA]
END
GO
-- Процедура экспорта раздела(ов) данных формы.
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_DATA]
	@iLINK_SAVED_FORM	INT,	                      -- Линк выгружаемой формы	
   @tTABLE_ORDER    TINYINT = NULL,             -- NULL - все таблицы, порядковый номер таблицы.
	@iMODE	        INT = 2,                    -- Формат: 1-внутренний, 2-МФ (стандартный), 3 - МФ (для пятисотых форм).
	@vcTableName     VARCHAR(50) = '#tabExport', -- Таблица для получения результата.
	@vcFilter        VARCHAR(8000) = NULL,       -- Фильтр на временную таблицу (#tabRI_PROC_T).
	@vcFilterTotal   VARCHAR(8000) = NULL,       -- Фильтр на результирующие строки.	
	@iRD_DELTA       INT = 0,                    -- Смещение для номеров разделов данных РД(ТБ), NULL - исключительно строки с данными.
	@bLAST_DELIMITER BIT = 1,                    -- 1 - ставить терминальный символ '|' в строках с данными, 0 - иначе.	
	@vcRD_NAME       VARCHAR(10) = NULL,         -- Заголовок раздела, NULL - автоматически (внутренний формат - РД, формат МФ - ТБ).
	@bSPECIAL_SIGNS  BIT = 1,                    -- Только для формата МФ. 0 - не испльзовать спец. знаки (#,#@,#$) для разделения разделов данных, 1 - иначе.
	@iRD_WIDTH       INT = 2                     -- Только для формата МФ. Ширина в символах до которой надо дополнять номер РД. По умолчанию 2, т.е. будет ТБ=01,02...09
AS

SET NOCOUNT ON

CREATE TABLE #IMPORT_TABLE([TXT]   VARCHAR(1000), 
                           [ORDER] INT IDENTITY(1, 1))	   

DECLARE @i INT,
        @ltMAX_COL_ORDERS TINYINT,
        @lvcCOL           VARCHAR(10),
        @lvcReplace       VARCHAR(250),

        @lbDELETE_PARAM_EXPORT BIT,        
        @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),   
   
        @liError           INT, 
        @lvcTXT            VARCHAR(8000), 
        @lvcTableHeader    VARCHAR(8000), 
        @lvcExecTable      VARCHAR(8000), 
        @liORDERS          INT, 
        @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,
        @ltCOL_VAL_LEN        INT,
        @ltCOL_ISEDITED       TINYINT,
        @ltCOL_ISEXPORTED     TINYINT,
        @ltPERIOD_TYPE        TINYINT,
        @lvcDICTIONARY_COLUMNS_LIST VARCHAR(250),

        @lvcExec	            VARCHAR(8000),

        @liPosition  INT     

IF @iRD_WIDTH IS NULL OR 
   @iRD_WIDTH<1
BEGIN
   SET @iRD_WIDTH = 1
END

IF @iMode=3
BEGIN
   SELECT @iMode = 2,
          @bLAST_DELIMITER = 0,
          @vcRD_NAME='РД',
          @iRD_WIDTH = 1,
          @bSPECIAL_SIGNS = 0          
END

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           = [C].[OUTCODE]
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 @iMode = 2 AND 
   OBJECT_ID('tempdb..#tabPARAM_EXPORT') IS NULL
BEGIN   
   CREATE TABLE  #tabPARAM_EXPORT ([TXT]         VARCHAR(1000), 
                                   [TABLE_ORDER] INT IDENTITY(1,1))
   SET @lbDELETE_PARAM_EXPORT = 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

CREATE TABLE #tabExcludeCodes([LINK_TABLE] INT,
                              [CODE]       VARCHAR(250))
                        
INSERT #tabExcludeCodes([LINK_TABLE],
                        [CODE])                           
EXEC [RA_EXPORT_FORM_GET_EXCLUDE_CODES] @liFORM_LINK

-- Выгрузка части с данными.
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 [A].[LINK_FORM] = @liFORM_LINK AND
         (@tTABLE_ORDER IS NULL OR 
          [A].[ORDERS] = @tTABLE_ORDER)

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
	SET @lvcTXT = ''

   IF @iMode = 1 OR
      (@iMode = 2 AND @lbIsEmpty = 1)
   BEGIN   
      SELECT @lvcTXT = @lvcTXT + 
                       'C' +
/*      
                       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]
      
      IF LEN(@lvcTXT)>0
      BEGIN
         SET @lvcTXT = LEFT(@lvcTXT,LEN(@lvcTXT)- (CASE @bLAST_DELIMITER 
                                                     WHEN 1 THEN 1
                                                     ELSE 5
                                                   END)) -- "откусываем" '+' либо '+'|'+'
      END

--      select @lvcTXT 
   END
   ELSE BEGIN
   	SELECT @lvcTXT = REPLACE([TXT],'COL','C')
      FROM #tabPARAM_EXPORT 
      WHERE [TABLE_ORDER] = @liTABLE_ORDER
   END
   
	IF LEN(ISNULL(@lvcTXT, '')) > 0
	BEGIN
	   IF @iRD_DELTA IS NOT NULL
	   BEGIN
         IF @iMode = 1
         BEGIN
   		   INSERT #IMPORT_TABLE 
            SELECT [TXT] = ISNULL(@vcRD_NAME,'РД')+'=' + LTRIM(CONVERT(VARCHAR(2),@liTABLE_ORDER + @iRD_DELTA))             
         END
         ELSE BEGIN
   		   IF @bSPECIAL_SIGNS=1 
      		   BEGIN
   		      INSERT #IMPORT_TABLE([TXT]) SELECT '#@'
   		   END
   		   
   		   INSERT #IMPORT_TABLE([TXT]) SELECT ISNULL(@vcRD_NAME,'ТБ')+'='+ RIGHT(RTRIM('0' + LTRIM(CONVERT(CHAR(2),@liTABLE_ORDER + @iRD_DELTA))),@iRD_WIDTH)
   		   
   		   IF @bSPECIAL_SIGNS=1 
   		   BEGIN
      		   INSERT #IMPORT_TABLE([TXT]) SELECT '#$'
      		END
         END
      END         
/*
		SELECT @liLINK_CODE_COL = [LINK_CODE_COL]
      FROM dbo.[REPORT_TABLES]
      WHERE [LINK_TABLE] = @liTABLE_LINK
*/
		SELECT @lvcExecTable = 'CREATE TABLE #tabRI_PROC_T ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] ' + 
                             CASE 
                                WHEN [A].[COL_TYPE] = 1 THEN 'VARCHAR(50)' 
                                ELSE 'FLOAT' 
                             END
		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

      SELECT @lvcTXTDataNotNull = '1=2',
             @lvcTableHeader = ''

   	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] DESC

		OPEN tabColumns

		FETCH 
      NEXT FROM tabColumns
		INTO @liCOL_LINK, 
           @liCOL_TYPE, 
           @liORDERS, 
           @ltCOL_VAL_LEN, 
           @ltCOL_ISEDITED,
           @ltCOL_ISEXPORTED
      
--      print '----------------------'
   
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @lvcTableHeader = ', COL' + LTRIM(STR(@liORDERS)) + 
                             CASE 
                                WHEN @liCOL_TYPE = 1 THEN ' VARCHAR(250)' 
                                ELSE ' NUMERIC(20,' + LTRIM(STR(@ltCOL_VAL_LEN)) + ')' 
                             END  + @lvcTableHeader


--         print @ltCOL_ISEXPORTED

			IF @ltCOL_ISEXPORTED = 1 AND 
			   @liORDERS <> @ltORDER_CODE_COL 
			   -- AND @lvcDICTIONARY_COLUMNS_LIST not like '%COL' + LTRIM(STR(@liORDERS)) + ',%'
			BEGIN			
			   IF @liCOL_TYPE = 0
			   BEGIN
				   SET @lvcTXTDataNotNull = @lvcTXTDataNotNull +                                       
                                        ' OR COL' + LTRIM(STR(@liORDERS)) + ' <> 0'
			   END
			   ELSE BEGIN
				   SET @lvcTXTDataNotNull = @lvcTXTDataNotNull +                                       
                                        ' OR COL' + LTRIM(STR(@liORDERS)) + ' <> '''''
			   END
			END
         
         SELECT @lvcCOL = LTRIM(STR(@liORDERS)),         
                @lvcTXT = REPLACE(@lvcTXT,'C'+@lvcCOL,CASE @liCOL_TYPE
                                                     WHEN 0 THEN 'ISNULL(CAST(COL'+@lvcCOL+' AS VARCHAR(20)),''0.' + REPLICATE('0',@ltCOL_VAL_LEN) + ''')'
                                                     ELSE 'RTRIM(ISNULL(COL'+@lvcCOL+',''''))'
                                                  END)
                                                  
--         print @lvcCOL
--         print @lvcTXT
         
         
         
		   FETCH 
         NEXT FROM tabColumns
		   INTO @liCOL_LINK, 
              @liCOL_TYPE, 
              @liORDERS, 
              @ltCOL_VAL_LEN, 
              @ltCOL_ISEDITED,
              @ltCOL_ISEXPORTED
		END

		CLOSE tabColumns
		DEALLOCATE tabColumns

		IF @liTABLE_VAL_TYPE = 0
      BEGIN
			SET @lvcExecTable = @lvcExecTable + @lvcTableHeader + ',[ITOG] TINYINT)'
      END
		ELSE BEGIN
			SET @lvcExecTable = @lvcExecTable + @lvcTableHeader + ')'
      END

		SET @lvcExec = @lvcExecTable + CHAR(13) +
                     ' INSERT #tabRI_PROC_T exec dbo.[RI_PROC_T' + 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)) + ',' + 
                                                              ISNULL('''' + REPLACE(@vcFilter,'''','''''') + '''','NULL') + ',1'
                                                              
                                                              
--+ ' select * from #tabRI_PROC_T' 
      END
/*      
      SELECT @ltMAX_COL_ORDERS = MAX([ORDERS])
      FROM dbo.[REPORT_COLOUMNS]
      WHERE [LINK_TABLE] = @liTABLE_LINK


      SET @i = 1
      WHILE @i<=@ltMAX_COL_ORDERS
      BEGIN
         SELECT @lvcCOL = 'COL'+LTRIM(STR(@i)),
               @i = @i+1
         SET @lvcTXT = REPLACE(@lvcTXT,@lvcCOL,'ISNULL(CAST('+@lvcCOL+' AS VARCHAR(20)),'''')')
      END
  */    
      SET @lvcExec = @lvcExec + CHAR(13) +      
                     ' INSERT #IMPORT_TABLE([TXT]) SELECT ' + REPLACE(@lvcTXT, 'STR(', '('/*'CONVERT(VARCHAR(20), '*/) + ' FROM #tabRI_PROC_T WHERE ' + @lvcTXTDataNotNull + CHAR(13) +
                     ' DROP TABLE #tabRI_PROC_T'

--      print @lvcDICTIONARY_COLUMNS_LIST

-- 		print @lvcExec      
 		EXEC(@lvcExec) 		


		IF @iMODE = 2 AND 
		   @iRD_DELTA IS NOT NULL AND
         @bSPECIAL_SIGNS=1 
      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

EXEC dbo.[RA_IMPORT_FORM_REPLACE_DATA] @tMode = 2,
                                       @cCODE_FORM = @lcFORM_CODE,
                                       @iLINK_SAVED_FORM = @iLINK_SAVED_FORM

SET @lvcExec = 'INSERT ' + @vcTableName + '([TXT]) SELECT [TXT] = RTRIM([TXT]) FROM #IMPORT_TABLE ' 

IF @vcFilterTotal IS NOT NULL
BEGIN
   SET @lvcExec = @lvcExec + 'WHERE ' + @vcFilterTotal
END

SET @lvcExec = @lvcExec + ' ORDER BY [ORDER]'

--print @lvcExec
EXEC(@lvcExec)

DROP TABLE #IMPORT_TABLE 

IF @lbDELETE_PARAM_EXPORT = 1
BEGIN
   DROP TABLE #tabPARAM_EXPORT
END

GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_DATA] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*


EXEC dbo.[RA_EXPORT_FORM_DATA] 11936, 1,DEFAULT,10

ra_test_fill_form '(36н)580'
select * from report_saved_forms order by link_saved_form desc

drop table #tabRI_PROC_T 
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] VARCHAR(50), COL1 VARCHAR(250), COL2 VARCHAR(250), COL3 NUMERIC(20,1), COL4 NUMERIC(20,1), COL5 NUMERIC(20,1), COL6 NUMERIC(20,1), COL7 NUMERIC(20,1),[ITOG] TINYINT)
 INSERT #tabRI_PROC_T exec dbo.[RI_PROC_T4614] @DEL_FCOL=1, @varKSLSF=11936
 EXEC dbo.[RA_EXPORT_FORM_UPDATE] 4614
 INSERT #IMPORT_TABLE([TXT]) SELECT RTRIM(COL2)+'|'+CONVERT(VARCHAR(20), COL3)+'|'+CONVERT(VARCHAR(20), COL4)+'|'+CONVERT(VARCHAR(20), COL5)+'|'+CONVERT(VARCHAR(20), COL6)+'|' FROM #tabRI_PROC_T WHERE 1=2 OR COL3 <> 0 OR COL4 <> 0 OR COL5 <> 0 OR COL6 <> 0
 DROP TABLE #tabRI_PROC_T
 
  select * from report_forms where code='(36н)580'
 select * from report_tables where link_form=1687
 sp_helptext RI_PROC_T4614
 
 select * from report_
*/

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS]

GO

CREATE    PROCEDURE [dbo].SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS 
/*Для расчетов по больничным листам*/
 @varKSRefPay 	int,
 @varKSlinkEmpl	 int,
 @varKSMonth	int,
 @varKSYear	int,
 @MODE INT = 0 --определяет вид операции @varKSRefPay, для которого ищется база - начисление(0) или отчисление(1)
AS  
declare @varKSdDate1 datetime, @varKSdDate2 datetime

CREATE TABLE #SJC (LINK_PAYS INT, WAY_CALC TINYINT, CODE_PAYS VARCHAR(10), NAME_PAYS VARCHAR(60), SUMMA NUMERIC(18,2), 
					LINK_INC INT, LINK_VKR INT, DATE1 DATETIME, DATE2 DATETIME,
					LINK_DOC INT, LINK_EMPL INT, PERIOD_BEGIN DATETIME)

CREATE TABLE #GROUP_PAYS (PAY_LINK INT, PERIOD INT, KOEF NUMERIC(18,10), LINK_GRP INT)
INSERT INTO #GROUP_PAYS (PAY_LINK, PERIOD, KOEF, LINK_GRP)
SELECT PAY_LINK, PERIOD, KOEF, LINK_GRP FROM dbo.group_pays(@varKSRefPay)

IF @MODE = 0
	INSERT INTO #SJC (LINK_PAYS, WAY_CALC, CODE_PAYS, NAME_PAYS, SUMMA, LINK_INC, LINK_VKR, DATE1, DATE2, LINK_DOC, LINK_EMPL, PERIOD_BEGIN)
	SELECT SJ.LINK_PAYS, SJ.WAY_CALC, SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.SUMMA, SJ.LINK_INC, SJ.LINK_VKR, SJ.DATE1, SJ.DATE2, SJ.LINK_DOC, SJ.LINK_EMPL, SJ.PERIOD_BEGIN
	FROM 
		dbo.S_J_C_Short SJ
		INNER JOIN #GROUP_PAYS T ON SJ.link_PAYS=T.PAY_LINK 
	WHERE 
		SJ.LINK_EMPL = @varKSlinkEmpl
	
ELSE
	INSERT INTO #SJC (LINK_PAYS, WAY_CALC, CODE_PAYS, NAME_PAYS, SUMMA, LINK_INC, LINK_VKR, DATE1, DATE2, LINK_DOC, LINK_EMPL, PERIOD_BEGIN)
	SELECT SJ.LINK_PAYS, SJ.WAY_CALC, SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.SUMMA, SJ.LINK_INC, SJ.LINK_VKR, SJ.DATE1, SJ.DATE2, SJ.LINK_DOC, SJ.LINK_EMPL, SJ.PERIOD_BEGIN
	FROM 
		dbo.S_J_C_Short SJ
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @varKSRefPay 
		AND LINK_EMPL = @varKSlinkEmpl

if @varKSMonth<1 or @varKSMonth>12
	return -1
SET @varKSdDate1 = convert(datetime,'01.'+str(@varKSMonth)+'.'+str(@varKSYear),104)
SET @varKSdDate2 =DATEADD(M,1,@varKSdDate1) -1

--------
CREATE TABLE #KU_EmplStafKBK (LINK_EMPL INT, LINK_KBK INT)
INSERT INTO #KU_EmplStafKBK (LINK_EMPL, LINK_KBK)
SELECT LINK_EMPL, LINK_KBK FROM dbo.KU_EmplStafKBK(default) WHERE LINK_EMPL = @varKSlinkEmpl

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

--------
SELECT 			
			[CODE_PAY] = CODE_PAYS,
			[NAME_PAY] = NAME_PAYS,
			[WAY_CALC],
			SJ.link_PAYS as [LINK_PAY],
			SUM(SJ.summa) as [SUMMA],
			KOEF = 0,
			LINK_INC, LINK_VKR = COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2
INTO #TMP
FROM 
	#SJC SJ
	LEFT JOIN #KU_EmplStafKBK DEF ON DEF.LINK_EMPL = SJ.LINK_EMPL	
	--суммы по перерасчету будем учитывать в месяце, за который перерасчитывали, если они начислены в том же году
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP
WHERE 
	SJ.LINK_EMPL = @varKSlinkEmpl 
	AND 
	(
		(COALESCE(R.LINK_UP,0) = 0 AND SJ.WAY_CALC in (6,7) OR @DOCUMENTS_RECALC_OPT1=2) AND YEAR(SJ.PERIOD_BEGIN) = @varKSYear AND MONTH(SJ.PERIOD_BEGIN) = @varKSMonth
		OR
		NOT (COALESCE(R.LINK_UP,0) = 0 AND SJ.WAY_CALC in (6,7) OR @DOCUMENTS_RECALC_OPT1=2) AND YEAR(SJ.DATE1) = @varKSYear AND MONTH(SJ.DATE1) = @varKSMonth
	)
GROUP BY  
	SJ.link_PAYS, LINK_INC, CODE_PAYS, NAME_PAYS, WAY_CALC, COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2


IF dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT3') = 1
BEGIN
	
	/*
	Игнатьев А.Н. 2007-02-05
		В соответствии с ФЗ "255-ФЗ от 29.12.2006 ст.14, п.2
		Учитываем доходы, с которых уплачивались взносы в ФСС.
		Мат. помощь и пр. доходы, на которые предоставляется льгота 3000р. берем за минусом этой льготы
	*/
	
	CREATE TABLE #SPR_PREDEL (LINK_PAY INT, SUMMA NUMERIC(18,2) )
	INSERT INTO #SPR_PREDEL (LINK_PAY, SUMMA)
	SELECT REF_PAY, PREDEL FROM dbo.Salary_deduct_esn(@varKSdDate1) 
	
	DECLARE @SPR TABLE (LINK_PAY int, LINK_DOH int, LINK_VYCH int, PREDEL numeric(18,2))

	/*Справочник пределов льгот*/
	insert into @SPR(LINK_PAY, LINK_DOH, LINK_VYCH, PREDEL)
	select DISTINCT LINK_PAY= P.link, LINK_DOH= DTI.LINK, LINK_VYCH= SDE.LINK_PAY,  SUMMA from dbo.pays P inner join dbo.DICTIONARY_TYP_INCOMS DTI on P.link_inc = DTI.link 
		inner join #SPR_PREDEL SDE on SDE.LINK_PAY = DTI.REF_DEDUCT

	/*Для каждого кода дохода рассчитывается остаток льготы*/

	DECLARE @PREDEL0 TABLE (LINK_DOH int, PREDEL numeric(18,2))
	INSERT INTO @PREDEL0 (LINK_DOH, PREDEL)
	SELECT DISTINCT LINK_DOH, PREDEL FROM @SPR

	CREATE TABLE #MAT_POM (DATE1 DATETIME, LINK_DOH INT, SUMMA NUMERIC(18,2))
	INSERT INTO #MAT_POM (DATE1, LINK_DOH, SUMMA)
	SELECT SJC.DATE1, SJC.LINK_INC, SUM(SJC.SUMMA)
	FROM 
		#SJC SJC
	WHERE 
		YEAR(SJC.DATE1) = @varKSYear AND SJC.DATE2 <= @varKSdDate2
		AND
		EXISTS (SELECT * FROM @SPR WHERE LINK_DOH = LINK_INC)
	GROUP BY 
		SJC.DATE1, SJC.LINK_INC

	DECLARE @Cur CURSOR, @Cur0 CURSOR, @DATE1 DATETIME, @LINK_D1 INT, @PREDEL1 NUMERIC(18,2)
	SET @Cur = CURSOR FORWARD_ONLY
	FOR SELECT DISTINCT LINK_DOH FROM #MAT_POM ORDER BY LINK_DOH
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @LINK_D1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			SET @PREDEL1 = ISNULL((SELECT TOP 1  PREDEL FROM @PREDEL0 WHERE LINK_DOH = @LINK_D1),0)

			SET @Cur0 = CURSOR FORWARD_ONLY
			FOR SELECT DATE1 FROM #MAT_POM WHERE LINK_DOH = @LINK_D1 ORDER BY LINK_DOH
			OPEN @Cur0
			FETCH NEXT FROM @Cur0 INTO @DATE1
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					UPDATE #MAT_POM 
					SET SUMMA = CASE WHEN SUMMA >= @PREDEL1 THEN @PREDEL1 ELSE SUMMA END
					WHERE DATE1 =  @DATE1 AND LINK_DOH = @LINK_D1

					SET @PREDEL1 = @PREDEL1 - ISNULL((SELECT SUM(SUMMA) FROM #MAT_POM WHERE LINK_DOH = @LINK_D1 AND DATE1 <= @DATE1),0)
				
				END
				FETCH NEXT FROM @Cur0 INTO @DATE1
			
			END	
			CLOSE @Cur0
			DEALLOCATE @Cur0
			
		
		END
		FETCH NEXT FROM @Cur INTO @LINK_D1
	
	END	
	CLOSE @Cur
	DEALLOCATE @Cur

	----------------------------------------------
	
	DECLARE @PREDEL TABLE (LINK_DOH int, PREDEL numeric(18,2))

	INSERT INTO @PREDEL (LINK_DOH, PREDEL)
	SELECT LINK_DOH, SUMMA FROM #MAT_POM WHERE YEAR(DATE1) = @varKSYear AND MONTH(DATE1) = @varKSMonth

	/*Для каждого вида дохода с льготой*/
	DECLARE @Cur1 CURSOR, @LINK_DOH int, @PREDEL_SUM numeric(18,2), @Cur2 CURSOR, @LINK_PAY INT, @SUMMA1 numeric(18,2)
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR Select * from @PREDEL where PREDEL > 0
		
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
	
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR Select LINK_PAY, SUMMA from #tmp where LINK_INC = @LINK_DOH and summa > 0
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_PAY, @SUMMA1
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN	
				
					/*Уменьшаем сумму начисления на сумму льготы, т.к. со суммы льготы не отчислялии в ФСС*/
					UPDATE #tmp SET SUMMA = (CASE WHEN @PREDEL_SUM > 0  THEN
												CASE WHEN SUMMA > @PREDEL_SUM THEN 
													SUMMA - @PREDEL_SUM
												ELSE
													0
												END		
											 ELSE SUMMA 
											 END) 
											 WHERE LINK_PAY = @LINK_PAY
					
					/*Рассчитаем остаток льготы*/
					SET @PREDEL_SUM = @PREDEL_SUM - (Select @SUMMA1 - SUM(SUMMA) from #tmp where LINK_PAY = @LINK_PAY)
		
				END
				FETCH NEXT FROM @Cur2 INTO @LINK_PAY, @SUMMA1
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END
		FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1
END

SELECT * FROM #TMP ORDER BY REPLACE(STR(CODE_PAY,10),' ', 0)



GO


GRANT EXECUTE ON dbo.[SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[web_sign_DocsSign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[web_sign_DocsSign]
GO




/*
© Кейсистемс (Keysystems), 2005
процедура привязки электронной подписи к документу
*/

CREATE   
procedure dbo.web_sign_DocsSign
	@cDocCode varchar(200), -- код объекта
	@xmlLinks text, -- xml с линками
	@out varchar(100) = null output,
	@cTableLinks varchar(100) = '' -- название таблицы с линками если не передали в @xmlLinks
AS
begin

DECLARE @hDoc int, @xpath varchar(1000), @nDocCode int, @nDigSig int, @nErr int, @link int, @varKSEventStr varchar(1000), @varKSLink_Task int

create table #docs(link int, signature varchar(6000))

if (@xmlLinks is not null)
begin
	exec sp_xml_preparedocument @hDoc OUTPUT,@xmlLinks

	insert #docs (link, signature)
	select link, signature
	FROM OPENXML(@hDoc, 'Links/Link', 2)
	WITH (	link int '@Link',
		signature varchar(6000) '@Signature') 

	EXEC sp_xml_removedocument @hDoc
end
else
begin
	exec('insert #docs (link, signature) select link, [sign] from ' + @cTableLinks)
end

update report_sign
set date = getdate(),
	[sign] = d.signature
from #docs d
where [sid] = suser_sid() and LSF = d.link

insert report_sign(lsf, [sign], text_for_sign)
select link, [signature], ''
from #docs D
where not exists(select top 1 * from report_sign S where S.[sid] = suser_sid() and S.lsf = D.link)

update report_sign
set text_for_sign = txt,
   type_who = dbo.RO_SignWhat(T.LSF)
from report_sign_txt T JOIN  #docs d ON T.lsf = d.link
where report_sign.[sid] = suser_sid() and report_sign.LSF = T.LSF AND T.[sid] = SUSER_SID()

declare cur_lsf cursor local static for select link from #docs

open cur_lsf

fetch next from cur_lsf into @link

while @@fetch_status = 0
begin
   select @varKSEventStr = 'Отчет: ' + rtrim(RF.code) + ' ' + atr + ' Период: ' + 
	      convert(char(4),year(BEGIN_DATE)) + ' год ' + 
	      case period_Type when 2 then convert(char(1),period_number) + ' квартал'
		      when 4 then convert(char(2),period_number) + ' месяц'
	      ELSE '' end + ' Версия:' +  convert(char(3),RSF.version) + ' Организация: ' + D.Code + ' Бюджет: ' + isnull(B.Name, '')
   from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
      left join departments D on D.link = RSF.link_organization 
      left join kl_budg_type B on B.link = RSF.link_type_svod
   where link_saved_form = @link

   select @varKSEventStr = 'Пользователь ' + isnull(FIO, '') + ' ' + isnull(Name,'') + '. ' + @varKSEventStr
   from dbo.db_users
   where uid = dbo.AdminGetUidBySiD(suser_sid())

   exec dbo.WF_GENERATEEVENT 'Подпись', @varKSEventStr, @varKSLink_Task, 'REPORT_SIGN', @link

   fetch next from cur_lsf into @link
end

close cur_lsf
deallocate cur_lsf

/*
update dbo.report_saved_forms 
set signature = d.signature
from #docs d
where link_saved_form = d.link
*/

set @out = 'Документы подписаны.'

end

GO

GRANT ALL ON dbo.[web_sign_DocsSign] 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.[BK_GET_DATA_NOMEN_FOR_STIKER]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_GET_DATA_NOMEN_FOR_STIKER]

GO
CREATE PROCEDURE dbo.BK_GET_DATA_NOMEN_FOR_STIKER
	(@strBUFFER VARCHAR (8000),
	@dDATE_PRINT	DATETIME = NULL,
	@intSHORT_DESC	INT = 0)
AS
BEGIN
	DECLARE @strFILE_NAME VARCHAR (254),
		@intDEP_LINK INT

	IF @dDATE_PRINT IS NULL
		SET @dDATE_PRINT = (SELECT WORKDATE FROM dbo.USER_INFO)
	
	SET @dDATE_PRINT = DATEADD (DAY, 1, @dDATE_PRINT)

	CREATE TABLE #TAB_REST_INV (DEP_LINK INT, INV INT, EMP INT)
	
	SET @strFILE_NAME = ''

	SET @intDEP_LINK = dbo.GetOwnDepLink ()
	
	SELECT BUF.LINK AS INV_LINK,
		'2' AS INV_TYPE,
		INV.CODE AS INV_CODE,
		INV.[NAME] AS INV_NAME,
		DEP.[CODE] AS DEP_CODE,
		DEP.[NAME] AS DEP_NAME,
		DEP.INN AS DEP_INN,
		0 AS EMP, '' AS EMP_CODE, '' AS EMP_NAME,
		'' AS PLANT_NUM,
		@strFILE_NAME AS FNAME
	FROM dbo.BufferGetTableByID (@strBUFFER) BUF
	INNER JOIN dbo.NOMENCLATURE INV ON (INV.LINK = BUF.LINK)
	INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = @intDEP_LINK)
	
	DROP TABLE #TAB_REST_INV

	EXEC dbo.BufferClear @strBUFFER
END



GO


GRANT EXECUTE ON dbo.[BK_GET_DATA_NOMEN_FOR_STIKER] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_ISP_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_ISP_SAVE]
GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.[SD_ISP_SAVE]
	@varKSparLINK		int	OUTPUT,
	@varKSparNumber		varchar(15) = null,
	@varKSparDate		datetime = null,
	@varKSparRefPay		int = null,
	@varKSparComments	varchar(100) = '',
	@varKSparREF_EMPL	int = null,
	@varKSparREF_ORGANIZATION	int = null,
	@varKSparSumma		numeric(15,4) = 0.0,	
	@varKSparDate1		datetime = null,
	@varKSparDate2		datetime = null,
	@varKSparPayment		int = null,
	@varKSparWay			int = null,
	@varKSparSum_Enum	numeric(15,2) = 0.0,
	@varKSparPERCENT		numeric(10,2) = 0.0,
	@varKSparSumma_Need	numeric(15,2) = 0.0,
	@varKSparRefPayP		int = null,
	@varKSparRefOrgP		int = null,
	@varKSparLinkVKR		int = NULL,
	@varKSparINO			tinyint = 0,
	@linkDep int,
	@PERC_SFIN TINYINT = 0,
	@NO_NDFL TINYINT = 0,
	@BY_EKR TINYINT = 0
		
		
		
as
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int, 	@varKSPeriodLink  int, @varKSsoLink int, @varKSRowCount INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


IF @varKSparNumber IS NULL OR @varKSparNumber = '' or @varKSparDate IS NULL or @linkDep is null or @linkDep = 0
BEGIN
	ROLLBACK
	RETURN 5
END

IF @varKSparRefPayP = 0
	SET @varKSparRefPayP = NULL
IF @varKSparRefOrgP = 0
	SET @varKSparRefOrgP = NULL

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'DOCUMENTS_KADR_WRIT'
EXECUTE @varKSERROR = SALARY_UPD_SDOC @varKSparLINK OUTPUT, @varKSsoLink, @varKSparNumber,@varKSparDate,@varKSparComments,0, default, default, @linkDep
IF @varKSERROR <> 0
	RETURN @varKSERROR

IF not exists(select link_up from SDOC_WRIT  where link_up =@varKSparLINK)
	BEGIN
		INSERT INTO SDOC_WRIT WITH (ROWLOCK) (LINK_UP,LINK_PAY,LINK_EMPL,LINK_ORG,DATE1,DATE2,SUMMA,PAYMENT,WAY,SUM_ENUM,
														PERC,SUMMA_NEED,LINK_ORGP,LINK_PAYP,LINK_VKR,INO, PERC_SFIN, NO_NDFL, BY_EKR) 
			VALUES (	@varKSparLINK, @varKSparRefPay,
						@varKSparREF_EMPL,
						@varKSparREF_ORGANIZATION,
						@varKSparDate1,
						@varKSparDate2,
						@varKSparSumma,
						@varKSparPayment,
						@varKSparWay, 
						@varKSparSum_Enum, 
						@varKSparPERCENT,
						@varKSparSumma_Need, 
						@varKSparRefOrgP,
						@varKSparRefPayP, 	
						@varKSparLinkVKR,
						@varKSparINO,
						@PERC_SFIN,
						@NO_NDFL,
						@BY_EKR )
						
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE SDOC_WRIT WITH (ROWLOCK) 
		SET 	LINK_PAY = @varKSparRefPay,
				LINK_EMPL =@varKSparREF_EMPL ,
				LINK_ORG = @varKSparREF_ORGANIZATION,
				DATE1 = @varKSparDate1,
				DATE2 = @varKSparDate2,
				SUMMA =@varKSparSumma ,
				PAYMENT =@varKSparPayment ,
				WAY = @varKSparWay,
				SUM_ENUM =@varKSparSum_Enum ,
				PERC =@varKSparPERCENT ,
				SUMMA_NEED = @varKSparSumma_Need,
				LINK_ORGP = @varKSparRefOrgP,
				LINK_PAYP = @varKSparRefPayP,
				LINK_VKR = @varKSparLinkVKR,
				INO = @varKSparINO,
				PERC_SFIN = @PERC_SFIN,
				NO_NDFL = @NO_NDFL,
				BY_EKR = @BY_EKR
		WHERE LINK_UP=@varKSparLINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END


declare @varKSEventText varchar(200)
SET @varKSEventText = 'Исполнительный лист № ' + RTRIM(LTRIM(convert(varchar(10),@varKSparNumber))) + ' от ' + CONVERT(VARCHAR(10),@varKSparDate,104)
EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSsoLink, 'SDOC',@varKSparLINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0


GO


GRANT EXECUTE ON dbo.[SD_ISP_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV4_SVEDENIA_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV4_SVEDENIA_SAVE]

GO

CREATE   PROCEDURE dbo.SA_SZV4_SVEDENIA_SAVE
	@LINK		int,
	@link_up	int,
	@pachka		int,
	@orders		int,
	@link_pers	int,
	@sum_doh	numeric(18,2) = 0,
	@sum_str	numeric(18,2) = 0,
	@sum_nak	numeric(18,2) = 0,
	@sum_dop	numeric(18,2) = 0,
	@dper_vn_m	numeric(18,2) = 0,
	@dper_vn_d	numeric(18,2) = 0,
	@dper_oz_m	numeric(18,2) = 0,
	@dper_oz_d	numeric(18,2) = 0,
	@isum_str	numeric(18,2) = 0,
	@isum_nak	numeric(18,2) = 0,
	@sum_dolg_str	numeric(18,2) = 0,
	@sum_uplata_dolga_str	numeric(18,2) = 0,
	@sum_dolg_nak	numeric(18,2) = 0,
	@sum_uplata_dolga_nak	numeric(18,2) = 0
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int, @varKSRowCount INT, @varKSsoLink int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


IF coalesce(@link_up,0) = 0 or coalesce(@orders,0) = 0 or coalesce(@link_pers,0) = 0
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV4_SVEDENIA'

IF @LINK is null OR @LINK = 0
	BEGIN

		INSERT INTO dbo.SZV4_SVEDENIA WITH (ROWLOCK) (link_up, pachka, orders, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d, dper_oz_m, dper_oz_d, isum_str, isum_nak, sum_dolg_str, sum_uplata_dolga_str, sum_dolg_nak, sum_uplata_dolga_nak) 
			VALUES (@link_up, @pachka, @orders, @link_pers, @sum_doh, @sum_str, @sum_nak, @sum_dop, @dper_vn_m, @dper_vn_d, @dper_oz_m, @dper_oz_d, @isum_str, @isum_nak, @sum_dolg_str, @sum_uplata_dolga_str, @sum_dolg_nak, @sum_uplata_dolga_nak)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN

		UPDATE dbo.SZV4_SVEDENIA WITH (ROWLOCK) 
		SET 	link_up =@link_up, pachka = @pachka, orders =@orders, link_pers =@link_pers, sum_doh =@sum_doh, sum_str = @sum_str, 
			sum_nak =@sum_nak, sum_dop = @sum_dop, dper_vn_m = @dper_vn_m, dper_vn_d =@dper_vn_d, dper_oz_m =@dper_oz_m, 
			dper_oz_d =@dper_oz_d, isum_str =@isum_str, isum_nak = @isum_nak,
			sum_dolg_str = @sum_dolg_str, sum_uplata_dolga_str = @sum_uplata_dolga_str, sum_dolg_nak = @sum_dolg_nak, sum_uplata_dolga_nak = @sum_uplata_dolga_nak
		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END


declare @varKSEventText varchar(200)
Select  @varKSEventText = 'Сведения персонифицированного учета по физдицу ' + RTRIM(LTRIM(FIO)) from dbo.SA_SZV4_SVEDENIA where link = @LINK
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV4_SVEDENIA',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0

GO


GRANT EXECUTE ON dbo.[SA_SZV4_SVEDENIA_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].[get_CallDictInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[get_CallDictInfo]
GO




--Release Information
--06.07.2005 Поддержка нескольких парметров [+Лицевой счет] (Нужно для выборки БК и Договоров)
CREATE     procedure dbo.get_CallDictInfo
	@cMode varchar(20) = 'getClientInfo',
	@cObjCode varchar(1000) = '',
	@nObjDict int = 0 OUTPUT,
	@cQuery varchar(8000) = '' OUTPUT,
	@Title varchar(254) = '' OUTPUT,
	@ColToShow varchar(8000) = '' OUTPUT,
	@ColHeadersToShow varchar(8000) = '' OUTPUT,
	@ColToReturn varchar(8000) = '' OUTPUT,
	@ElementsInto varchar(8000) = '' OUTPUT

as
declare @cMask varchar(40), @cParamList varchar(1000), @cCmd varchar(8000), @cParam1 varchar(1000)
declare @lsf int, @link_org int, @link_budg INT, @vcdate VARCHAR(50), @vcOrg VARCHAR(50), @vcBudg VARCHAR(50) 
	set @cParamList = ''
	set @cParam1 = ''

	if CHARINDEX(';', @cObjCode) > 0
	begin
		select @cParamList = SUBSTRING(@cObjCode, CHARINDEX(';', @cObjCode) + 1, 8000)
		if CHARINDEX(';', @cParamList) > 0
		BEGIN
			select @cParam1 = SUBSTRING(@cParamList, CHARINDEX(';', @cParamList) + 1, 8000)
			select @cParamList = LEFT(@cParamList, CHARINDEX(';', @cParamList) - 1)
		END
		
		select @cObjCode = LEFT(@cObjCode, CHARINDEX(';', @cObjCode) - 1)
	end

	declare @cDicCode varchar(1000), @cColumnsList varchar(1000), @cFieldsList varchar(1000), @cWhere varchar(1000)
	select @cDicCode = ''
   set @cWhere = ''

	if CHARINDEX('.', @cObjCode) > 0
	begin
		select @cDicCode = SUBSTRING(@cObjCode, CHARINDEX('.', @cObjCode) + 1, 8000)
		select @cObjCode = LEFT(@cObjCode, CHARINDEX('.', @cObjCode) - 1)
		select @cColumnsList = SUBSTRING(@cDicCode, CHARINDEX('.', @cDicCode) + 1, 8000)
		select @cDicCode = LEFT(@cDicCode, CHARINDEX('.', @cDicCode) - 1)
		select @cFieldsList = SUBSTRING(@cColumnsList, CHARINDEX('.', @cColumnsList) + 1, 8000)
		select @cColumnsList = LEFT(@cColumnsList, CHARINDEX('.', @cColumnsList) - 1)
      if CHARINDEX('.', @cFieldsList) >0
      begin
         set @cWhere = SUBSTRING(@cFieldsList, CHARINDEX('.', @cFieldsList) + 1, LEN(@cFieldsList) - CHARINDEX('.', @cFieldsList) )
         set @cFieldsList = LEFT(@cFieldsList, CHARINDEX('.', @cFieldsList) - 1)
      end
	END
   

	
if LOWER(@cMode) = 'getserverinfo'
begin

	declare @cProc varchar(100)
	if @cDicCode = '' 
		select @nObjDict = dbo.obj_id(dbo.get_val(@cObjCode, 'DICTIONARY', null))
	else select @nObjDict = dbo.obj_id(@cDicCode)

	select @cCmd = ltrim(dbo.get_val(@nObjDict, 'SELECT_RECORDS_METHOD_SQL', null))
	
	select [key], value, type
	into #t_gcdit
	from proc_param_list(@cCmd)


	if (select count(*) from #t_gcdit) = 0
		BEGIN
		if @cDicCode = ''
			begin
				select @cQuery = ' ' + dbo.get_val(@nObjDict, 'SELECT_RECORDS_METHOD_SQL', null)
				select @cQuery = @cQuery + ' [pagingArgs], ' + 
					' @cFields=''' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null), ''), '''', '''''') + 
					''', @cFrom=''' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null), ''), '''', '''''') + 
					''', @cWhere=''' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null), ''), '''', '''''') + ''''
			end
		else
			begin
				select @cQuery = ' ' + dbo.get_val(@nObjDict, 'SELECT_RECORDS_METHOD_SQL', null)
				select @cQuery = @cQuery + ' [pagingArgs], @cFields='''', @cFrom='''', @cWhere='''''
			end
		END
	else
		begin
			delete #t_gcdit
			where value = ''
			if exists(select * from #t_gcdit where [key] = '@cFields') and ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null)) <> ''
				UPDATE #t_gcdit
				SET VALUE = VALUE + ', ' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null), ''), '''', '''''')
				WHERE [KEY] = '@cFields'
			else
				if (ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null)) <> '')
					insert #t_gcdit([key], value, type)
					select '@cFields', REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null), ''), '''', ''''''), 'C'


			if exists(select * from #t_gcdit where [key] = '@cFrom' and ltrim(value) <> '') and ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null)) <> ''
				UPDATE #t_gcdit
				SET VALUE = VALUE + ', ' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null), ''), '''', '''''')
				WHERE [KEY] = '@cFrom'
			else
				if (ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null)) <> '')
					insert #t_gcdit([key], value, type)
					select '@cFrom', REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null), ''), '''', ''''''), 'C'

			if exists(select * from #t_gcdit where [key] = '@cWhere' and ltrim(value) <> '') and ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null)) <> ''
				UPDATE #t_gcdit
				SET VALUE = VALUE + ' and ' + REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null), ''), '''', '''''')
				WHERE [KEY] = '@cWhere'
			else
				if (ltrim(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null)) <> '')
					insert #t_gcdit([key], value, type)
					select '@cWhere', REPLACE(isnull(dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null), ''), '''', ''''''), 'C'
	
		select @cProc = left(@cCmd, CHARINDEX(' ', @cCmd))

		select @cQuery = 'EXECUTE ' + @cProc +  '[pagingArgs], '
		
		update #t_gcdit 
		set @cQuery = value = @cQuery + [KEY] + ' = ' + CASE WHEN TYPE = 'C' THEN '''' ELSE '' END + VALUE + CASE WHEN TYPE = 'C' THEN '''' ELSE '' END + ', '

		select @cQuery = LEFT(@cQuery, LEN(@cQuery) - 1)
		
		end

-- DVG 03.02.2006	
/*	if @cParamList <> ''
		select @cQuery = @cQuery + ', @cSearch = ''' + @cParamList + ''''

	if @cParam1 <> ''
		select @cQuery = @cQuery + ', @nAccount = ' + STR(link) from s_account where account = @cParam1
*/
	if @cParam1 <> ''
		select @cQuery = @cQuery + ', @cSearch = ''' + @cParam1 + ''''
      
   -------------------------------------------------------
   -- зависимые справочники
   IF object_id('tempdb..#report_dictionary_values') IS NOT NULL AND COL_LENGTH('tempdb..#report_dictionary_values', 'linkTable') IS NOT NULL
      AND ISNUMERIC(REPLACE(@cObjCode, 'COL', '')) = 1
   BEGIN
   	DECLARE @cDependentCol varchar(1000), @cDependentRelations varchar(1000), @cDependentCalc varchar(1000), @cDependentColDict varchar(1000),
            @iLinkTable int, @iOrders INT, @cDepWhere VARCHAR(1000), @i INT, @nvExecStr NVARCHAR(1000), @vcValue VARCHAR(8000), @vcCol VARCHAR(100)
      SET @nvExecStr = 'SELECT @iLinkTable = linkTable FROM #report_dictionary_values'
      EXEC sp_executesql @nvExecStr, N'@iLinkTable INT OUTPUT', @iLinkTable = @iLinkTable OUTPUT  
      
      
      SET @iOrders = convert(int, REPLACE(@cObjCode, 'COL', ''))
      
      EXEC dbo.[RO_GET_DEPENDENT_DICT] @cDependentCol output,
	                                    @cDependentRelations output,
	                                    @cDependentCalc output,
	                                    @cDependentColDict output,
	                                    @iLinkTable,
	                                    @iOrders
      
      IF CHARINDEX('|', @cDependentCol) = 0 AND @cDependentCol LIKE '%' + RTRIM(@cObjCode) + '%' -- пока только одинарная зависимость
      BEGIN 
         SET @i = 1
         SET @cDepWhere = ''
         WHILE @i <= dbo.[RA_GETWORDCOUNT](@cDependentCol, '#') AND @i <= dbo.[RA_GETWORDCOUNT](@cDependentCalc, '#')
         BEGIN
            IF dbo.[RA_GETWORDNUM](@cDependentCol, @i, '#') <> 'COL' + LTRIM(STR(@iOrders))
            BEGIN
               SET @vcValue = ''
               IF COL_LENGTH('tempdb..#report_dictionary_values', dbo.[RA_GETWORDNUM](@cDependentCol, @i, '#')) IS NOT NULL
               BEGIN 
                  SET @nvExecStr = 'select @Value = ' + dbo.[RA_GETWORDNUM](@cDependentCol, @i, '#') + ' from #report_dictionary_values'
                  EXEC sp_executesql @nvExecStr, N'@Value varchar(8000) output', @Value = @vcValue OUTPUT 
                  SET @cDepWhere = @cDepWhere 
                                    + CASE WHEN @cDepWhere = '' THEN '' ELSE ' AND ' END
                                    + dbo.[RA_GETWORDNUM](@cDependentCalc, @i, '#') + ' = ''' + RTRIM(@vcValue) + ''''
               END
            END
            ELSE 
            BEGIN
               SET @vcCol = dbo.[RA_GETWORDNUM](@cDependentCalc, @i, '#')         
            END
            SET @i = @i + 1
         END
         IF @cDepWhere <> '' AND isnull(@vcCol, '') <> '' 
         BEGIN
            EXEC dbo.DropTempTable '#Dependent_Diction'
            CREATE TABLE #Dependent_Diction (txt VARCHAR(8000))
            EXEC dbo.RO_GET_DEPENDENT_DICT_WHERE @vcCol, @cDependentColDict, @cDependentRelations, @cDepWhere, '#Dependent_Diction'
            DELETE dbo.[BUFFER] WHERE [SID] = SUSER_SID() AND [LINK] = -999888
            INSERT dbo.buffer([SID], [ID], [LINK])
            SELECT suser_sid(), txt, -999888 from #Dependent_Diction
            SET @cWhere = @cDependentColDict + ' in (select id from dbo.buffer where [sid] = suser_sid() and link = -999888) '
            EXEC dbo.DropTempTable '#Dependent_Diction'
         END
      END
      SELECT @cWhere = RTRIM(ISNULL(@cWhere, '')) + CASE WHEN ISNULL(@cWhere, '') <> '' AND ISNULL([Dictionary_Where], '') <> '' THEN ' AND ' ELSE '' END + ISNULL([Dictionary_Where], '')  
      FROM dbo.report_coloumns
      WHERE [Link_Table] = @iLinkTable AND orders = convert(int, REPLACE(@cObjCode, 'COL', ''))
   END       

   if @cWhere <> '' and object_id('tempdb..#report_dictionary_values') is NOT NULL
   begin
      select @lsf = convert(int, lsf) from #report_dictionary_values
      select @link_org = link_organization, @link_budg = isnull(link_type_svod, 0), 
              @vcDate = CONVERT(varchar(10), begin_date, 112),
              @vcorg = d.[CODE],
              @vcBudg = ISNULL(kbt.[Code], '')  
      from dbo.report_saved_forms rsf
            LEFT JOIN dbo.[DEPARTMENTS] d ON [LINK] = rsf.[Link_Organization]
            LEFT JOIN dbo.[KL_BUDG_TYPE] kbt ON kbt.[Link] = rsf.[Link_Type_Svod]       
      where link_saved_form = @lsf
      
      set @cWhere = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@cWhere, '%link_org%', ltrim(str(@link_org))), '%link_budg%', ltrim(str(@link_budg))), '%date%', '''' + @vcDate + ''''), '%org%', '''' + @vcorg + ''''), '%budg%', '''' + @vcbudg + '''')
      IF CHARINDEX('@cWhere', @cQuery) > 0
      BEGIN 
         select @cQuery = REPLACE(@cQuery, '@cWhere=''''', '@cWhere=''' + REPLACE(@cWhere, '''', '''''') + '''')
      END 
      ELSE BEGIN
         select @cQuery = @cQuery + ', @cWhere = ''' + REPLACE(@cWhere, '''', '''''') + ''''        
      END
   end

  return
end

if LOWER(@cMode) = 'getclientinfo'
begin
	select @cMask = '%' + @cObjCode + '%'

	create table #t1(DICT varchar(1000),
									 DICT_FIELD_LIST varchar(800), 
									 DICT_COLUMN_LIST varchar(800), 
									 DICT_ADD_SELECT varchar(800), 
									 DICT_ADD_FROM varchar(800), 
									 DICT_ADD_WHERE varchar(800),
									 OBJ_CODE varchar(800),
									 FIELD_CODE varchar(800),
						       VISIBLE varchar(800))


	if @cDicCode = ''
	  begin
			insert into #t1(DICT, DICT_FIELD_LIST, DICT_COLUMN_LIST, DICT_ADD_SELECT, DICT_ADD_WHERE, DICT_ADD_FROM, OBJ_CODE, FIELD_CODE, VISIBLE)
			values (dbo.get_val(@cObjCode, 'DICTIONARY', null),
				dbo.get_val(@cObjCode, 'DICTIONARY_FIELDS_LIST', null),
				dbo.get_val(@cObjCode, 'DICTIONARY_COLUMNS_LIST', null),
				dbo.get_val(@cObjCode, 'DICTIONARY_ADD_SELECT', null),
				dbo.get_val(@cObjCode, 'DICTIONARY_ADD_FROM', null),
				dbo.get_val(@cObjCode, 'DICTIONARY_ADD_WHERE', null),
				@cObjCode, 
			  @cObjCode,
				dbo.get_val(@cObjCode, 'VISIBLE', null))
		end
	else
		begin
			insert into #t1(DICT, DICT_FIELD_LIST, DICT_COLUMN_LIST, DICT_ADD_SELECT, DICT_ADD_WHERE, DICT_ADD_FROM, OBJ_CODE, FIELD_CODE, VISIBLE)
			values (@cDicCode,
								@cFieldsList,
								@cColumnsList,
								' ',
								@cWhere,
								' ',
								@cObjCode, 
								@cObjCode,
								'4');
		end
		

	if (select count(*) from #t1 where left(visible, 2) = '&&') > 0
	begin
		create table #tc_wgdfc(value varchar(8000))
		declare @cValue varchar(8000)
		declare t_wgdfc cursor for
		select visible from #t1 where left(visible, 2) = '&&'
		OPEN t_wgdfc
		FETCH NEXT FROM t_wgdfc INTO @cValue
		WHILE @@FETCH_STATUS = 0
		begin
			select @cCmd = substring(@cValue, 3, 8000)
			insert #tc_wgdfc
			exec(@cCmd)
			update #t1
			set visible = (select value from #tc_wgdfc)
			where #t1.visible = @cValue
			truncate table #tc_wgdfc
			FETCH NEXT FROM t_wgdfc INTO @cValue
		end
	
		CLOSE t_wgdfc
		DEALLOCATE t_wgdfc
		drop table #tc_wgdfc
	end
	
	create table #t_dict(obj_code varchar(100), title varchar(100), field_data varchar(100), dict_code varchar(100), colToShow varchar(2000), HeadersToShow varchar(2000))
	
	create table #t_temp(class_name varchar(100), obj_code varchar(100), title varchar(100), field_data varchar(100), visible int, orders int)
	
	declare @cDict varchar(100)
	select @cDict = DICT from #t1
	

	exec web_get_doc_field_columns @cDict, 'TITLE,FIELD_DATA,VISIBLE', 'EDIT_FIELD_CLASS', '', 1, 'VISIBLE&4 > 0', @cTable = '#t_temp'
	
	insert #t_dict(obj_code, title, field_data, dict_code)
	select obj_code, title, field_data, @cDict from #t_temp order by orders
		


	DECLARE @t1 varchar(100), @buff1 varchar(8000), @buff2 varchar(8000)

	set @buff1 = ''
	set @buff2 = ''
	select @t1 = min(DICT_CODE) from #t_dict
	
	update #t_dict set @buff1 = colToShow = case when @t1 = DICT_CODE then isnull(@buff1, '') +case when isnull(@buff1, '') <> '' then ',' else '' END else '' END + FIELD_DATA,
		@buff2 = HeadersToShow = case when @t1 = DICT_CODE then isnull(@buff2, '') +case when isnull(@buff2, '') <> '' then ',' else '' END else '' END + TITLE,
		@t1 = DICT_CODE = DICT_CODE
	
	select t.* 
	into #t_dictionary
	from #t_dict t, (select max(len(colToShow)) as lenCol, dict_CODE from #t_dict group by dict_code) tt
	where t.dict_code = tt.dict_code
		and len(t.colToShow) = lenCol

	select @Title = dbo.get_val(t2.DICT, 'TITLE', null), @ColToShow = t1.ColToShow, @ColHeadersToShow = t1.HeadersToShow, @ColToReturn = t2.DICT_FIELD_LIST, @ElementsInto = ltrim(rtrim(t2.DICT_COLUMN_LIST))
	from #t_dictionary t1, #t1 t2
	where t2.DICT = t1.DICT_CODE
	
	
	drop table #t1
	drop table #t_dict
	drop table #t_temp
	drop table #t_dictionary
end






GO
GRANT EXECUTE ON dbo.[get_CallDictInfo] 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].[BB_GZ_REESTR_REPORT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_GZ_REESTR_REPORT]

GO


create    procedure dbo.BB_GZ_REESTR_REPORT @iLSF int 

as

declare @dDateBeg	datetime,
		@cDepCode	varchar(20),
		@iDepLink int, 
		@dDateEnd datetime


select @iDepLink = Link_Organization, 
		@dDateEnd    = Begin_Date + 1, 
		@dDateBeg  = dbo.DateBeginOfYear(Begin_Date)
from dbo.REPORT_SAVED_FORMS
where Link_Saved_Form = @iLSF


select @cDepCode = isnull(rtrim(ltrim(BUDG)),'')
from dbo.DEPARTMENTS 
where LINK = @iDepLink 

set @dDateBeg = dbo.DateBeginOfYear(@dDateEnd)
declare @cTableReestr table (	LINK_GC		int,
			 	LINK_OKDP	int,
			 	TYPE		tinyint,
				QUANTITY	numeric(19,4),
				--COST		numeric(19,4),
				SUMMA		numeric(19,4))

declare @cTemp table(LINK_OKDP	int,
			NAME_DOC	varchar(100),
			LINK_DEP	INT,
			NUMBER		varchar(30),
			[DATE]		datetime,
			COMMENT		varchar(1000),		
			C_TYPE		int,
			CON_END		datetime,
			C_QUANTITY	numeric(19,4),
			C_COST		numeric(19,4),
			C_SUMMA		numeric(19,4),
			GZ_QUANTITY	numeric(19,4),
			GZ_COST		numeric(19,4),
			GZ_SUMMA	numeric(19,4),
			OPL_SUMMA	numeric(19,4),
			OPL_SUMMA_B	numeric(19,4),
			OPL_SUMMA_V	numeric(19,4))

declare @cTemp1 table(LINK_GC	int,  
						LINK_OKDP	int,  
						NAME_DOC	varchar(100), 
						LINK_DEP	int, 
						NUMBER	varchar(30), 
						[DATE]	datetime,
						COMMENT	varchar(1000), 
						C_TYPE	int, 
						CON_DATE	datetime,
						[TYPE]	int, 
						QUANTITY numeric(19,4),
						COST numeric(19,4), 
						SUMMA numeric(19,4))
			



-- Выбираем строки реестра госзакупок
insert into @cTableReestr(LINK_GC, LINK_OKDP, QUANTITY,/* COST, */SUMMA, TYPE)
select GR.LINK_CONTRACT, OKDP.LINK, SUM(GRT.QUANTITY * N.COEFF)/*, (case when N.COEFF = 0 then 0 else GRT.COST / N.COEFF end)*/, SUM(GRT.SUMMA) / 1000, GRT.TYPE
from dbo.G_PROV G
inner join dbo.GZ_REESTR GR on GR.LINK = G.LINK
inner join dbo.GZ_REESTR_DOP GRT on GRT.LINK_UP = G.LINK
inner join dbo.NOMENCLATURE N on GRT.NOMENCLATURE = N.LINK 
inner join dbo.OKDP OKDP on N.LINK_OKDP = OKDP.LINK --and not exists (select * from OKDP OKDP1 where OKDP1.LINK_SELF = OKDP.LINK)
where  G.DATE_PROV is not NULL and 
	G.DATE_PROV between @dDateBeg and @dDateEnd and 
	G.DEP = @iDepLink
group by GR.LINK_CONTRACT, OKDP.LINK, GRT.TYPE --, case when N.COEFF = 0 then 0 else GRT.COST / N.COEFF end

--select * from @cTableReestr

insert into @cTemp1
select distinct LINK_GC 	= G.LINK, 
		     LINK_OKDP	= CT.OKDP,  
		     NAME_DOC	= case when CH.GZ_LINK is not null or (rtrim(CH.GZ_NUM) <> '' or CH.GZ_DATE is not null) then 'Госконтракт' else /*rtrim(SO.NAME)*/'Договор' end, 
		     LINK_DEP	= CH.DEP_LINK_P, 
		     NUMBER	= case when CH.GZ_LINK is not null then GZ.NUMBER else case when rtrim(CH.GZ_NUM) <> '' or CH.GZ_DATE is not null then CH.GZ_NUM else case when CH.DOG_LINK is not null then GPD.NUMBER else G.NUMBER end end end, 
		     DATE	= case when CH.GZ_LINK is not null then GZ.DATE else case when rtrim(CH.GZ_NUM) <> ''  or CH.GZ_DATE is not null then CH.GZ_DATE else case when CH.DOG_LINK is not null then GPD.DATE else G.DATE end end end,
		     COMMENT	= case when CH.GZ_LINK is not null and GZ.COMMENT <> '' then GZ.COMMENT else CH.MAINTENANCE end, 
		     C_TYPE	= CH.TYPE, 
		     CON_DATE	= DATE_END,
		     TYPE	= 3, 
		     CT.QUANTITY, 
		     CT.COST, 
		     SUMMA      = CT.SUMMA / 1000
		from dbo.G_PROV G
		inner join dbo.FINANSE_CONTRACT_HEAD CH on CH.Link_G_Prov = G.LINK and CH.GZ = 1 and
							   (CH.DATE_BEGIN between @dDateBeg and @dDateEnd or
								CH.DATE_END between @dDateBeg and @dDateEnd or
								@dDateBeg between CH.DATE_BEGIN and CH.DATE_END or
								@dDateEnd between CH.DATE_BEGIN and CH.DATE_END)
		inner join (	select LINK_UP, OKDP, sum(SUMMA) as SUMMA, sum(QUANTITY) as QUANTITY, case sum(QUANTITY) when 0 then 0 else sum(SUMMA)/sum(QUANTITY) end  as cost
				from dbo.FINANSE_CONTRACT 
				group by LINK_UP, OKDP) CT on CT.LINK_UP = G.LINK
		left  join dbo.G_PROV GZ on GZ.LINK = CH.GZ_LINK
		left  join dbo.S_OBJECTS SO on isnull(GZ.OBJECT, G.OBJECT) = SO.LINK
		left  join dbo.G_PROV GPD on GPD.LINK = CH.DOG_LINK
		where G.DEP = @iDepLink and G.DATE_PROV is not null  
		union all
		select LINK_GC 	= G.LINK, 
		     LINK_OKDP	= NULL,  
		     NAME_DOC	= rtrim(DT.NAME), 
		     LINK_DEP	= CH.DEP_LINK_P, 
		     NUMBER	= G.NUMBER, 
		     DATE	= G.DATE, 
		     COMMENT	= G.COMMENT, 
		     C_TYPE	= CH.TYPE, 
		     CON_DATE	= NULL, 
		     TYPE	= 4, 
		     QUANTITY	= 0, 
		     COST	= 0, 
		     SUMMA	= G.SUMMA / 1000
		from dbo.G_PROV G
		inner join dbo.GZ_NOT_CONTRACT_HEAD CH on CH.LINK = G.LINK
		inner join dbo.BB_NOT_CONTRACT_DOC_TYPE DT on DT.LINK = CH.TYPE_DOC 
		where G.DEP = @iDepLink and 
 			G.[DATE] between @dDateBeg and @dDateEnd and
			G.LINK in (select LINK_GC from @cTableReestr)

insert into  @cTemp(NAME_DOC, LINK_DEP, NUMBER, [DATE], CON_END, COMMENT, C_TYPE, LINK_OKDP, 
			C_QUANTITY, C_COST, C_SUMMA, GZ_QUANTITY, GZ_COST, GZ_SUMMA, OPL_SUMMA, OPL_SUMMA_B, OPL_SUMMA_V)

select distinct TC.NAME_DOC, TC.LINK_DEP, TC.NUMBER, TC.DATE, TC.CON_DATE,  TC.COMMENT, TC.C_TYPE, 
	LINK_OKDP	= O.LINK,  
	C_QUANTITY	= isnull(case TC.TYPE when 4 then TR.QUANTITY else TC.QUANTITY end,0),
	C_COST		= isnull(case TC.TYPE when 4 then TR.COST else TC.COST end,0),
	C_SUMMA		= isnull(case TC.TYPE when 4 then TR.SUMMA else TC.SUMMA end,0),
	GZ_QUANTITY 	= isnull(TR.QUANTITY,0), 
	GZ_COST		= isnull(TR.COST,0), 
	GZ_SUMMA	= isnull(TR.SUMMA,0),
	OPL_SUMMA	= isnull(TR.SUMMA1,0),
	OPL_SUMMA_B	= isnull(TR.SUMMA1,0),
	OPL_SUMMA_V	= 0
from @cTemp1 TC
full outer join (select LINK_GC = isnull(TR2.LINK_GC,TR1.LINK_GC),
			LINK_OKDP = isnull(TR2.LINK_OKDP,TR1.LINK_OKDP),
			TR2.QUANTITY, 
		     	COST = case TR2.QUANTITY when 0 then 0 else TR2.SUMMA/TR2.QUANTITY * 1000 end, 
		     	TR2.SUMMA, 
		     	SUMMA1 = TR1.SUMMA 
		 from @cTableReestr TR2 
		 full outer join @cTableReestr TR1 on TR1.LINK_GC = TR2.LINK_GC and TR2.LINK_OKDP = TR1.LINK_OKDP
		 where TR2.TYPE = 2 and TR1.TYPE = 1
		 
		 ) TR 
	on TR.LINK_GC = TC.LINK_GC and (TC.LINK_OKDP = TR.LINK_OKDP or TC.TYPE = 4) 
inner join dbo.OKDP O on O.LINK = ISNULL(TC.LINK_OKDP, TR.LINK_OKDP) --and not exists (select * from OKDP OKDP1 where OKDP1.LINK_SELF = O.LINK)


select 	CODE/*OKDP_CODE*/	= cast(rtrim(cast(O.CODE as char(10))) + '$' + isnull(@cDepCode,'') + '$' + isnull(rtrim(T.NAME_DOC),'') + '$' + isnull(ltrim(rtrim(T.[NUMBER])),'') + '$' + isnull(ltrim(rtrim(ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''))) ,'') as varchar(50)),
	---CODE/*OKDP_CODE*/	= O.CODE, 
	COL1/*OKDP_CODE*/	= rtrim(O.CODE), 
	COL2/*DOC_NAME*/ 	= rtrim(isnull(cast(T.NAME_DOC + ' № '  + rtrim(T.[NUMBER]) + ' от ' + ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),'') as varchar(254)),'')),
	COL3/*DOC_COMMENT*/	= rtrim(isnull(replace(T.COMMENT,'
',' '),'')),
	COL4/*CON_TYPE_NAME*/	= rtrim(isnull(cast(ZT.NAME as char(100)),'')),
	COL5/*OKDP_NAME*/	= rtrim(O.NAME),
	COL6/*DEP_NAME*/	= cast(isnull(rtrim(D.NAME) + case when D.INN = '' then '' else ' ИНН ' + RTRIM(D.INN) + CASE WHEN D.INN_DOP = '' THEN '' ELSE '/' + D.INN_DOP END end + ' ' + rtrim(isnull(dbo.GetAddressByKladr(D.KLADR_LINK),'')) + CASE when D.HOUSE is null or D.HOUSE = '' then '' else  ' ,' + D.HOUSE end,'') as varchar(250)),
	COL7/*OKDP_UM*/		= isnull(UM.NAME,''),
	COL8/*C_QUANTITY*/	= case when UM.NAME like '%руб%' then 0 else C_QUANTITY end,
	COL9/*GZ_QUANTITY*/	= case when UM.NAME like '%руб%' then 0 else GZ_QUANTITY end,
	COL10/*C_COST*/		= case when UM.NAME like '%руб%' then 0 else C_COST end,
	COL11/*GZ_COST*/	= case when UM.NAME like '%руб%' then 0 else GZ_COST end,
	COL12/*C_SUMMA*/	= C_SUMMA,
	COL13/*GZ_SUMMA*/	= GZ_SUMMA,
	COL14/*OPL_SUMMA*/	= OPL_SUMMA,
	COL15/*OPL_SUMMA_B*/	= OPL_SUMMA,
	COL16/*OPL_SUMMA_V*/	= 0,
	COL17/*CON_END*/	= ISNULL(CONVERT(VARCHAR(30),T.[CON_END],104),''),
	COL18/*OPL_SUMMA_V*/	= case when C_SUMMA = GZ_SUMMA and C_SUMMA = OPL_SUMMA then 'выполнен' else '' end,
	COL19/*CON_END*/	= ISNULL(case D.DEP_TYPE2 when 1 then 'МП' else '' end ,''),
	COL20/*OKDP_CODE*/	= cast(rtrim(cast(O.CODE as char(10))) + '$' + isnull(@cDepCode,'') + '$' + isnull(rtrim(T.NAME_DOC),'') + '$' + isnull(ltrim(rtrim(T.[NUMBER])),'') + '$' + isnull(ltrim(rtrim(ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''))) ,'') as varchar(50)),
	COL21/*CON_NUM*/	= '',
	COL22/*CON_DATE*/	= '20060101',
	COL23/*NAME_DOC*/	= rtrim(T.[NAME_DOC]),
	COL24/*DOC_NUM*/	= rtrim(T.[NUMBER]),
	COL25/*DOC_DATE*/	= ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''),
	COL26/*PDEP_NAME*/	= cast(isnull(rtrim(D.NAME),'') as varchar(250)),
	COL27/*PDEP_ADR*/	= isnull(rtrim(cast(dbo.GetAddressByKladr(D.KLADR_LINK) + CASE when D.HOUSE is null or D.HOUSE = '' then '' else ' ,' + D.HOUSE end   as varchar(250))),''),
	COL28/*PDEP_ADR*/	= @cDepCode
/*	OKDP_CODE1		= case LEVEL_OKDP when 2 then O.CODE else '' end,
	OKDP_CODE2		= case LEVEL_OKDP when 3 then O.CODE  else '' end,
	OKDP_CODE3		= case LEVEL_OKDP when 4 then O.CODE  else '' end,
	OKDP_CODE4		= case LEVEL_OKDP when 5 then O.CODE  else '' end,
	OKDP_CODE5		= case LEVEL_OKDP when 6 then O.CODE  else '' end*/

		

from @cTemp T
inner join dbo.OKDP O on O.LINK = T.LINK_OKDP
left join dbo.DICTIONARY_DIGIT UM on O.UM = UM.LINK 
left join dbo.FB_GZ_TYPE ZT on T.C_TYPE = ZT.TYPE
left join dbo.DEPARTMENTS D on T.LINK_DEP = D.LINK 
order by CODE


GO


grant all on BB_GZ_REESTR_REPORT 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.[RO_FILL_WITH_CODE_ROW_DATE]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_FILL_WITH_CODE_ROW_DATE]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_FILL_WITH_CODE_ROW_DATE]
	@vcSplit          VARCHAR(8000),
	@vcTableName	   VARCHAR(100),
   @iLinkTable       INT  
AS
DECLARE @i INT, @vcDict VARCHAR(1000), @vcCol VARCHAR(1000), @nvStr NVARCHAR(1000)
SET @i = 1
WHILE @i < dbo.[RA_GETWORDCOUNT](@vcSplit, '#')
BEGIN
   SET @vcDict = dbo.RA_GETWORDNUM(@vcSplit, @i, '#')
   SET @vcCol = dbo.RA_GETWORDNUM(@vcDict, 2, '=')
   SET @vcDict = dbo.RA_GETWORDNUM(@vcDict, 1, '=')
   SELECT @vcDict = RTRIM(rc.[Dictionary])  
   FROM dbo.[REPORT_COLOUMNS] rc
   WHERE rc.[Link_Table] = @iLinkTable AND rc.[Orders] = CONVERT(INT, REPLACE(@vcDict, 'col', ''))
   
   IF ISNULL(@vcDict, '') <> '' AND COL_LENGTH(@vcDict, 'begin_date') IS NOT NULL AND NOT( ISNULL((SELECT val_int FROM dbo.[REPORT_OPTIONS] ro WHERE ro.[Razdel] = 'COMMON' AND ro.[Code] = 'ITOG_117'), 0) = 1 AND (@vcDict LIKE '%VR%' OR @vcDict LIKE '%CSR%')) 
   BEGIN
      SET @nvstr = ' insert #CodeDate (Code, begin_date, end_date) '
      + ' select C.Code, min(D.begin_date), max(D.end_date)'
      + ' from ' + @vcTableName + ' C join ' + @vcDict + ' D on ' + REPLACE(@vcCol, 'CODE_ROW', 'C.Code') + '= D.Code'
      + ' where not exists(select * from #CodeDate C1 where C1.Code = C.Code)'
      + ' group by C.Code'
      + ' update C'
      + ' set begin_date = case when isnull(C.begin_date, ''19000101'') > isnull(D.begin_date, ''19000101'') then C.begin_date else D.begin_date end,'
      + ' end_date = case when isnull(C.end_date, ''30000101'') > isnull(D.end_date, ''30000101'') then D.end_date else C.end_date end'
      + ' from #CodeDate C join (select Code, min(begin_date) begin_date, max(end_date) end_date from ' + @vcDict + ' group by Code) D on ' + REPLACE(@vcCol, 'CODE_ROW', 'C.Code') + '= D.Code'
     -- PRINT @nvstr
      EXEC sp_executesql @nvstr 
   END                   
   SET @i = @i + 1
END  


GO
GRANT ALL ON dbo.[RO_FILL_WITH_CODE_ROW_DATE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[web_sign_checksign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[web_sign_checksign]
GO




/*
© Кейсистемс (Keysystems), 2005
*/

CREATE   
procedure dbo.web_sign_checksign
					@cDocCode varchar(200), -- код документа
					@xmlLinks text, -- xml с линками
					@cTableLinks varchar(200) = '', -- название таблицы с линками если не передали в @xmlLinks
               @cTableName varchar(100) = '' --  таблица, в которую нужно все поместить
as

declare @cData  as varchar(8000)
declare @cSign as varchar(8000)
declare @ip varchar(20)
declare @cErr varchar(8000)
declare @query nvarchar(4000), @error_text varchar(8000),  @xml varchar(8000), @retVal int, @CadesCheck varchar(500)
create table #res_out (date DATETIME, form_code varchar(254), form_per varchar(254), form_name varchar(254),form_org varchar(254), form_kbp varchar(254), form_type varchar(254), sign_res varchar(254), sign_who varchar(254), sign_det varchar(254), link_doc int, [uid] int)


IF  @cDocCode = 'REPORT_FORMS_LIST' or @cDocCode = 'REPORT_SVOD'
begin 
	 create table #doc_link(link int)
	 create table #docs_signat(link int, text TEXT)
	 create table #docs_signat_str(link int IDENTITY(1,1), link_doc int, value varchar (8000), sid varbinary(85) default 0, value_copy VARCHAR(8000) DEFAULT(''))
	 create table #docs_sign(link int, text text)
	 create table #docs_sign_str(link int IDENTITY(1,1), link_doc int, value varchar (8000), sid varbinary(85) default 0)
	 create table #t_Result (i int)	

	 create table #t_retValueXML (text text ,link int)
	 create table #t_retValues (CertServerVersion varchar(50), XPKSwVersion varchar(50), CheckSignature varchar(4), CheckSignatureStatus varchar(500), FindCertificate varchar(4), FindCertificateStatus varchar(500), CheckChain varchar(4), CheckChainStatus varchar(500), Subject varchar(500), SubjectName varchar(500), error varchar(500), REASON varchar(500), CadesCheck varchar(500), [Timestamp] varchar(500))

	
	DECLARE @sp VARCHAR(100),@cTapok VARCHAR(8000),
	@form_code varchar(254), @form_period varchar(254), @form_name varchar(254),
	@form_org varchar(254), @form_kbp varchar(254), @form_type varchar(254), 
	@sign_res varchar(254), @sign_who varchar(254), @sign_detail varchar(254), @sid varbinary(85), @date DATETIME 
	
		
	DECLARE @hDoc int, @nDocCode int, @doc_link int, @doc_string varchar (8000), @return_code varchar (8000)
		
	if (@xmlLinks is not null)
		begin
			exec sp_xml_preparedocument @hDoc OUTPUT, @xmlLinks
			insert #docs (link)
			select link
			FROM OPENXML(@hDoc, 'Links/Link', 2)
			WITH (link int '@Link') 
			EXEC sp_xml_removedocument @hDoc
		end
		else
		begin
			exec('insert #doc_link (link) select link from ' + @cTableLinks)
		end
		
		-- ип сервера сертификатов
			select @ip  = rtrim(ltrim(serverip)) from i_report_options_ecp_common
		
		-- сформируем контент для подписи этого документа процой web_sign_docList
		
		  exec dbo.web_sign_docsList @cDocCode, null, '#doc_link', 1

		insert into #docs_signat (link, text)
		select LSF, txt
		from REPORT_SIGN_TXT
		where sid = suser_sid() and LSF in (select link from #doc_link)
      
		insert  #docs_signat_str( link_doc, value)
		select 0, 'insert #t_retValueXML (text) exec master..xp_checkdigt ''' 

		exec text2varchar
			@cTableSour ='#docs_signat',
			@cValueSour ='text',
			@cKeySour ='link',
			
			@cTableDest ='#docs_signat_str',
			@cValueDest ='value',
			@cKeyUpDest ='link_doc'
         
      UPDATE #docs_signat_str 
      set value_copy = value          

	-- проверка подписи 
		DECLARE form_cursor CURSOR local static FOR 
		SELECT Link,  sid FROM #docs_signat D inner join report_sign S on D.link = S.LSF 
		OPEN form_cursor
		FETCH NEXT FROM form_cursor  INTO @doc_link,  @sid
			WHILE @@FETCH_STATUS = 0
			BEGIN

				insert #docs_sign (link, [text])
				select lsf, sign 
				from dbo.report_sign
				where lsf = @doc_link and sid = @sid
            
            SELECT @date = [date]
            FROM dbo.report_sign
				where lsf = @doc_link and sid = @sid

            UPDATE #docs_signat_str
            SET VALUE = LEFT(value_copy, CHARINDEX('ПО=Свод-КС', value_copy) - 1) 
                      + ISNULL((SELECT TOP 1 SUBSTRING(convert(varchar(8000), text_for_sign),CHARINDEX('ПО=Свод-КС',convert(varchar(8000), text_for_sign)), 23)   
                         FROM  dbo.report_sign S WHERE S.sid = @sid AND  S.[lsf] = #docs_signat_str.link_doc AND CHARINDEX('ПО=Свод-КС',convert(varchar(8000), text_for_sign)) > 0), '')
                      + SUBSTRING(value_copy,   CHARINDEX(CHAR(13)+CHAR(10), value_copy, CHARINDEX('ПО=Свод-КС', value_copy)) + 2, 8000)                           
            WHERE VALUE_copy LIKE '%ПО=Свод-КС%' AND [link_doc] = @doc_link



            UPDATE #docs_signat_str
            SET VALUE = ISNULL((SELECT TOP 1 SUBSTRING(convert(varchar(8000), text_for_sign),1, CHARINDEX('КФ=',convert(varchar(8000), text_for_sign)) - 3)   
                         FROM  dbo.report_sign S WHERE S.sid = @sid AND S.[lsf] = #docs_signat_str.link_doc AND CHARINDEX('ВФ=',convert(varchar(8000), text_for_sign)) > 0) + CHAR(13) + CHAR(10), '')
                       +  SUBSTRING(value_copy,    CHARINDEX(CHAR(13) + CHAR(10) + 'КФ=', value_copy) + 2, 8000)                              
            WHERE VALUE_copy LIKE '%' + CHAR(13) + CHAR(10) + 'КФ=%РД=%' 
                  AND [link_doc] = @doc_link

--SELECT * FROM #docs_signat_str WHERE [link_doc] = @doc_link ORDER BY link
--SELECT * FROM report_sign WHERE lsf = @doc_link AND [sid] = @sid
                   
 				exec text2varchar
					@cTableSour ='#docs_sign',
					@cValueSour ='text',
					@cKeySour ='link',
					
					@cTableDest ='#docs_sign_str',
					@cValueDest ='value',
					@cKeyUpDest ='link_doc'


				insert  #docs_signat_str( link_doc, value, sid)
				select @doc_link, ''', ''' , @sid

				insert  #docs_signat_str( link_doc, value, sid)
				select @doc_link, value , @sid
				from #docs_sign_str

				insert  #docs_signat_str( link_doc, value, sid)
				select @doc_link, ''', '''+ isnull(@ip, '') + ''', null, 22, ''ID 0ef1318040f''', @sid
			
				set @cData = 'select value from #docs_signat_str where link_doc=0 or link_doc = ' + STR(@doc_link) + ' order by link'
--EXEC(@cData)
				exec @retVal = ssp_execresultset @varKScmd = @cData--, @varKSdebug = 1
				
				update #t_retValueXML set link = 1
				
				if (@@ERROR <> 0)
				begin
					set @cErr = 'ошибка выполнения [xp_checkdigt]' 
					raiserror(@cErr, 18, 1) 
					return 
				end
	
				exec dbo.[RO_EXECUTE_WITH_TEXT] 'declare @hdoc int EXEC sp_xml_preparedocument @hDoc OUTPUT, ''@text@'' insert #t_Result (i) select @hdoc', #t_retValueXML

				select @hDoc = i from #t_Result
				
				insert #t_retValues (CertServerVersion, XPKSwVersion, CheckSignature, CheckSignatureStatus, FindCertificate, FindCertificateStatus, CheckChain, CheckChainStatus, Subject, SubjectName, error, CadesCheck, Timestamp) 
				select CertServerVersion, XPKSwVersion, CheckSignature, CheckSignatureStatus, FindCertificate, FindCertificateStatus, CheckChain, CheckChainStatus, Subject, SubjectName, error, CadesCheck, Timestamp
				FROM OPENXML(@hDoc, N'/data') 
				with (	
						CertServerVersion varchar(50) 'CertServerVersion/text()',
						XPKSwVersion varchar(50) 'XPKSwVersion/text()',
						CheckSignature varchar(4) 'CheckSignature/text()',
						CheckSignatureStatus varchar(500) 'CheckSignatureStatus/text()',
						FindCertificate varchar(4) 'FindCertificate/text()',
						FindCertificateStatus varchar(500) 'FindCertificateStatus/text()',
						CheckChain varchar(4) 'CheckChain/text()',
						CheckChainStatus varchar(500) 'CheckChainStatus/text()',
						Subject varchar(500) 'Subject/text()',
						SubjectName varchar(500) 'SubjectName/text()',
						error varchar(500) 'error/text()',
						CadesCheck varchar(500) 'CadesCheck/text()',
						Timestamp varchar(500) 'Timestamp/text()'
					) 
				
				EXEC sp_xml_removedocument @hDoc

				select @error_text = error, @CadesCheck = CadesCheck from #t_retValues
				
				if (isnull(@error_text, '') <> '')
				begin
					update #t_retValues
					set CheckSignature = 'FAIL',
						REASON = error
				end
				else
				begin
					update #t_retValues
					set REASON = CheckSignatureStatus
					where CheckSignature = 'FAIL'
					
					update #t_retValues
					set REASON = 'ПОДПИСЬ ВЕРНА.'
					where CheckSignature = 'OK'
				end

				if isnull(@CadesCheck, '') <> ''
				begin
					update #t_retValues
					set REASON = ' ШТАМП ВРЕМЕНИ: ' + Timestamp + ' ' + REASON  
					where CadesCheck = 'OK'	

					update #t_retValues
					set REASON = 'ПРОВЕРКА ШТАМПА ВРЕМЕНИ: ' + CadesCheck + ' ' + REASON  
					where CadesCheck <> 'OK'	
				end

		
    		delete #docs_signat_str where sid = @sid
			
			select @form_code = code, @form_period = period, @form_name = name, @form_org = dep_name, @form_kbp = dep_code, @form_type = type_svod 
			from RO_SAVED_FORMS_VIEW_SVOD
			where link = @doc_link

			
			insert into #res_out (date, form_code, form_per, form_name,form_org, form_kbp, form_type, sign_res, sign_who, sign_det, link_doc, [uid])
			select @date, left(@form_code,250), left(@form_period,250), left(@form_name,250), left(@form_org,250), left(@form_kbp,250), left(@form_type,250), left(REASON,250), left(SubjectName,250),  left(SUBJECT,250), @doc_link, dbo.AdminGetUidBySid(@sid)
			from #t_retValues

			
			truncate table #docs_sign
			truncate table #docs_sign_str
			truncate table #t_Result
			truncate table #t_retValues
			truncate table #t_retValueXML
			

	FETCH NEXT FROM form_cursor 
	INTO @doc_link, @sid

	END
	
CLOSE form_cursor
DEALLOCATE form_cursor

drop table #docs_signat
drop table #docs_signat_str
drop table #doc_link

if isnull(@cTableName, '') = ''
   select form_code, form_per, form_name,form_org, form_kbp, form_type, sign_res, sign_who, sign_det, link_doc, date, [uid] from #res_out
else begin
   set @query = 'select * into ' + @cTableName + ' from #res_out'
   exec sp_executesql @query
end

END
   exec dbo.DropTempTable '#res_out' 
GO

GRANT ALL ON dbo.[web_sign_checksign] TO PUBLIC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_4FSS_09022012_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_4FSS_09022012_PREPARE]

GO

CREATE PROCEDURE dbo.RSA_4FSS_09022012_PREPARE
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

EXEC dbo.BufferClear

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT

DECLARE --Для выравнивания погрешности
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N NUMERIC(18,6)


select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF
set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(18,6) default 0.00, DED_M numeric(18,6) default 0.00, INV_M numeric(18,6) default 0.00, SUMMA numeric(18,6) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, KATEG TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) WHERE WAY_CALC = 2

---Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, P.WAY_CALC, GT.PERS_LINK,
	KATEG = (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)
FROM 
	dbo.SDOC G
	INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
	INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
	LEFT JOIN dbo.pers_invalid I ON GT.PERS_LINK = I.PERS_LINK 
	AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(G.[DATE]),@nYEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
WHERE
	G.[OBJECT] =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
	AND GT.[OBJECT] = 3
	AND FLAG_JC = 1
	AND P.WAY_CALC = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK

/*РАЗДЕЛ 2.1*/
CREATE TABLE #RES2(CODE_STR VARCHAR(10), BASE_FSS NUMERIC(18,6), CNT_FSS INT, CNT_FEM INT)

/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность работающих инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2
SELECT '3', 0, @NAvgCount, 0

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
INSERT INTO #RES2
SELECT '1', 0, @NAvgCount, 0

/* Среднесписочная численность женщин */
INSERT INTO #RES2
SELECT '2', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 2, 1, 0, DEFAULT)), 0

/* Среднесписочная численность работающих во вредных условиях */
INSERT INTO #RES2
SELECT '4', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 2, DEFAULT)), 0

--Р1.ТАБЛИЦА 1
--Начислено ЕСН. На НАч квартала
INSERT INTO #RES2 --код=табл. 02, строка 3_1
SELECT '0121', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE < @nMONTH1 

--Начислено ЕСН. 1 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_3
SELECT '0123', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH1

--Начислено ЕСН. 2 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_4
SELECT '0124', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH2
--
--Начислено ЕСН. 3 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_5
SELECT '0125', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH3

--Р1.ТАБЛИЦА 2

DECLARE 
	@P02010 INT, --Количество больничных
	@P02013 NUMERIC(18,2),  --Количество больничных дней 
	@P02014 NUMERIC(18,2), --Сумма по больничным за счет ФСС

	@P02020 INT, --Количество больничных по внешнему совместительству
	@P02023 NUMERIC(18,2),  --Количество больничных дней по внешнему совместительству
	@P02024 NUMERIC(18,2), --Сумма по больничным за счет ФСС по внешнему совместительству
	
	@P02030 INT, --Количество больничных По беременности и родам
	@P02033 NUMERIC(18,2),  --Количество По беременности и родам дней
	@P02034 NUMERIC(18,2), --Сумма По беременности и родам за счет ФСС

	@P02040 INT, -- Количество больничных по беременности и родам по внешнему совместительству
	@P02043 NUMERIC(18,2),  --Количество дней по беременности и родам по внешнему совместительству
	@P02044 NUMERIC(18,2),  --Сумма по беременности и родам за счет ФСС по внешнему совместительству

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за первым
	@P02080 INT, --количество получателей
	@P02083 NUMERIC(18,2),  -- количество произведенных выплат
	@P02084 NUMERIC(18,2), -- сумма расходов

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за вторым и последующим
	@P02090 INT, --количество получателей
	@P02093 NUMERIC(18,2),  -- количество произведенных выплат
	@P02094 NUMERIC(18,2) -- сумма расходов

---	
SELECT 
	@P02010 = COUNT(DISTINCT (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN NULL ELSE A.LINK END) ),
	@P02020 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 0 THEN A.LINK ELSE NULL END), 
	@P02030 = COUNT(DISTINCT (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN A.LINK ELSE NULL END) ), 
	@P02040 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 1 THEN A.LINK ELSE NULL END) 
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK
	INNER JOIN DBO.SDOC_ADIS_TABLE1 T ON T.LINK_UP = A.LINK AND T.PAYER = 0
	inner join dbo.DIS d on d.link = a.ref_arhe 
WHERE 
	A.LINK_DEP = @DEP_LINK 
	AND A.FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(A.[DATE]) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(A.[DATE]) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ
	and isnull(D.REF_DOC,0) = 0

---	
SELECT 
	@P02013 = SUM( (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END) * ISNULL(A.FSS_DAYS,0)), --(DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	@P02023 = SUM( (CASE WHEN STATUS_EMPL = 3 THEN 1 ELSE 0 END) * (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02033 = SUM(  COALESCE(A.DEKRET,0)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02043 = SUM( (CASE WHEN STATUS_EMPL = 3  AND COALESCE(A.DEKRET,0) = 1 THEN 1 ELSE 0 END)  * ISNULL(A.FSS_DAYS,0))--* (DATEDIFF(DAY,T.DATE1, T.DATE2)+1) )	
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK 
WHERE 
	LINK_DEP = @DEP_LINK 
	AND FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(DATE) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(DATE) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ

SELECT P.F4FSS, E.[STATUS], CNT_EMPL = COUNT(DISTINCT J.LINK_EMPL), CNT = COUNT( J.LINK_EMPL),SUMMA = SUM(SUMMA), CNT_DAYS = SUM([DAYS])
INTO #ATR_4FSS
FROM 
	dbo.ATRIBUT_F4FSS A
	INNER JOIN dbo.PAYS P ON A.LINK = P.F4FSS
	INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
	INNER JOIN DBO.SA_EMPLS_INFO(@END_DATE, DEFAULT) E ON E.EMPL_LINK = J.LINK_EMPL 	
WHERE
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3
	and J.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1	
	and P.F4FSS > 1
	AND J.LINK_EKR = (SELECT LINK FROM KOSGU WHERE CODE = '213')	
GROUP BY 	
	P.F4FSS, E.[STATUS]

--ВЫПЛАТА ПОСОБИЙ По временной нетрудоспособности
-----Число дней на больничном
INSERT INTO #RES2 --код=табл. 02, строка 01
SELECT '0201', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2),0), --ISNULL(@P02014,0), 
	@P02013, @P02010
	

-----Число дней на больничном по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 02
SELECT '0202', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2 AND [STATUS] = 3),0),--ISNULL(@P02024,0), 
	@P02023, @P02020

-----Число дней по берем и родам
INSERT INTO #RES2 --код=табл. 02, строка 03
SELECT '0203', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3),0),--@P02034, 
	@P02033, @P02030


-----Число дней по берем и родам по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 04
SELECT '0204', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3 AND [STATUS] = 3),0),--@P02044, 
	@P02043, @P02040

INSERT INTO #RES2
SELECT '0205', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 4),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 4),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 4),0)	

INSERT INTO #RES2
SELECT '0206', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 5),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 5),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 5),0)	

---- Ежемесячное пособие по уходу за ребенком по основному месту работы
INSERT INTO #RES2
SELECT '0208',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 6),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 6),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 6),0)	

INSERT INTO #RES2
SELECT '0209',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 7),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 7),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 7),0)	

INSERT INTO #RES2
SELECT '0210', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 8),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 8),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 8),0)	

INSERT INTO #RES2
SELECT '0211', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 9),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 9),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 9),0)		

--Р1.ТАБЛИЦА 3

Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 2)

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY GT.PERS_LINK, MONTH(G.[DATE])

CREATE TABLE #DGH_CJ (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA NUMERIC(18,6))
INSERT INTO #DGH_CJ (PERS_LINK, PERIOD_BEGIN, SUMMA)
SELECT PERS_LINK, PERIOD_BEGIN, SUM(SUMMA)
FROM dbo.CALCULATE_JURNAL CJ
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	INNER JOIN DBO.PAYS P ON P.LINK = CJ.LINK_PAYS
WHERE
	yEAR(CJ.period_begin) = @nYEAR
	AND CJ.LINK_DEP = @DEP_LINK
	AND P.[OBJECT] = 1
GROUP BY
	PERS_LINK, PERIOD_BEGIN

---------
SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO)
INTO #SALARY_SUM2
FROM 
(
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END) --на которые не начисляются страховые взносы
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B.SUMMA_BASE,0)) --на которые не начисляются страховые взносы
from 
	#DGH_CJ CJ
	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
	
--Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2 SELECT '030103', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2
INSERT INTO #RES2 SELECT '030104', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '030105', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '030106', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH3

DECLARE @TMP_VAL NUMERIC(18,2)
--Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ
--INV_M теперь содержит только льготы (100 тыс инвалидам теперь нет)
SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN ) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2),0)
INSERT INTO #RES2 VALUES('030203', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030204', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030205', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030206', @TMP_VAL, 0, 0)


DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @LIMIT = ISNULL(@LIMIT,0)


--  тариф, применяемый  свыше установленного предела величины базы (%)
DECLARE 
	@PERCENT1 NUMERIC(18,2),
	@PERCENT1_IN NUMERIC(18,2)
--	@PERCENT_FSS NUMERIC(18,2)

-- Рабочие 	
SELECT @PERCENT1 = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	predel = @LIMIT
	and tarif =1
	and 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
-- нивалиды
SELECT @PERCENT1_IN = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	predel = @LIMIT
	and tarif =3
	and 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @PERCENT1 = ISNULL(@PERCENT1,0)
SET @PERCENT1_IN = ISNULL(@PERCENT1_IN,0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
WHERE
	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0
	
--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24 
INSERT INTO #RES2 SELECT '030303', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M <= @nMONTH3
INSERT INTO #RES2 SELECT '030304', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH1
INSERT INTO #RES2 SELECT '030305', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH2
INSERT INTO #RES2 SELECT '030306', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH3

--из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы
SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1KATEG3 FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2KATEG3
FROM 
	#SPR_ESN1KATEG3 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1KATEG3 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1KATEG3 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
WHERE
	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3),0)
INSERT INTO #RES2 VALUES('030503', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030504', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030505', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030506', @TMP_VAL, 0, 0)


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
IF ISNULL(@PERCENT1,0) > 0
BEGIN

	--Вычисление погрешности для накопительной части	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030103' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030203' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030303' THEN BASE_FSS  ELSE 0 END)
				) * @PERCENT1/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR in ('0123', '0124','0125'))
			) / (@PERCENT1/100)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030104' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030204' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030304' THEN BASE_FSS  ELSE 0 END)
				) * @PERCENT1/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0123')
			) / (@PERCENT1/100)	
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030105' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030205' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030305' THEN BASE_FSS  ELSE 0 END)
				) * @PERCENT1/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0124')
			) / (@PERCENT1/100)			
		),
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030106' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030206' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030306' THEN BASE_FSS  ELSE 0 END)
				) * @PERCENT1/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0125')
			) / (@PERCENT1/100)							
		)
	FROM #RES2
	WHERE
		CODE_STR IN ('030103', '030203', '030303','030104', '030204', '030304','030105', '030205', '030305','030106', '030206', '030306')

	UPDATE #RES2
	SET BASE_FSS = BASE_FSS + ISNULL(@C3N,0)			 
	WHERE 
		CODE_STR = '030203'
	
	UPDATE #RES2
	SET BASE_FSS = BASE_FSS + ISNULL(@C4N,0)			 
	WHERE 
		CODE_STR = '030204'
		
	UPDATE #RES2
	SET BASE_FSS = BASE_FSS + ISNULL(@C5N,0)			 
	WHERE 
		CODE_STR = '030205'
		
	UPDATE #RES2
	SET BASE_FSS = BASE_FSS + ISNULL(@C6N,0)			 
	WHERE 
		CODE_STR = '030206'	
end


-- Тоже выводим по физлицу в таблицу 3.1
CREATE TABLE #RAZD31 (LINK INT, COL5 NUMERIC(18,2), COL6 NUMERIC(18,2), COL7 NUMERIC(18,2), COL8 NUMERIC(18,2))

INSERT INTO #RAZD31 (LINK, COL5, COL6, COL7, COL8)
SELECT DISTINCT 
	P.REF_PHYS_PERS,
	S5 = ISNULL(S51.SUMMA,0) - ISNULL(S52.SUMMA,0),
	S6 = ISNULL(S61.SUMMA,0) - ISNULL(S62.SUMMA,0),
	S7 = ISNULL(S71.SUMMA,0) - ISNULL(S72.SUMMA,0),
	S8 = ISNULL(S81.SUMMA,0) - ISNULL(S82.SUMMA,0)
FROM 
	#SPR_ESN P

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 GROUP BY REF_PHYS_PERS) S51 ON S51.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3 GROUP BY REF_PHYS_PERS) S52 ON S52.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1 GROUP BY REF_PHYS_PERS) S61 ON S61.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1 GROUP BY REF_PHYS_PERS) S62 ON S62.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2 GROUP BY REF_PHYS_PERS) S71 ON S71.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2 GROUP BY REF_PHYS_PERS) S72 ON S72.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3 GROUP BY REF_PHYS_PERS) S81 ON S81.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3 GROUP BY REF_PHYS_PERS) S82 ON S82.REF_PHYS_PERS = P.REF_PHYS_PERS
	
WHERE KATEG = 3

DECLARE @Table_Razd31 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd31 OUTPUT
EXEC ('select * INTO ' + @Table_Razd31 + ' from #RAZD31')
EXEC dbo.BufferPush -116, @Table_Razd31

--Используется в хранимке SA_4FSS_28022011_PREPARE_INV

--Р3.ТАБЛИЦА 9

Declare @StBase5 table (link int)
Insert into @StBase5 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 5)

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(CASE WHEN GT.WAY_CALC  = 5 THEN GT.SUMMA_BASE ELSE 0 END)
INTO #DGH_FAKT_BASE2
FROM 
	dbo.DOCUMENTS_DGH G 
	--INNER JOIN dbo.DOCUMENTS_DGH_T1 T1 ON T1.LINK = G.LINK
	--INNER JOIN dbo.REESTR_DGH R ON R.LINK = T1.LINK_DOG  --AND FLAG_TRAVMA = 1	
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK --AND T1.PERS_LINK = GT.PERS_LINK 
WHERE 
	G.LINK_DEP = @DEP_LINK
	AND FLAG_JC = 1
	--AND GT.WAY_CALC  = 5
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY   GT.PERS_LINK,  MONTH(G.[DATE]) /*, GT.WAY_CALC*/


SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I)
INTO #SALARY_SUM
FROM 
(
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) AND I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase5 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN DBO.PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK 
			AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
			--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(CJ.SUMMA),
	SUMMA_NO = SUM( CJ.SUMMA - ISNULL(B.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END)
from 
	#DGH_CJ CJ
	INNER JOIN #DGH_FAKT_BASE2 B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK 
		AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
		--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
------------------------

--Льготы по травматизму
DECLARE @LINK_S_OBJ INT
SET @LINK_S_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')

CREATE TABLE #TRAVM_LGOTY (I TINYINT, M TINYINT, SUMMA NUMERIC(18,2))
--скидки по травматизму
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_SKIDKI S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])
	
----Вычеты по травматизму	
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_VYCHET S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])	

--Данные для таблицы 6
CREATE TABLE #TABLE6 (MON TINYINT, SUMMA3 NUMERIC(18,2), SUMMA4 NUMERIC(18,2), SUMMA5 NUMERIC(18,2) )
INSERT INTO #TABLE6 (MON, SUMMA3, SUMMA4, SUMMA5)
SELECT 
	M.NUM, 
	SUMMA3 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL)-SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/,
	SUMMA4 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL_I)-SUM(SUMMA_NO_I) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE I = 1 AND M = M.NUM),0) /*,0)*/,
	SUMMA5 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) + ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/
FROM
	dbo.MONTHS M
	
	
INSERT INTO #RES2 SELECT '060103', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060104', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6) ,0), 0, 0
INSERT INTO #RES2 SELECT '060105', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060303', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH1) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060304', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
INSERT INTO #RES2 SELECT '060305', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060403', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH2) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060404', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
INSERT INTO #RES2 SELECT '060405', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060503', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH3) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060504', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0
INSERT INTO #RES2 SELECT '060505', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0

--Р3.ТАБЛИЦА 10
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA = SUM(SUMMA)
INTO 
	#SALARY_SUM1
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and CJ.LINK_PAYS = (select top 1 link from pays where object = 3 and way_calc = 5)
GROUP BY
	Month(CJ.PERIOD_BEGIN)

INSERT INTO #RES2 SELECT '1021', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON < @nMONTH1
INSERT INTO #RES2 SELECT '1023', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '1024', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '1025', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH3

INSERT INTO #RES2
SELECT '1101', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10),0),	
	0

INSERT INTO #RES2
SELECT '1102', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),	
	0	
	
INSERT INTO #RES2
SELECT '1104', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11),0),	
	0

INSERT INTO #RES2
SELECT '1105', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),	
	0		

INSERT INTO #RES2
SELECT '1107', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 12),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 12),0),	
	0

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferPush -115, @Table_Razd1

DROP TABLE #RES2
DROP TABLE #SPR_ESN
DROP TABLE #ATR_4FSS
DROP TABLE #DGH_FAKT_BASE
DROP TABLE #SALARY_SUM2
DROP TABLE #SPR_ESN1
DROP TABLE #SPR_ESN2
DROP TABLE #SPR_ESN1KATEG3
DROP TABLE #SPR_ESN2KATEG3
DROP TABLE #RAZD31
DROP TABLE #DGH_FAKT_BASE2
DROP TABLE #SALARY_SUM
DROP TABLE #SALARY_SUM1
DROP TABLE #TRAVM_LGOTY
DROP TABLE #TABLE6






GO


GRANT EXECUTE ON dbo.[RSA_4FSS_09022012_PREPARE] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_WEB_MUST]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_MUST]
GO



/*
	© Кейсистемс (Keysystems), 2006
	Собрать свод в WEB
*/

CREATE       PROCEDURE dbo.RO_WEB_MUST
AS

	/* Список возвращаемых таблиц */
	SELECT	[alias] = 'REPORT_MUST', 
		[order] = convert(smallint,1),
		[tab_name] = 'Требуемые к сдаче отчеты:',
		[link_table] = convert(varchar(50), 'REPORT_MUST'),--convert(int,0),
		[table_type] = convert(smallint,0)

declare @date datetime, @day tinyint, @month tinyint, @year smallint, @dEndDate datetime, @LinkHistory int
exec X_GET_PERIOD_END   @dEndDate output
select @LinkHistory = dbo.RO_SVOD_TREE_Link_History(@dEndDate)

set @date = getdate()
set @year = YEAR(@date)
set @month = MONTH(@date)
set @day = DAY(@date)
declare @tree table(link int, parent int, hasChildren bit)
declare @t_tree_with_access table (link int, parent int, hasChildren bit)

	insert @t_tree_with_access(link, parent, hasChildren)
	select	link,
			[parent] = link_self,
			[hasChildren] = case childrens when 1 then 0 else 1 end
		from dbo.RO_SVOD_TREE T inner join dbo.user_form_access ufa on  link_history = @LinkHistory and ufa.dep_link = T.link_report_org and ufa.budg_link = T.link_report_budg and ufa.SID = suser_sid() order by orders 

insert @tree
		select link, parent, hasChildren
		from @t_tree_with_access T1
		where parent is not NULL and not exists(select * from @t_tree_with_access T2 where T1.parent = T2.link) -- у которого нет отца

declare @t_days_month table (m tinyint, d tinyint)
insert @t_days_month
select 1 as m ,31 as d
union all
select 2 as m ,case YEAR(GETDATE()) %4 when 0 then 29 else 28 end as d
union all
select 3 as m ,31 as d
union all
select 4 as m ,30 as d
union all
select 5 as m ,31 as d
union all
select 6 as m ,30 as d
union all
select 7 as m ,31 as d
union all
select 8 as m ,31 as d
union all
select 9 as m ,30 as d
union all
select 10 as m ,31 as d
union all
select 11 as m ,30 as d
union all
select 12 as m ,31 as d


declare @task table (task varchar(50), date_end datetime, code_form varchar(50), name_form varchar(254), stage varchar(50), hyperlink varchar(20), link bigint, nm varchar(254), budg varchar(254), nodelink int, obj varchar(30), link_form INT, ISRO int)

insert @task
select distinct RM.name as task, ltrim(str(isnull(year2, @year))) +  case len(ltrim(str(isnull(month2, @month)))) when 1 then '0' + ltrim(str(isnull(month2, @month))) else ltrim(str(isnull(month2, @month))) end + case len(ltrim(str(coalesce(DM.d, day2, @day)))) when 1 then '0' + ltrim(str(coalesce(DM.d, day2, @day))) else ltrim(str(coalesce(DM.d, day2, @day))) end as date_end,
		F.Code, F.name as name_form, 
		'Нет отчета' as stage,
		'' as hyperlink, --case T.hasChildren when 1 then 'Собрать свод' else 'Создать отчет' end as hyperlink,
		case T.haschildren when 1 then -(convert(bigint,F.Link_Form) + 8589934592) else -F.Link_Form end, 
		D.name as nm, B.name, T.link as nodelink,
		case T.hasChildren when 0 then 'REPORT_SVOD' else  case isnull(atributs,'') when '' then 'REPORT_WEB_SVOD' else 'REPORT_WEB_SVOD_ATR' end end as obj,
		F.Link_Form, -1
from report_must RM 
	inner join report_must_users RMU on RM.Link = RMU.link_report_must
	left join @t_days_month DM on DM.m = isnull(RM.month2, @month) and RM.day2 > DM.d
	inner join (select CASE WHEN sy.issqlrole = 1 THEN sg.sid ELSE sy.SID END as SID,
				sy.name
				from dbo.sysusers sy left join dbo.S_GROUP_SID sg on sy.uid = sg.uid
				where sy.sid = suser_sid() or IS_MEMBER(sg.name) = 1) u on RMU.sid = U.sid
	inner join report_form_groups_ref RFGR on RFGR.link_form_groups = RM.link_form_groups
	inner join i_report_forms F on F.Link_Form = RFGR.link_form
	left join @tree T on 1=1
	left join dictionary_department D on D.link = dbo.RO_SVOD_ORG(T.link)
	left join dbo.KL_BUDG_TYPE B on B.Link = dbo.RO_SVOD_BUDG(T.link)
where @date >= dateadd(day, isnull(day1,@day) - 1, dateadd(month,isnull(month1,@month) - 1, convert(datetime, LTRIM(RTRIM(STR(isnull(year1, @year)))) + '0101', 112)))
	and @date <= dateadd(day, isnull(day2,@day) - 1, dateadd(month,isnull(month2,@month) - 1, convert(datetime, LTRIM(RTRIM(STR(isnull(year2, @year)))) + '0101', 112)))
--@day >= isnull(day1, 0) and @day <= isnull(day2,31) and @month >= isnull(month1,0) and @month <= isnull(month2, 12)and @year >= isnull(year1, 0) and @year <= isnull(year2,3000)

	and F.Start_Date = (select max(Start_Date) from report_forms F1 where F1.Code = F.Code)
	and F.End_DATE is NULL

update @task
set stage = status_name,
	hyperlink = 'Переход',
	link = link_saved_form,
	obj = case isnull(rtrim(RF.object),'') when '' then 'REPORT_FORMS_TABLES' else substring(RF.object, 1, charindex('#',RF.object) - 1) END,
   [ISRO] = rsf.[IsRO]
from @task T, report_saved_forms RSF left join report_status RS on RS.status = RSF.IsRO left join report_forms RF on RSF.link_form = RF.link_form
where RSF.link_form = T.Link_form AND RSF.del = 0 and dbo.RO_SVOD_ORG(T.nodelink) = RSF.Link_Organization and dbo.RO_SVOD_BUDG(T.nodelink) = RSF.link_type_svod
	and RSF.begin_Date = (select max(begin_Date) from report_saved_forms RSF1 where RSF.link_form = RSF1.link_form and begin_Date  <  T.date_end)
	and RSF.Version = (select max(version) from report_saved_forms RSF2 WHERE RSF2.del = 0 AND RSF.link_form = RSF2.link_form and RSF.begin_date = RSF2.begin_date and RSF.Link_Organization = RSF2.Link_Organization and RSF.Link_Type_Svod = RSF2.Link_Type_Svod)

select distinct task, date_end, code_form, name_form, stage, hyperlink, link, nm, budg, nodelink, obj, link_form, ISRo from @task
GO
GRANT ALL ON dbo.[RO_WEB_MUST] 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.[RO_EXPORT_FORM_466]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_466]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_466]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

--перенос формы из архивной базы
EXEC dbo.[RN_MOVE_FORM_FROM_ARH] @iLINK_SAVED_FORM

declare @iReturn int, @vcVersion varchar(100), @subjectCode varchar(100), @subjectName varchar(254), @dBEGIN_DATE datetime, @cDate varchar(10),
	 @vcFILE_NAME_ARH varchar(100), @iLINK_TABLE int, @iLINK_FORM int, @vcExec varchar(8000), @NameOrg varchar(254), @NameBudg varchar(254), @LinkOrg int, @ExportCodeForm varchar(10), @strKS varchar(8000), @KS INT, @cDateSign varchar(8),
    @ID VARCHAR(100), @cDateCreate VARCHAR(30), @vcTmpTable VARCHAR(1000), @nvExecStr NVARCHAR(4000)
    
SET @cDateCreate = LEFT(CONVERT(VARCHAR(30), GETDATE(), 126),19)    
    
SET @ID = replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '')

CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							  [ORDERS] INT IDENTITY(1,1))

CREATE TABLE #tabXML1 ([TXT]	  VARCHAR(8000),
							  [ORDERS] INT IDENTITY(1,1))

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

select @subjectCode = RTRIM(subject_Code), @subjectName = RTRIM(Subject_Name) from dbo.I_REPORT_OPTIONS_EXPORT

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL
BEGIN
   SELECT @vcVersion = [VERSION]
   FROM #tabExportOutput 
END

SELECT  @iLINK_FORM = RSF.Link_Form, @LinkOrg = Link_Organization, @dBEGIN_DATE = [BEGIN_DATE], @NameOrg = isnull(LEFT(RTRIM(dbo.GetDepName(Link_Organization, begin_date)),250),''), @NameBudg = isnull(LEFT(isnull(RTRIM(B.Name),''),250),'')
FROM dbo.[REPORT_SAVED_FORMS] RSF left join kl_budg_type B on RSF.Link_Type_Svod = B.Link
	left join dictionary_department D on D.Link = RSF.Link_Organization
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

set @cDate = convert(varchar(10), @dBEGIN_DATE+1, 4)
SET @cDateSign =convert(varchar(8),  isnull((SELECT MAX(rs.[date]) FROM dbo.[REPORT_SIGN] rs WHERE rs.[lsf] = @iLINK_SAVED_FORM), GETDATE()), 4)

set @KS = 0
set @strKS = ''
SET @ExportCodeForm = '691'

SELECT @vcFILE_NAME =  @ID + '.xml',
	   @vcFILE_NAME_ARH = @ID + '.zip'
      
EXEC dbo.X_GET_TABLE_NAME @vcTmpTable OUTPUT     

-- Заполнение шапки пакета.
EXEC dbo.[ВЕРСИЯ] @vcVersion OUTPUT, 0
INSERT #tabXML([TXT]) VALUES ('<?xml version="1.0" encoding="windows-1251"?>')
INSERT #tabXML([TXT]) VALUES ('<PacketED SoftWareProduct="Свод-КС" SoftWareProductVersion="' + REPLACE(@vcVersion,'Версия ','') + '" FormatVersion="2012.04">')
INSERT #tabXML([TXT]) VALUES ('	<From Name="' + LEFT(dbo.[RA_XML_MASK](@subjectName),250) + '" CodeReg="'+LEFT(dbo.[RA_XML_MASK](@subjectCode),2)+'"/>')
INSERT #tabXML([TXT]) VALUES ('	<To Name="Минфин России" Code="092"/>')
INSERT #tabXML([TXT]) VALUES ('	<Inf Name="Сведения об исполнении Соглашений  по предоставлению дотаций на поддержку мер по обеспечению сбалансированности бюджетов субъектов Российской Федерации и бюджетных кредитов на реализацию мер по поддержке монопрофильных муниципальных образований, предоставленных из федерального бюджета в 2010 году." Code="466" />')
INSERT #tabXML([TXT]) VALUES ('	<DateRegl>'+@cDate+'</DateRegl>')
INSERT #tabXML([TXT]) VALUES ('	<Period>месячная</Period>')
INSERT #tabXML([TXT]) VALUES ('	<EI>руб.</EI>')

INSERT #tabXML([TXT]) VALUES ('	<ED01>') -- первый раздел

set @strKS = @strKS + @cDate -- вычисление контрольного числа

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 1


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str01 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) + ''" PlanSogl="'' + RTRIM(LTRIM(STR(COL3,20,2))) + ''" Fakt="'' + RTRIM(LTRIM(STR(COL4,20,2))) + ''" Vsego="'' + RTRIM(LTRIM(STR(COL5,20,2))) + ''" Dot="'' + RTRIM(LTRIM(STR(COL6,20,2)))  + ''" Kred="'' + RTRIM(LTRIM(STR(COL7,20,2))) + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2)))
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED01>') -- конец первого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED02>') -- второй раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 2


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str02 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" FB2010Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" FB2010Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" BS2010="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" MB2010="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" VnI2010="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" Itg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" FB2011Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" FB2011Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" BS2011="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" MB2011="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" VnI2011="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" Itg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" FB2012Dot="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" FB2012Kred="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" BS2012="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" MB2012="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" VnI2012="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" Itg2012="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
      + RTRIM(LTRIM(STR(COL12,20,2))) + RTRIM(LTRIM(STR(COL13,20,2))) + RTRIM(LTRIM(STR(COL14,20,2))) + RTRIM(LTRIM(STR(COL15,20,2))) + RTRIM(LTRIM(STR(COL16,20,2))) + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2)))
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED02>') -- конец второго раздела
INSERT #tabXML([TXT]) VALUES ('	<ED03>') -- третий раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 3


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)


SET @vcExec = 'SELECT ''    <Str03 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" FFB2010Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" FFB2010Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" FBS2010="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" FMB2010="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" FVnI2010="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" FItg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" FFB2011Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" FFB2011Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" FBS2011="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" FMB2011="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" FVnI2011="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" FItg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" FVsego2011="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" FFB2012Dot="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" FFB2012Kred="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" FBS2012="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" FMB2012="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" FVnI2012="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" FItg2012="'' + RTRIM(LTRIM(STR(COL21,20,2)))
            + ''" FVsego2012="'' + RTRIM(LTRIM(STR(COL22,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
      + RTRIM(LTRIM(STR(COL12,20,2))) + RTRIM(LTRIM(STR(COL13,20,2))) + RTRIM(LTRIM(STR(COL14,20,2))) + RTRIM(LTRIM(STR(COL15,20,2))) + RTRIM(LTRIM(STR(COL16,20,2))) + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2))) + RTRIM(LTRIM(STR(COL21,20,2))) + RTRIM(LTRIM(STR(COL22,20,2)))
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED03>') -- конец третьего раздела
INSERT #tabXML([TXT]) VALUES ('	<ED04>') -- четвертый раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 4


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str04 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" KFB2010Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" KFB2010Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" KBS2010="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" KMB2010="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" KVnI2010="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" FItg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" KFB2011Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" KFB2011Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" KBS2011="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" KMB2011="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" KVnI2011="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" KItg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" KFB2012Dot="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" KFB2012Kred="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" KBS2012="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" KMB2012="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" KVnI2012="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" KItg2012="'' + RTRIM(LTRIM(STR(COL20, 20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
      + RTRIM(LTRIM(STR(COL12,20,2))) + RTRIM(LTRIM(STR(COL13,20,2))) + RTRIM(LTRIM(STR(COL14,20,2))) + RTRIM(LTRIM(STR(COL15,20,2))) + RTRIM(LTRIM(STR(COL16,20,2))) + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2))) 
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED04>') -- конец четвертого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED05>') -- пятый раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 5


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str05 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" AFB2010Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" AFB2010Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" ABS2010="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" AMB2010="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" AVnI2010="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" AItg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" AFB2011Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" A2011Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" ABS2011="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" AMB2011="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" AVnI2011="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" AItg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" AFB2012Dot="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" AFB2012Kred="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" ABS2012="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" AMB2012="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" AVnI2012="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" AItg2012="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
      + RTRIM(LTRIM(STR(COL12,20,2))) + RTRIM(LTRIM(STR(COL13,20,2))) + RTRIM(LTRIM(STR(COL14,20,2))) + RTRIM(LTRIM(STR(COL15,20,2))) + RTRIM(LTRIM(STR(COL16,20,2))) + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2))) 
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED05>') -- конец пятого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED06>') -- шестой раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 6


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str06 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" DFB2010Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" DFB2010Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" DBS2010="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" DMB2010="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" DVnI2010="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" DItg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" DFB2011Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" D2011Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" DBS2011="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" DMB2011="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" DVnI2011="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" DItg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" DFB2012Dot="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" DFB2012Kred="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" DBS2012="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" DMB2012="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" DVnI2012="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" DItg2012="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
      + RTRIM(LTRIM(STR(COL12,20,2))) + RTRIM(LTRIM(STR(COL13,20,2))) + RTRIM(LTRIM(STR(COL14,20,2))) + RTRIM(LTRIM(STR(COL15,20,2))) + RTRIM(LTRIM(STR(COL16,20,2))) + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2))) 
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED06>') -- конец шестого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED07>') -- седьмой раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 7


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str07 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" Beg2011Dot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" Beg2011Kred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" Beg2011Itg="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" End2011Dot="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" End2011Kred="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" End2011Itg="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" End2012Dot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" End2012Kred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" End2012Itg="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED07>') -- конец седьмого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED08>') -- восьмой раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 8


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str08 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" Beg2011FBDot="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" Beg2011FBKred="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" Beg2011BS="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" Beg2011MB="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" Beg2011VnI="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" ZItg2010="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" End2011FBDot="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" End2011FBKred="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" End2011BS="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" End2011MB="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" End2011VnI="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" ZItg2011="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" End2012FBDot="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" End2012FBKred="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" End2012BS="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" End2012MB="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" End2012VnI="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" ZItg2012="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
 + RTRIM(LTRIM(STR(COL12,20,2)))  + RTRIM(LTRIM(STR(COL13,20,2)))  + RTRIM(LTRIM(STR(COL14,20,2)))  + RTRIM(LTRIM(STR(COL15,20,2)))  + RTRIM(LTRIM(STR(COL16,20,2)))  + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2)))    
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED08>') -- конец восьмого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED09>') -- девятый раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 9


SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) + ',@tmp_table='+@vcTmpTable
 

execute(@vcExec)

SET @vcExec = 'SELECT ''    <Str09 KodMonG="'' + LEFT(CODE,2) + ''" KodStr="'' + RTRIM([CODE]) 
            + ''" T2010Plan="'' + RTRIM(LTRIM(STR(COL3,20,2))) 
            + ''" T2010PlanEnd="'' + RTRIM(LTRIM(STR(COL4,20,2))) 
            + ''" T2010Fakt="'' + RTRIM(LTRIM(STR(COL5,20,2))) 
            + ''" T2010FaktEnd="'' + RTRIM(LTRIM(STR(COL6,20,2)))  
            + ''" T2010PrMPlan="'' + RTRIM(LTRIM(STR(COL7,20,2))) 
            + ''" T2010PrMFakt="'' + RTRIM(LTRIM(STR(COL8,20,2)))
            + ''" T2011Plan="'' + RTRIM(LTRIM(STR(COL9,20,2)))
            + ''" T2011PlanEnd="'' + RTRIM(LTRIM(STR(COL10,20,2)))
            + ''" T2011Fakt="'' + RTRIM(LTRIM(STR(COL11,20,2)))
            + ''" T2011FaktEnd="'' + RTRIM(LTRIM(STR(COL12,20,2)))
            + ''" T2011PrMPlan="'' + RTRIM(LTRIM(STR(COL13,20,2)))
            + ''" T2011PrMFakt="'' + RTRIM(LTRIM(STR(COL14,20,2)))
            + ''" T2011FaktM="'' + RTRIM(LTRIM(STR(COL15,20,2)))
            + ''" T2012Plan="'' + RTRIM(LTRIM(STR(COL16,20,2)))
            + ''" T2012PlanEnd="'' + RTRIM(LTRIM(STR(COL17,20,2)))
            + ''" T2012Fakt="'' + RTRIM(LTRIM(STR(COL18,20,2)))
            + ''" T2012FaktEnd="'' + RTRIM(LTRIM(STR(COL19,20,2)))
            + ''" T2012PrMPlan="'' + RTRIM(LTRIM(STR(COL20,20,2)))
            + ''" T2012PrMFakt="'' + RTRIM(LTRIM(STR(COL21,20,2)))
            + ''" T2012FaktM="'' + RTRIM(LTRIM(STR(COL22,20,2)))
            + ''" T2010PlanN="'' + RTRIM(LTRIM(STR(COL23,20,2)))
            + ''" T2010FaktN="'' + RTRIM(LTRIM(STR(COL24,20,2)))
            + ''" T2011PlanN="'' + RTRIM(LTRIM(STR(COL25,20,2)))
            + ''" T2011FaktN="'' + RTRIM(LTRIM(STR(COL26,20,2)))
            + ''" T2012PlanN="'' + RTRIM(LTRIM(STR(COL27,20,2)))
            + ''" T2012FaktN="'' + RTRIM(LTRIM(STR(COL28,20,2)))
            + ''" /> 
''
from ' + @vcTmpTable + '
where del = 0 '
 

INSERT #tabXML([TXT])
EXECUTE (@vcExec)

SET @nvExecStr = 'select @strKS = @strKS + LEFT(CODE,2) + RTRIM([CODE]) + RTRIM(LTRIM(STR(COL3,20,2))) + RTRIM(LTRIM(STR(COL4,20,2))) + RTRIM(LTRIM(STR(COL5,20,2))) + RTRIM(LTRIM(STR(COL6,20,2))) + RTRIM(LTRIM(STR(COL7,20,2))) + RTRIM(LTRIM(STR(COL8,20,2))) + RTRIM(LTRIM(STR(COL9,20,2))) + RTRIM(LTRIM(STR(COL10,20,2))) + RTRIM(LTRIM(STR(COL11,20,2))) 
 + RTRIM(LTRIM(STR(COL12,20,2)))  + RTRIM(LTRIM(STR(COL13,20,2)))  + RTRIM(LTRIM(STR(COL14,20,2)))  + RTRIM(LTRIM(STR(COL15,20,2)))  + RTRIM(LTRIM(STR(COL16,20,2)))  + RTRIM(LTRIM(STR(COL17,20,2))) + RTRIM(LTRIM(STR(COL18,20,2))) + RTRIM(LTRIM(STR(COL19,20,2))) + RTRIM(LTRIM(STR(COL20,20,2)))    
 + RTRIM(LTRIM(STR(COL21,20,2)))  + RTRIM(LTRIM(STR(COL22,20,2)))  + RTRIM(LTRIM(STR(COL23,20,2)))  + RTRIM(LTRIM(STR(COL24,20,2)))  + RTRIM(LTRIM(STR(COL25,20,2)))  + RTRIM(LTRIM(STR(COL26,20,2))) + RTRIM(LTRIM(STR(COL27,20,2))) + RTRIM(LTRIM(STR(COL28,20,2)))
from ' + @vcTmpTable + '
where del = 0 drop table ' + @vcTmpTable

EXECUTE sp_executesql @nvExecStr, N'@strKS varchar(8000) output', @strKS = @strKS OUTPUT 


INSERT #tabXML([TXT]) VALUES ('	</ED09>') -- конец девятого раздела
INSERT #tabXML([TXT]) VALUES ('	<ED10>') -- десятый раздел


INSERT #tabXML([TXT])
SELECT '		<Str10_01 NumStr="01" ChiefPost="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(CHIEF_POST,'')),250)) 
         + '" ChiefFio="' + RTRIM(dbo.[RA_XML_MASK](LEFT(ISNULL(CHIEF,''),250))) 
         + '" ExecutorPost="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(POST,'')),250)) 
         + '" ExecutorFio="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(FIO,'')),250)) 
         + '" ExecutorPhone="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(PHONES,'')),15)) 
         + '" Comment="" DtSigning="' + @cDateSign + '" /> '
FROM dbo.[PrintDoc_GetDepData2](@LinkOrg) P full join dbo.[RA_GET_USER_INFO](NULL) U on 1 = 1

select @strKS = @strKS + '01' + LEFT(RTRIM(isnull(CHIEF_POST,'')),250) + RTRIM(LEFT(ISNULL(CHIEF,''),250)) + LEFT(RTRIM(isnull(POST,'')),250) + LEFT(RTRIM(isnull(FIO,'')),250) + LEFT(RTRIM(isnull(PHONES,'')),15) 
FROM dbo.[PrintDoc_GetDepData2](@LinkOrg) P join dbo.[RA_GET_USER_INFO](NULL) U on 1 = 1

set @KS = dbo.[RA_GET_CRC](@strKS, @KS)
set @strKS = LTRIM(RTRIM(STR(@KS)))
set @KS = dbo.[RA_GET_CRC](@strKS, 0)

INSERT #tabXML([TXT]) VALUES ('		<Str10_02 NumStr="02" KsOtch="' + LTRIM(RTRIM(STR(@KS))) + '" />')

INSERT #tabXML([TXT]) VALUES ('	</ED10>') -- конец шестого раздела
INSERT #tabXML([TXT]) VALUES ('</PacketED>')

INSERT #tabXML1(TXT)
VALUES('<?xml version="1.0" encoding="windows-1251"?>')
INSERT #tabXML1(TXT)
VALUES('<Package MF_FormType="784D5E6589394354AC41A7A45D118A19">')
INSERT #tabXML1(TXT)
VALUES('<Properties MF_PackageType="27E97A84479941A8988EF84CFCF8C276" MF_PackageSubType="1" LibVersion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '" InDateReg="1899-12-30T00:00:00" OutDateReg="1899-12-30T00:00:00">')
INSERT #tabXML1(TXT)
VALUES('<PropertyList>')
INSERT #tabXML1(TXT)
VALUES('<Property Name="CodeReg" Value="'+LEFT(dbo.[RA_XML_MASK](@subjectCode),2)+'"/>')
INSERT #tabXML1(TXT)
VALUES('<Property Name="DateRegl" Value="'+@cDate+'"/>')
INSERT #tabXML1(TXT)
VALUES('<Property Name="CodeFrm" Value="466"/>')
INSERT #tabXML1(TXT)
VALUES('</PropertyList>')
INSERT #tabXML1(TXT)
VALUES('</Properties>')
INSERT #tabXML1(TXT)
VALUES('<MF_Body>')
INSERT #tabXML1(TXT)
VALUES('<MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('<MF_ID>' + @ID + '</MF_ID>')
INSERT #tabXML1(TXT)
VALUES('<MF_BODY>')
INSERT #tabXML1(TXT)
VALUES('<!--Отчет по форме 466-->')
INSERT #tabXML1(TXT)
VALUES('<Document MF_FormType="9FB9832A5AE6438B9426AA23B0DF12B3">')
INSERT #tabXML1(TXT)
VALUES('<Properties MF_DocumentType="5B122F01E1034B33B0FE4C637F69C584" MF_DocumentSubType="1" LibVersion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '">')
INSERT #tabXML1(TXT)
VALUES('</Properties>')
INSERT #tabXML1(TXT)
VALUES(' <MF_Body MF_FormatData=".xml" MF_StoreFormat="2">')
INSERT #tabXML1(TXT)
VALUES('<MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('<MF_ID>' + replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '') + '</MF_ID>')
INSERT #tabXML1(TXT)
VALUES('<MF_BODY>#DEL13#')

INSERT #tabXML1(TXT)
SELECT dbo.RO_STR_ASCII_16(TXT)  + '#DEL13#' 
FROM #tabXML



INSERT #tabXML1(TXT)
VALUES('</MF_BODY>')
INSERT #tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('</MF_Body>')
INSERT #tabXML1(TXT)
VALUES('</Document>')
INSERT #tabXML1(TXT)
VALUES('<!-- Пояснительная записка к отчету по форме 466-->')
INSERT #tabXML1(TXT)
VALUES('<Document MF_FormType="9FB9832A5AE6438B9426AA23B0DF12B3">')
INSERT #tabXML1(TXT)
VALUES('<Properties MF_DocumentType="D6804F64E02D4E3EAD250F4E754D10F3" MF_DocumentSubType="1" LibVersion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '">')
INSERT #tabXML1(TXT)
VALUES('</Properties>')
INSERT #tabXML1(TXT)
VALUES(' <MF_Body MF_FormatData=".doc" MF_StoreFormat="2">')
INSERT #tabXML1(TXT)
VALUES('  <MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('   <MF_ID>' + replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '') + '</MF_ID>')
INSERT #tabXML1(TXT)
VALUES('   <MF_BODY></MF_BODY>')
INSERT #tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('</MF_Body>')
INSERT #tabXML1(TXT)
VALUES('</Document>')
INSERT #tabXML1(TXT)
VALUES('</MF_BODY>')
INSERT #tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT #tabXML1(TXT)
VALUES('</MF_Body>')
INSERT #tabXML1(TXT)
VALUES('</Package>')



INSERT #FileExportReport([TXT],
                         [NameFile],
                         [ORDERS],
                         [NameFileArh])
SELECT [TXT],
	    @vcFILE_NAME,
	    [ORDERS],
       @vcFILE_NAME_ARH
FROM #tabXML1
ORDER BY [ORDERS]

DROP TABLE #tabXML
DROP TABLE #tabXML1

GO
GRANT ALL ON dbo.[RO_EXPORT_FORM_466] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_SYNC_BKS_QUERY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[RT_SYNC_BKS_QUERY]
GO

CREATE procedure [dbo].[RT_SYNC_BKS_QUERY]
	@sdc char(2) = null
AS

declare @strsql varchar(1000)

if @sdc in ('ВР','ЦС','АД') begin
	set @strsql = 'select max(link) as link, [code], [cname], [name], [date_begin], [date_end] 
	from dbo.kbk 
	where [object] in 
	(select link from dbo.s_objects where code = '''+
	case @sdc 
		when 'ВР' then 'DICTIONARY_EXPEND'
		when 'ЦС' then 'DICTIONARY_TARGET_ITEM'
		when 'АД' then 'DICTIONARY_DEPARTMENT'
		else 'NOTHINGISFINDED'
	end+''')' + 
   ' group by [code], [cname], [name], [date_begin], [date_end]'
end
else begin
	if @sdc in ('ИС','ДО') begin
		set @strsql = 'select link, ''000''+right(rtrim([code]),17) as [code], [cname], [name], [date_begin], [date_end] 
		from dbo.kbk 
		where link in (
			select max(K.link) as [link]
			from (
				select        
					link,
					right(rtrim([code]),17) as [code],       
					[cname] as [cname]      
				from dbo.kbk      
				where [object] in (select link from dbo.s_objects where code = '''+
				case @sdc 
					when 'ИС' then 'DICTIONARY_KBK_SOUR'
					when 'ДО' then 'DICTIONARY_KBK_INC'
					else 'NOTHINGISFINDED'
				end+''')      
			) as K
			inner join (
				select
					A.code as [code],
					max(A.cname) as [cname]
				from 
				(select 
					right(rtrim([code]),17) as [code],
					[cname] as [cname]
				from dbo.kbk
				where [object] in 
				(select link from dbo.s_objects where code = '''+
				case @sdc 
					when 'ИС' then 'DICTIONARY_KBK_SOUR'
					when 'ДО' then 'DICTIONARY_KBK_INC'
					else 'NOTHINGISFINDED'
				end+''')
				) as A group by A.code
			) as B
			on K.code = B.code and K.cname = B.cname
			group by K.code, K.cname
		)'
	end
	else
		set @strsql = 'select 0 as link, '''' as [code], '''' as [cname], '''' as [name], null as [date_begin], null as [date_end]'
end

select @strsql as [SQLSTR]

GO
GRANT EXECUTE ON [dbo].[RT_SYNC_BKS_QUERY] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_GET_DEP_ACC') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].BB_EXPORT_GET_DEP_ACC
GO

CREATE PROCEDURE dbo.BB_EXPORT_GET_DEP_ACC 
	@iDep int output, 
	@iAcc int output, 
	@cRes varchar(8000) output, 
	@cDepINN varchar(13), 
	@cDepKPP varchar(9), 
	@cDepName varchar(254), 
	@cAccCode varchar(20), 
	@cAccBIC varchar(9), 
	@cAccName varchar(160),
	@cAccKS varchar(20)
AS	
declare @iRecCountDep int,
		@iRecCountAcc int,
		@iDepAcc int,
		@cDepNextCode varchar(10),
		@iBank int
		
if @cDepINN is null
	set @cDepINN = ''

if @cAccCode = ''
begin
	set @cRes = 'Не заполнен код Счета'
	set @iRecCountAcc = 0	
end
else
begin
	select @iDepAcc = LINK_UP, @iAcc = LINK
	from dbo.DEPARTMENT_ACCOUNTS 
	where CODE = @cAccCode 
	set @iRecCountAcc = @@RowCount
	if @iRecCountAcc = 0
	begin
		set @iAcc = 0
		set @iDepAcc = 0
	end
	if @iRecCountAcc > 1
	begin
		select @iDepAcc = LINK_UP
		from dbo.DEPARTMENT_ACCOUNTS 
		where CODE = @cAccCode
		GROUP BY LINK_UP
		set @iRecCountAcc = @@RowCount
		if @iRecCountAcc > 1 
			set @iDepAcc = 0
		set @iAcc = 0
	end
end
if @cDepINN = ''
	set @iDep = @iDepAcc
else
begin
	select @iDep = LINK
	from dbo.DEPARTMENTS 
	where INN = @cDepINN 
	set @iRecCountDep = @@RowCount
	if @iRecCountDep = 0
	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], KPP)
		values(@cDepNextCode,@cDepINN,@cDepName,@cDepName,1, @cDepKPP)
		set @iDep = @@Identity
		set @iRecCountDep = 1
		set @cRes = 'Организация ' + @cDepName + ' с ИНН: ' + @cDepINN + ' добалена в справочник'
	end
	if @iRecCountDep > 1
		if @iRecCountAcc = 1
		begin	
			set @iDep = @iDepAcc
			set @iRecCountDep = 1
		end 
		else
			set @iDep = 0
end

if @iDep <> 0 and @iDepAcc = 0 
begin
	if @iRecCountAcc > 0	
	begin
		select @iAcc = LINK
		from dbo.DEPARTMENT_ACCOUNTS 
		where CODE = @cAccCode and LINK_UP = @iDep
		set	@iRecCountAcc = @@RowCount
		if	@iRecCountAcc > 1 
			set @iAcc = 0
	
	end	
	if @iRecCountAcc = 0
	begin
		select @iBank = LINK from dbo.BANKS where BIK = @cAccBIC
		if @@RowCount = 0
		begin
			insert into dbo.BANKS(BIK, NAME, FNAME, KS)
			values(@cAccBIC, @cAccName, @cAccName, @cAccKS)
			set @iBank = @@identity
			if 	@cRes <> ''
				set @cRes = @cRes + char(13) 
			set @cRes = @cRes + 'Банк ' + @cAccName + ' с БИК: ' + @cAccBIC + ' добалена в справочник'

		end
		insert into dbo.DEPARTMENT_ACCOUNTS(CODE, [TYPE], BANK_LINK, LINK_UP)
		values(@cAccCode, 1, @iBank, @iDep) 
		set @iAcc = @@identity
		if 	@cRes <> ''
			set @cRes = @cRes + char(13) 
		set @cRes = @cRes + 'Счет ' + @cAccCode + ' добален в организацию ' + @cDepName
	end
end	
if @iDep <> 0 and @iDepAcc <> 0 and @iDep <> @iDepAcc
begin
	set @cRes = @cRes + 'Счет ' + @cAccCode + ' не пренадлежит организации ' + @cDepName
end


if @iRecCountAcc > 1 and @iRecCountDep > 1
	select @iAcc = DA.LINK, @iDep = D.LINK
	from dbo.DEPARTMENT_ACCOUNTS DA
	inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
	where D.INN = @cDepINN and DA.CODE = @cAccCode

if @@ROWCOUNT <> 1		
begin
	if @iRecCountAcc > 1
		set @iAcc = - @iRecCountAcc

	if @iRecCountDep > 1
		set @iDep = - @iRecCountDep
end



	
RETURN 1


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].[RN_CHECK_DICT_SAVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_CHECK_DICT_SAVE]
GO

/*******************************************************************************
	c Кейсистемс (Keysystems), 2006
    проверка на правильный ввод данных 
*******************************************************************************/
CREATE       procedure dbo.RN_CHECK_DICT_SAVE
    @tmpTable varchar(200), --имя временной таблички
    @dict varchar(200), --имя справочника
    @col varchar(200), --колонка в справочнике
    @col_code varchar(200), --кодовая колонка в справочнике
    @iLink_Saved_Form   INT = 0,
    @iLink_Col INT = 0
AS
    create table #err (code varchar(4000),inRep varchar(4000),inSpr varchar(4000))
    declare @cstr varchar(8000), @DictWhere VARCHAR(1000), @AddWhere VARCHAR(1000), @link_org INT, @link_budg INT, @org VARCHAR(50), @budg VARCHAR(50), @vcDate VARCHAR(10)
    
    SELECT @DictWhere = [Dictionary_Where]
      FROM dbo.report_coloumns WHERE link_col = @iLink_Col
    
    IF ISNULL(@DictWhere, '') <> ''
    BEGIN
      SELECT @link_org = rsf.[Link_Organization],
            @link_budg = rsf.[Link_Type_Svod],
             @vcDate = CONVERT(VARCHAR(10), rsf.[Begin_Date], 112)
      FROM dbo.[REPORT_SAVED_FORMS] rsf
      WHERE rsf.[Link_Saved_Form] = @iLink_Saved_Form
      
      SELECT @org = code FROM dbo.[DEPARTMENTS] d WHERE link = @link_org
      SELECT @budg = code FROM dbo.kl_budg_type WHERE [Link] = @link_budg
      
       
      SET @AddWhere =  ' and ' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DictWhere,'%link_org%',LTRIM(STR(@link_org))),'%link_budg%',LTRIM(STR(@link_budg))),'%org%','''' + LTRIM(@org) + ''''),'%budg%','''' + LTRIM(isnull(@budg,'')) + ''''), '%date%', 'convert(datetime,''' + @vcDate + ''',112)')   
    END
    ELSE
       SET @AddWhere = ''
     
    set @cstr='insert #err SELECT CODE,CODE_CHECK,(SELECT top 1 '+@col+' FROM '+@DICT+' B WHERE A.code='+@col_code+ @AddWhere+')'+@col+' FROM '+@tmpTable+' A WHERE NOT EXISTS(SELECT * FROM '+@DICT+' B WHERE A.code='+@col_code+' and  left(A.code_check,100)=left(B.'+@col+',100) ' + @AddWhere + ') order by 1'
    print @cstr
    exec(@cstr)
    select * from #err
GO
GRANT ALL ON dbo.[RN_CHECK_DICT_SAVE] 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.[KO_PUNKT_POSTANOV_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KO_PUNKT_POSTANOV_SAVE]

GO


CREATE  PROCEDURE dbo.KO_PUNKT_POSTANOV_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparCODE           VARCHAR(10) = null,
	@varKSparNAME           VARCHAR(2000) = null,
    @varKSparPRIK_TYP_N		VARCHAR(254) = null,
	@varKSparPRIK_TYP		INT
AS 
	DECLARE 
		@varKSERROR	int,
		@varKSRowCount int,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,
		@varKSEventText	varchar(254), 
		@varKSObject INT

	SET LOCK_TIMEOUT 30000
	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN
	
	IF	@varKSparCODE IS NULL OR LEN(@varKSparCODE) = 0 OR 
		@varKSparNAME IS NULL OR LEN(@varKSparNAME) = 0 OR
		@varKSparPRIK_TYP_N IS NULL OR LEN(@varKSparPRIK_TYP_N) = 0 OR
		@varKSparPRIK_TYP IS NULL OR LEN(@varKSparPRIK_TYP) = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END	

	IF EXISTS (	SELECT LINK 
				FROM dbo.KO_PUNKT_POSTANOV 
				WHERE LINK <> @varKSparLINK AND (CODE = @varKSparCODE OR [NAME] = @varKSparNAME) ) BEGIN
		ROLLBACK
		RETURN 8
	END

	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN

		INSERT INTO dbo.PUNKT_POSTANOV WITH (ROWLOCK) (CODE, [NAME],PRIK_TYP) 
		VALUES (@varKSparCODE, @varKSparNAME,@varKSparPRIK_TYP)
		SELECT @varKSERROR = @@ERROR, @varKSparLINK=@@identity
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE BEGIN
		UPDATE dbo.PUNKT_POSTANOV WITH (ROWLOCK) 
		SET CODE = @varKSparCODE, [NAME]=@varKSparNAME , PRIK_TYP = @varKSparPRIK_TYP
		WHERE LINK=@varKSparLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

	
	SET @varKSEventText = 'Пункт статьи' + ' ' +  RTRIM(CONVERT(VARCHAR(50),@varKSparCODE))+' '+ RTRIM(CONVERT(VARCHAR(7000), @varKSparNAME))
	SET @varKSObject = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV')
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObject, 'KO_PUNKT_POSTANOV', @varKSparLINK

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0


GO


GRANT EXECUTE ON dbo.[KO_PUNKT_POSTANOV_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].[RN_GET_ATR_FOR_SVOD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_GET_ATR_FOR_SVOD]
GO
/*

  © Кейсистемс (Keysystems), 2006
  Возвращает список атрибутов
  
*/

CREATE       PROCEDURE dbo.RN_GET_ATR_FOR_SVOD
    @LF int , -- линк формы
    @begindate  datetime,
    @period_type int,
    @period_number int,
    @LinkTree int,
    @tmp_table varchar(250)='',
    @table_tree varchar(250) = '' -- для режима свод из первичных документов, свод по выбранным бюджетам
AS

declare @atr varchar(1000),@year int,@formcode varchar(30),@cstr varchar(4000),@begin_date datetime, @ExecStr varchar(1000)
--если у формы нет атрибутов, то выход
--select @atr=isnull(dbo.rn_get_atr_val(null,@LF,0),'')
select @atr=isnull(atributs,'') from report_forms where link_form=@lf

IF @atr=''
    begin
    IF @tmp_table=''
        select '' as atr,'' as atr_rus from report_atribut_values where 1=0 
    return 
    end

-- найдем все формы
    create table #LSF_DOWN (Link_saved_form int)
    set @year=YEAR(@begindate)
    select @formcode=code, @begin_date = START_DATE from report_forms where link_form=@LF
    IF (@formcode in ('(72н)0503125','(72н)0503125М','(72н)425M','(72н)425','(72н)0503117M','OPKB','OPKB_2008','0503117G','0503125G','425G','OPKB_MINREGION','425M','0503125M','0503117M','INVZ_2009','63', 'RRO','OPKB_2009_MR','Monit_napr_dohod(3)','Inf_opl_truda(1)','Inf_isp_dotaciy(2)','OPKB_2010_MR', '0503177G', '0503164G', '0503164M', '0503114M', '0503114G', '0503137M', '0503137G', '0503182M', '0503182G', '0503127M', '0503127G', '0503128G', '0503134G', '0503134M', '0503177M', '0503406', 'zarplata', 'PF', 'PR-1', 'Ostatki', 'РП-1', 'KS-1', 'ТСП-10', '0503138M', '0503138G','0503125G_R','425G_R', 'D003KS_1n', 'kurgan_ks', 'O00061', 'O0011', 'O0010', 'O0051', '0503666_1', '0503128M', 'PO_BA', 'adm_pravonar', 'kurgan_MD', 'Sovm_GIBDD', 'T0503324MF', 'T0503324MO', 'T0503324MI','KK04_PlanFHD_3', '0503125G_R', '425G_R', '(002)430109', 'KK04_PlanFHD_7_1', '0503163G', 'rk_3_2_4', 'rk_3_2_3', '457_pr3','kurgan_ks2', '298', 'rk_3_2_1', 'KK04_PlanFHD_10') or @formcode like 'Monitoring%'
         OR LEFT(@formcode,7) IN ('0503737', '0503738', '0503779', '0503725', '0503737', '0503737', '0503769', '0503125')
         OR @formcode IN ('kurgan_s11')
         OR @atr LIKE '%REPORTS_ATR_TYPE_ORG%'    
         OR @atr LIKE '%REPORTS_ATR_RZPR%'
         OR @atr LIKE '%REPORTS_ATR_VR%'
         OR @atr LIKE '%REPORTS_ATR_VID_BUDGET%')
      if isnull(@table_tree, '') = ''
        INSERT #LSF_DOWN exec RN_GET_SVOD_FORMS null,@linkTree,@YEAR,@period_type,@period_number,@formcode,default,default,default,1
      else begin
         create table #tree_for_atr (link int)
         set @ExecStr = 'insert #tree_for_atr select link from ' + @table_tree + ' #tree_for_atr insert #tree_for_atr select link from dbo.ro_svod_tree where childrens = 1 and link_self in (select link from #tree_for_atr)'
          exec (@ExecStr)
         INSERT #LSF_DOWN exec RN_GET_SVOD_FORMS null,@linkTree,@YEAR,@period_type,@period_number,@formcode,default,default,'#tree_for_atr',1
         exec dbo.DropTempTable '#tree_for_atr'
      end

    IF @tmp_table=''
      IF @atr LIKE '%REPORTS_ATR_VID_BUDGET%'
      BEGIN
         select distinct REPLACE(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1), 'REPORTS_ATR_VID_BUDGET='+dbo.[RN_GET_ATR_VALUE](link_saved_form,'REPORTS_ATR_VID_BUDGET'),'Свести все в Вид бюджета=00') as atr,
               REPLACE(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0),'Вид бюджета='+dbo.[RN_GET_ATR_VALUE](link_saved_form,'REPORTS_ATR_VID_BUDGET'),'Свести все в Вид бюджета=00')  atr_rus from #LSF_DOWN
	      union 
            select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
         
      END
      ELSE 
      IF @formcode = 'spravka_fin'
      BEGIN
         SELECT 'YA_ATR_MR_GO_CODE=' + RTRIM(CODE) + ',YA_ATR_MR_GO_NAME=' + RTRIM(NAME) AS atr, 'МР/ГО Код=' + RTRIM(CODE) + ',МР/ГО=' + RTRIM(NAME) AS atr_rus from R_SPR_YA_MR
      END
      ELSE 
		   IF @formcode in ('(72н)0503117M','0503117G','0503117M', '0503177G','0503164G', '0503164M', '0503114M', '0503114G', '0503137M', '0503137G', '0503182M', '0503182G', '0503127M', '0503127G', '0503128G', '0503134G', '0503134M', '0503177M', '0503138M', '0503138G', 'D003KS_1n', '0503128M', 'PO_BA', '0503163G', 'rk_3_2_4', 'rk_3_2_3')
			   IF EXISTS(SELECT * FROM #LSF_DOWN)
			      select ' Свести все в одну с АДМ=000' atr,' Свести все в одну с АДМ=000' atr_rus 
			      union 
	            select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
            ELSE
               BEGIN
                  -- Вытащим все ADM
                  select distinct '#REPORTS_ATR_ADM='+RTRIM(d.[VED]) AS atr ,'АДМ='+RTRIM(d.[VED]) atr_rus 
                  FROM dbo.[REPORT_SVOD_TREE] rst JOIN dbo.[DICTIONARY_DEPARTMENT] d ON rst.[LINK_REPORT_ORG] = d.link
                  WHERE rst.link_self = @LinkTree AND d.ved <> ''
                  UNION  
                  select distinct '#REPORTS_ATR_ADM='+RTRIM(d.[VED]) AS atr ,'АДМ='+RTRIM(d.[VED]) atr_rus 
                  FROM dbo.[REPORT_SVOD_TREE] rst JOIN dbo.[DICTIONARY_DEPARTMENT] d ON rst.[LINK_REPORT_ORG] = d.link
                  WHERE rst.link_self IN (SELECT rst1.link FROM dbo.[REPORT_SVOD_TREE] rst1 WHERE rst1.link_self = @LinkTree) AND d.ved <> ''
                  UNION
                  select distinct '#REPORTS_ATR_ADM=000' AS atr ,'АДМ=000' atr_rus
                  --rn_view_kbk_adm_m_atr
               END	         
		   else
			   IF @formcode in ('0503125M', '425M', '0503125G', '425G','0503125G_R','425G_R', '0503125m_AD') and not exists(select top 1 * from #LSF_DOWN)
			   BEGIN
			      IF YEAR(@begin_date) <> 2011
				      select 'REPORTS_ATR_ACC=' + rtrim(code) + ',REPORTS_ATR_PRP=500' as atr, 'Код СБУ=' + RTRIM(code) + ',ПРП=500' as atr_rus from RT_VIEW_KSBU_125
               ELSE
                  select 'REPORTS_ATR_ACC_2011=' + rtrim(code) + ',REPORTS_ATR_PRP=500' as atr, 'Код СБУ=' + RTRIM(code) + ',ПРП=500' as atr_rus from R_SPR_KSBU_125
			   end
			   ELSE
			      IF @formcode in ('0503725M') and not exists(select top 1 * from #LSF_DOWN)
			      BEGIN
                  select 'REPORTS_ATR_TYPE_ORG=' + RTRIM(T.code) + ',REPORTS_ATR_ACC_725=' + rtrim(S.code) + ',REPORTS_ATR_PRP=500' as atr, 'Тип=' + RTRIM(T.code) + ',Код СБУ=' + RTRIM(S.code) + ',ПРП=500' as atr_rus from R_SPR_KSBU_125 S, R_SPR_ATR_TYPE_ORG T
			      end
			      ELSE
                  IF left(@formcode, 7) IN ('0503737','0503738', '0503779')
                  BEGIN
                     IF NOT EXISTS(SELECT * FROM #LSF_DOWN)  
                        SELECT 'REPORTS_ATR_TYPE_ORG=' + RTRIM(T.code) + ',REPORTS_ATR_VID=' + rtrim(V.code) + ',REPORTS_ATR_VID_NAME=' + RTRIM(V.NAME) as atr, 'Тип=' + RTRIM(T.code) + ',ВидФинОб=' + RTRIM(V.code) + ',Наим=' + RTRIM(V.NAME) as atr_rus FROM R_SPR_ATR_VID V, R_SPR_ATR_TYPE_ORG T
                     ELSE
                        IF @atr LIKE '%REPORTS_ATR_TYPE_ORG%' 
                        BEGIN
                           IF CHARINDEX(',', @atr) = 0
                              select 'Свести все в одну с Тип=Сводный' as atr,'Свести все в одну с Тип=Сводный' atr_rus
                              UNION 
                              select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                              WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE '%Сводный%'
                           ELSE 
                              select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                              WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE '%Сводный%'
                              UNION 
                              select distinct 'Свести все в одну с Тип=Сводный' + SUBSTRING(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1), CHARINDEX(',', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1)), 254) as atr, 'Свести все в одну с Тип=Сводный' + substring(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0), CHARINDEX(',', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0)), 254) atr_rus from #LSF_DOWN
                        END 
                        ELSE  
                           select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                  END
                  ELSE BEGIN
                        IF @atr LIKE '%REPORTS_ATR_TYPE_ORG%' AND @formcode NOT IN ('573','576') 
                        BEGIN
                           IF CHARINDEX(',', @atr) = 0
                              select TOP 1 'Свести все в одну с Тип=Сводный' as atr,'Свести все в одну с Тип=Сводный' atr_rus
                              FROM #LSF_DOWN
                              UNION 
                              select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                              WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE '%Сводный%'
                              UNION 
                              SELECT 'REPORTS_ATR_TYPE_ORG=' + RTRIM(Code) , 'Тип=' + RTRIM(Code) FROM R_SPR_ATR_TYPE_ORG WHERE NOT EXISTS(SELECT * FROM #LSF_DOWN)
                           ELSE 
                              select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                              WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE '%Сводный%'
                              UNION 
                              select distinct 'Свести все в одну с Тип=Сводный' + SUBSTRING(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1), CHARINDEX(',', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1)), 254) as atr, 'Свести все в одну с Тип=Сводный' + substring(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0), CHARINDEX(',', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0)), 254) atr_rus from #LSF_DOWN
                        END 
                        ELSE
                           begin                        	                   
                            select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                           end
                  END       
    else
        BEGIN
       	
        	
      IF @formcode = 'spravka_fin'
      BEGIN
         set @cstr='insert '+@tmp_table+'
            SELECT ''YA_ATR_MR_GO_CODE='' + RTRIM(CODE) + '',YA_ATR_MR_GO_NAME='' + RTRIM(NAME) AS atr, ''МР/ГО Код='' + RTRIM(CODE) + '',МР/ГО='' + RTRIM(NAME) AS atr_rus from R_SPR_YA_MR'
         EXEC (@cstr)            
      END
      ELSE 
			IF @formcode in ('(72н)0503117M','0503117G','0503117M', '0503177G','0503164G', '0503164M', '0503114M', '0503114G', '0503137M', '0503137G', '0503182M', '0503182G', '0503127M', '0503127G', '0503128G', '0503134G', '0503134M', '0503177M', '0503138M', '0503138G', 'D003KS_1n', '0503128M', 'PO_BA', '0503163G', 'rk_3_2_4', 'rk_3_2_3')
				begin
					set @cstr='insert '+@tmp_table+'
					select '' Свести все в одну с АДМ=000'' atr,'' Свести все в одну с АДМ=000'' atr_rus
			      union 
	            select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN'
					exec(@cstr)    
				END
          else  
			IF @formcode in ('0503125M', '425M', '0503125G', '425G','0503125G_R','425G_R', '0503125m_AD') and not exists(select top 1 * from #LSF_DOWN)
			begin
			   IF YEAR(@begin_date) <> 2011
				   set @cstr='insert '+@tmp_table+'
				   select ''REPORTS_ATR_ACC='' + rtrim(code) + '',REPORTS_ATR_PRP=500'' as atr, ''Код СБУ='' + RTRIM(code) + '',ПРП=500'' as atr_rus from RT_VIEW_KSBU_125'
            ELSE
   				set @cstr='insert '+@tmp_table+'
				   select ''REPORTS_ATR_ACC_2011='' + rtrim(code) + '',REPORTS_ATR_PRP=500'' as atr, ''Код СБУ='' + RTRIM(code) + '',ПРП=500'' as atr_rus from R_SPR_KSBU_125'
				   exec(@cstr)    
			end
			else begin
			   IF @formcode in ('0503725M') and not exists(select top 1 * from #LSF_DOWN)
			   BEGIN
               set @cstr='insert '+@tmp_table+'
               select ''REPORTS_ATR_TYPE_ORG='' + RTRIM(T.code) + '',REPORTS_ATR_ACC_725='' + rtrim(S.code) + '',REPORTS_ATR_PRP=500'' as atr, ''Тип='' + RTRIM(T.code) + '',Код СБУ='' + RTRIM(S.code) + '',ПРП=500'' as atr_rus from R_SPR_KSBU_125 S, R_SPR_ATR_TYPE_ORG T'
               exec(@cstr)
			   end
			   ELSE
               IF left(@formcode, 7) IN ('0503737','0503738', '0503779')
               BEGIN
                  IF NOT EXISTS(SELECT * FROM #LSF_DOWN)
                     set @cstr='insert '+@tmp_table+'                    
                     SELECT ''REPORTS_ATR_TYPE_ORG='' + RTRIM(T.code) + '',REPORTS_ATR_VID='' + rtrim(V.code) + '',REPORTS_ATR_VID_NAME='' + RTRIM(V.NAME) as atr, ''Тип='' + RTRIM(T.code) + '',ВидФинОб='' + RTRIM(V.code) + '',Наим='' + RTRIM(V.NAME) as atr_rus FROM R_SPR_ATR_VID V, R_SPR_ATR_TYPE_ORG T'
                  ELSE
                     IF @atr LIKE '%REPORTS_ATR_TYPE_ORG%' 
                     BEGIN
                        IF CHARINDEX(',', @atr) = 0
                           set @cstr='insert '+@tmp_table+'
                           select ''Свести все в одну с Тип=Сводный'' as atr,''Свести все в одну с Тип=Сводный'' atr_rus
                           UNION 
                           select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                           WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE ''%Сводный%'''
                        ELSE 
                           set @cstr='insert '+@tmp_table+'
                           select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN
                           WHERE dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) NOT LIKE ''%Сводный%''
                           UNION 
                           select distinct ''Свести все в одну с Тип=Сводный'' + SUBSTRING(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1), CHARINDEX('','', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1)), 254) as atr, ''Свести все в одну с Тип=Сводный,'' + substring(dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0), CHARINDEX('','', dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0)), 254) atr_rus from #LSF_DOWN'
                     END 
                     ELSE  
                        set @cstr='insert '+@tmp_table+'
                        select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN'
                      exec(@cstr)    
               END
               ELSE BEGIN
                     set @cstr='insert '+@tmp_table+'
                     select distinct dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,1) as atr,dbo.RN_GET_ATR_SVOD_VAL(link_saved_form,null,0) atr_rus from #LSF_DOWN'
                     exec(@cstr) 
               END       
			end
        end
GO
GRANT ALL ON dbo.[RN_GET_ATR_FOR_SVOD] 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].[BM_CARD_LBO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BM_CARD_LBO]
GO




CREATE     PROCEDURE dbo.BM_CARD_LBO
		@dDate1		datetime,
		@intVid		int,
		@intLinkAccDep	varchar(5),
		@intAccShortCode int
AS 

declare	@dDateBM	datetime,
		@dDateBY	datetime,
		@strOrgOur	varchar(254),
		@intPRN_KBK	INT,
		@intPRN_SGU	INT,
		@strOrgCode	varchar(254)
		
declare  @varKStRestSum table  (account 	int,
				kbk	int,
				sgu	int,
				summa	numeric(18,2))		

declare @varKStOborotSum table (account 	int,
				kbk	int,
				sgu	int,
				summa	numeric(18,2))		

set 		@dDateBY		= dbo.DateBeginOfYear(@dDate1)
set 		@dDateBM		= dbo.DateBeginOfMonth(@dDate1)
select	@strOrgOur = rtrim(t.[name]), @strOrgCode = rtrim(t.[code])
from 	treasury t inner join
	departments d on d.tofk_link = t.link
			 and t.link = dbo.GetOwnDepLink()
--select * from buffer
exec BufferClear 'ACCOUNT_FOR_LBO'

IF ISNULL (@intAccShortCode, 0) = 0
BEGIN
	SET	@intPRN_KBK	=	0
	SET	@intPRN_SGU	=	0
END
ELSE
BEGIN
	SET	@intPRN_KBK	=	1
	SET	@intPRN_SGU	=	1
END

insert into buffer (link, [id])
select link,'ACCOUNT_FOR_LBO'
from s_accounts 
where @intVid = 1 and CODE = '1.501.15' or
	@intVid = 2 and CODE = '1.501.14' or
	@intVid = 3 and CODE = '1.503.15'or
	@intVid = 4 and CODE = '1.503.14'

if ISNULL (@intAccShortCode, 0) = 0
begin
	insert into @varKStRestSum
	select	[account]	= account,
		[kbk]		= null,
		[sgu]		= null,
		[summa]		= case	when @intVid = 1 or @intVid = 3 then sum(summa)
					when @intVid = 2 or @intVid = 4 then sum(-summa) end
	FROM (select ACCOUNT = DT_ACCOUNT, DEP_ACC = KT_DEP_ACC, summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBY,@dDate1, 'ACCOUNT_FOR_LBO', null) union all
			select KT_ACCOUNT, DT_DEP_ACC, -summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBY,@dDate1, null, 'ACCOUNT_FOR_LBO')) S
	where S.DEP_ACC = @intLinkAccDep and 
			S.DEP_LINK = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	group by account
	
	insert into @varKStOborotSum
	select	[account]	= account,
		[kbk]		= null,
		[sgu]		= null,
		[summa]		= case	when @intVid = 1 or @intVid = 3 then sum(summa)
					when @intVid = 2 or @intVid = 4 then sum(-summa) end
	FROM (select ACCOUNT = DT_ACCOUNT, DEP_ACC = KT_DEP_ACC, summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBM,@dDate1, 'ACCOUNT_FOR_LBO', null) union all
			select KT_ACCOUNT, DT_DEP_ACC,  -summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBM,@dDate1, null, 'ACCOUNT_FOR_LBO')) S
	where S.DEP_ACC = @intLinkAccDep and 
			S.DEP_LINK = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	group by account
end
else
begin
	insert into @varKStRestSum
	select	[account]	= account,
		[kbk]		= kbk,
		[sgu]		= sgu,
		[summa]		= case	when @intVid = 1 or @intVid = 3 then sum(summa)
					when @intVid = 2 or @intVid = 4 then sum(-summa) end
	FROM (select ACCOUNT = DT_ACCOUNT, DEP_ACC = KT_DEP_ACC, KBK = DT_VKR, SGU = DT_SGU,  summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBY,@dDate1, 'ACCOUNT_FOR_LBO', null) union all
			select KT_ACCOUNT, DT_DEP_ACC, KT_VKR, KT_SGU,  -summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBY,@dDate1, null, 'ACCOUNT_FOR_LBO')) S
	where S.DEP_ACC = @intLinkAccDep and 
			S.DEP_LINK = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	group by account, kbk, /*ekr, */sgu
	
	insert into @varKStOborotSum
	select	[account]	= account,
		[kbk]		= kbk,
		[sgu]		= sgu,
		[summa]		= case	when @intVid = 1 or @intVid = 3 then sum(summa)
					when @intVid = 2 or @intVid = 4 then sum(-summa) end
	FROM (select ACCOUNT = DT_ACCOUNT, DEP_ACC = KT_DEP_ACC, KBK = DT_VKR, SGU = DT_SGU,  summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBM,@dDate1, 'ACCOUNT_FOR_LBO', null) union all 
			select KT_ACCOUNT, DT_DEP_ACC, KT_VKR, KT_SGU,  -summa, DEP_LINK from dbo.AProvByBufferConditionsShort(@dDateBM,@dDate1, null, 'ACCOUNT_FOR_LBO')) S
	where S.DEP_ACC = @intLinkAccDep and 
			S.DEP_LINK = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	group by account, kbk, /*ekr, */sgu
end

select 	[acct2]	=	dbo.BK_GetAcctFullCode1 (rs.ACCOUNT, rs.KBK, rs.SGU, @intPRN_KBK, @intPRN_SGU),
	[sum1]	= 	rs.summa,
	[sum2]	= 	os.summa,
	[org_name]=	@strOrgOur,
	[org_code]=	@strOrgCode
from	@varKStRestSum rs	
left join @varKStOborotSum os	on	rs.account = os.account
					and	(rs.kbk = os.kbk or (rs.kbk is null and os.kbk is null))
					and	(rs.sgu = os.sgu or (rs.sgu is null and os.sgu is null))
	
				


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_372]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_372]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_372]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] <= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=01')
      ORDER BY [ORDER]
      
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] > (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=02')
            AND [ORDER] <= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = '#&')
            AND TXT <> 'ТБ=03'
      ORDER BY [ORDER]
      
      
      INSERT @tabImport (TXT)
      VALUES('ТБ=02')
      
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] > (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=01')
            AND [ORDER] < (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=02')
      ORDER BY [ORDER]
      

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|****|*******|***|*|*****|***|***|', '999|9999|9999999|999|9|99999|999|999|')
      WHERE TXT LIKE '***|****|*******|***|*|*****|***|***|%' 

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|****|****|**|****|*|*****|***|***|', '777|7777|7777|77|7777|7|77777|777|777|')
      WHERE TXT LIKE '***|****|****|**|****|*|*****|***|***|%' 

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|**************|*|*****|***|***|', '888|8888|8888|88|8888|8|88888|888|888|')
      WHERE TXT LIKE '***|**************|*|*****|***|***|%' 

      UPDATE @tabImport
      SET TXT = '000|0000|0000|00|0000|0|00011|000|' + SUBSTRING(TXT, 4, 8000)
      WHERE TXT LIKE '11|%'  

      UPDATE @tabImport
      SET TXT = '000|0000|0000|00|0000|0|00011|000|000|' + SUBSTRING(TXT, 8, 8000)
      WHERE TXT LIKE '**|***|%'  
      
      UPDATE @tabImport
      SET TXT = REPLACE(REPLACE(REPLACE(TXT, '***|****|*******|***|', '000|0000|0000000|000|'), '***|****|****|**|****|', '000|0000|0000|00|0000|'), '|***|', '|000|')

      DELETE #IMPORT_TABLE
      
      INSERT #IMPORT_TABLE (TXT)
      SELECT [TXT]
      FROM @tabImport
      ORDER BY [ORDER]
--SELECT * FROM #import_table
 
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_372] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select @@datalength
sp_help RA_IMPORT_FORM_ANALYZE_XML
*/	
--SELECT * FROM report_kbk WHERE code_form = 'SPR_86n_OGS' and code ='0115300000254'
--DELETE   report_kbk WHERE code_form = 'SPR_86n_OGS_OKVED'
--SELECT  dbo.rn_get_ogs_code('15001035','',0)
--SELECT SUM(aaa) FROM 
--(
--   SELECT code_str,add_info,COUNT(*) aaa FROM REPORT_KBK B WHERE B.CODE_FORM = 'SPR_86n_OGS' 
--   --AND add_info='15'
--   AND B.LONG_NAME NOT LIKE '%филиал%'
--   GROUP BY code_str,add_info HAVING COUNT(*)>1
--) A
--SELECT * FROM REPORT_KBK B WHERE B.CODE_FORM = 'SPR_86n_OGS'
--AND code_str='0326024141'


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_57X]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_57X]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2009

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_57X]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

SET NOCOUNT ON

DECLARE @vcFormCode VARCHAR(10),
        @vcFileName VARCHAR(50),
        @vcFileNameArh VARCHAR(50),
        @vcKBP      VARCHAR(100),
        @vcVB       VARCHAR(100),
        @i          INT,
        @vcVersion	VARCHAR(50), 
        @vcAtr       VARCHAR(254)

DECLARE @tabRD TABLE ([ORDER] INT IDENTITY(1,1),
                      [TXT]   VARCHAR(8000))

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE
							          
IF @iMODE = 2
BEGIN
   UPDATE #FileExportReport
   SET [TXT] = 'ПРД=4'   
   WHERE [TXT] = 'ПРД=3'

   SELECT @vcKBP = ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS]
   WHERE [RAZDEL] = '57X' AND
         [CODE] = 'IST_ZATO'

   SET @vcKBP = ISNULL(@vcKBP,'')

   SELECT @vcVB = [VAL_STR]
   FROM dbo.[REPORT_OPTIONS]
   WHERE [RAZDEL] = '57X' AND
         [CODE] = 'VB_ZATO'

   SET @vcVB = ISNULL(@vcVB,'')

	SELECT @vcVersion = [VERSION] FROM #tabExportOutput
      
   SELECT @vcFormCode = [B].[EXPORTCODE],
          @vcFileName = RTRIM([B].[EXPORTCODE]) + 
                        RIGHT('0'+LTRIM(STR(MONTH([A].[BEGIN_DATE]+1))),2)+ 
                        'Q' + RTRIM(@vcVersion) + '.TXT',
         @vcFileNameArh = '5' + RIGHT('000' + ISNULL(RTRIM(LTRIM((SELECT IST_ZATO FROM dbo.RA_VIEW_OPTIONS_57X))),''),3) +
						RIGHT('0'+LTRIM(STR(MONTH([A].[BEGIN_DATE]+1))),2)+ RTRIM(@vcVersion) + '.arj'
   FROM dbo.[REPORT_SAVED_FORMS] [A]
   JOIN dbo.[REPORT_FORMS]       [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
   WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM
   
   IF @vcFormCode = '566'
   BEGIN      
      UPDATE [A]
      SET [TXT] = ISNULL(RTRIM([C].[CODE_SUBJ])+'|'+RTRIM([C].[CODE]),'00|00')+'|'+[TXT]
      FROM #FileExportReport              [A]
      LEFT JOIN dbo.[REPORT_ZATO_OBJECTS] [B] ON dbo.[RA_GETWORDNUM]([A].[TXT],2,'|') = [B].[CODE_OBJECT]
      LEFT JOIN dbo.[RA_VIEW_ZATO]        [C] ON [B].[CODE] = [C].[CODE]
      WHERE [TXT] LIKE '%|%'
   END

   IF @vcFormCode = '571'
   BEGIN
      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE [ORDERS] <= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = 'ТБ=01')
      ORDER BY [ORDERS]

      INSERT @tabRD([TXT]) VALUES('#$')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE ([TXT] LIKE '%|%') AND (LEFT([TXT],2) = '01')
      ORDER BY [ORDERS]

      INSERT @tabRD([TXT]) VALUES ('#')
      INSERT @tabRD([TXT]) VALUES ('#@')
      INSERT @tabRD([TXT]) VALUES ('ТБ=02')
      INSERT @tabRD([TXT]) VALUES ('#$')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE ([TXT] LIKE '%|%') AND (LEFT([TXT],2) = '02')
      ORDER BY [ORDERS]

      INSERT @tabRD([TXT]) VALUES ('#')
      INSERT @tabRD([TXT]) VALUES ('#@')
      INSERT @tabRD([TXT]) VALUES ('ТБ=03')
      INSERT @tabRD([TXT]) VALUES ('#$')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE ([TXT] LIKE '%|%') AND (LEFT([TXT],2) = '03')
      ORDER BY [ORDERS]
      
      INSERT @tabRD([TXT]) VALUES ('#')
      INSERT @tabRD([TXT]) VALUES ('#@')
      INSERT @tabRD([TXT]) VALUES ('ТБ=04')
      INSERT @tabRD([TXT]) VALUES ('#$')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE ([TXT] LIKE '%|%') AND (LEFT([TXT],2) = '04')
      ORDER BY [ORDERS]
   
      INSERT @tabRD([TXT]) VALUES ('#')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE [ORDERS] >= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = '#&')
      ORDER BY [ORDERS]
         
      DELETE #FileExportReport
      
      INSERT #FileExportReport([TXT],[ORDERS],[NAMEFILE])
      SELECT [TXT],[ORDER],@vcFileName
      FROM @tabRD
      ORDER BY [ORDER]
   END

   IF @vcFormCode IN ('573', '576')
   BEGIN
      SET @vcAtr = dbo.RN_GET_ATR_VALUE(@iLINK_SAVED_FORM, 'REPORTS_ATR_TYPE_ORG_ZATO')
      
      IF @vcAtr LIKE 'Бюдж%'
      BEGIN
         SET @vcFileName = LEFT(@vcFileName, 3) + 'B' + SUBSTRING(@vcFileName, 4, 50)
         
         UPDATE #FileExportReport
         SET [TXT] = 'КОДФ=573B'
         WHERE [TXT] = 'КОДФ=573'

         UPDATE #FileExportReport
         SET [TXT] = 'КОДФ=576B'
         WHERE [TXT] = 'КОДФ=576'
      END 
   END
   
   IF @vcFormCode = '574'
   BEGIN
   
      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE [ORDERS] <= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = 'ТБ=01')
      ORDER BY [ORDERS]

      INSERT @tabRD([TXT]) VALUES('#$')

      INSERT @tabRD([TXT])
      SELECT COALESCE(LEFT(F1.TXT,CHARINDEX('|',F1.TXT)),LEFT(F2.TXT,CHARINDEX('|',F2.TXT)),LEFT(F3.TXT,CHARINDEX('|',F3.TXT))) -- код
				+ ISNULL(SUBSTRING(F1.[TXT], CHARINDEX('|',F1.[TXT]) + 1, LEN(F1.[TXT])),'0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|')
				+ ISNULL(SUBSTRING(F2.[TXT], CHARINDEX('|',F2.[TXT]) + 1, LEN(F2.[TXT])),'0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|')
				+ ISNULL(SUBSTRING(F3.[TXT], CHARINDEX('|',F3.[TXT]) + 1, LEN(F3.[TXT])) ,'0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|0.00|')
      FROM (SELECT * FROM #FileExportReport WHERE [TXT] LIKE '%|%' AND 
					orders > (SELECT orders FROM #FileExportReport WHERE txt = 'ТБ=01')
					AND orders < (SELECT orders FROM #FileExportReport WHERE txt = 'ТБ=02')) F1
			FULL JOIN (SELECT * FROM #FileExportReport WHERE [TXT] LIKE '%|%' AND 
					orders > (SELECT orders FROM #FileExportReport WHERE txt = 'ТБ=02')
					AND orders < (SELECT orders FROM #FileExportReport WHERE txt = 'ТБ=03')) F2
			ON LEFT(F1.TXT,CHARINDEX('|',F1.TXT)) = LEFT(F2.TXT,CHARINDEX('|',F2.TXT))
			FULL JOIN (SELECT * FROM #FileExportReport WHERE [TXT] LIKE '%|%' AND 
					orders > (SELECT orders FROM #FileExportReport WHERE txt = 'ТБ=03')
					AND orders < (SELECT orders FROM #FileExportReport WHERE txt = '#&')) F3
			ON ISNULL(LEFT(F1.TXT,CHARINDEX('|',F1.TXT)),LEFT(F2.TXT,CHARINDEX('|',F2.TXT))) = LEFT(F3.TXT,CHARINDEX('|',F3.TXT))
      ORDER BY COALESCE(LEFT(F1.TXT,CHARINDEX('|',F1.TXT)),LEFT(F2.TXT,CHARINDEX('|',F2.TXT)),LEFT(F3.TXT,CHARINDEX('|',F3.TXT)))

      INSERT @tabRD([TXT]) VALUES ('#')

      INSERT @tabRD([TXT])
      SELECT [TXT]
      FROM #FileExportReport
      WHERE [ORDERS] >= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = '#&')
      ORDER BY [ORDERS]
      
	  DELETE #FileExportReport
      
      INSERT #FileExportReport([TXT],[ORDERS],[NAMEFILE])
      SELECT [TXT],[ORDER],@vcFileName
      FROM @tabRD
      ORDER BY [ORDER]
      
   END

   UPDATE #FileExportReport
   SET [NAMEFILE] = @vcFileName,
		[NAMEFILEARH] =  @vcFileNameArh,
		[TXT] = REPLACE([TXT], '|0.00','|0')

	if isnull(@vcKBP,'') <> '' OR isnull(@vcVB,'') <> ''
	begin
	   UPDATE #FileExportReport
	   SET [TXT] = 'ИСТ=' + LTRIM(@vcKBP)
	   WHERE LEN(@vcKBP)>0 AND
			 LEFT([TXT],4)='ИСТ='

	   UPDATE #FileExportReport
	   SET [TXT] = 'ВИД=' + LTRIM(@vcVB)
	   WHERE LEN(@vcVB)>0 AND
			 LEFT([TXT],4)='ВИД='
	END
   
   UPDATE #FileExportReport
   SET [TXT] = REPLACE([TXT], '.00|', '|')
   WHERE [TXT] LIKE '%|%|%'
END                         



GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_57X] 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.[BK_REPORT_AKT_RESIVE_DEP1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_AKT_RESIVE_DEP1]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.BK_REPORT_AKT_RESIVE_DEP1
	@varKSdDate1	DATETIME,
	@varKSdDate2	DATETIME,
	@varKScVal1 char(1), @varKSnOtborLink1 int,
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@cVal_EKR char(1), @nOtborLinkEKR int,	-- Отбор ЭКР --
	@intParamDep	INT,
	@intRepByEKR	INT,
	@intRepByKBK	INT,
	@intSVOD_ZB	int,	-- Сводный отчет (ЦБ) --
	@strACCT_SINTH	VARCHAR (100) = '206, 302',
	@intNO_ZACHET	TINYINT = 0
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORG_Code	VARCHAR(20),
		@varKSORGNAME	VARCHAR(254),
		@strDATE_BEGIN	VARCHAR (10),
		@strDATE_END	VARCHAR (10),
		@strDATE_OUT	VARCHAR (10),
		@strGLBUH_NAME	VARCHAR (30),
		@intXO_ZACHET	INT,
		@dDATE_OUT_REST	DATETIME

	IF ISNULL (@intNO_ZACHET, 0) = 1
		SELECT @intXO_ZACHET = LINK
		FROM dbo.XD_XOZ_OPER
		WHERE FULLCODE = '14.03'
	ELSE
		SET @intXO_ZACHET = -1

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	-- Сводный отчет по ЦБ -- 
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()
--	SET @varKSDEP_LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL 	
		SET @varKSDEP_LINK = dbo.GetOwnDepLink ()

	SELECT  @varKSDEP_LINK = D.LINK,
		@varKSORG_Code = D.[CODE],
		@varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (D.LINK),
		@strGLBUH_NAME = ISNULL (OTV_B.[FACE_NAME], '')
	FROM dbo.DICTIONARY_DEPARTMENT D
	LEFT OUTER JOIN dbo.DICTIONARY_OTV_FACE OTV_B ON (OTV_B.DEP_LINK = D.LINK
		AND OTV_B.[NAME] = 'Главный бухгалтер')
	WHERE D.LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
	
	CREATE TABLE #TABLE_ACCT ([UPD] INT, [DEL] INT, [CHECKED] INT,
			[LINK] INT, [CODE] VARCHAR (30), [NAME] VARCHAR (254))
	
	IF LEN (@varKScVal1) > 0
		INSERT INTO #TABLE_ACCT (UPD, DEL, CHECKED, LINK, CODE, [NAME])
		SELECT 0, 0, 0, OVA.RECORD, SA.CODE, SA.[NAME]
		FROM dbo.OBJECT_VAR_ACCT OVA, dbo.S_ACCOUNTS SA
		WHERE OVA.LINK_UP = @varKSnOtborLink1
			AND SA.LINK = OVA.RECORD
	ELSE
		INSERT INTO #TABLE_ACCT
		EXEC dbo.BK_GET_OTBOR_ACCOUNTS1 @strACCT_SINTH, DEFAULT, DEFAULT

	DECLARE @DEP_TABLE TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254))

	IF ISNULL (@intParamDep, 0) = 0 -- организация в параметрах не указана
	BEGIN
		IF LEN(@varKScVal2)>0
		BEGIN
			INSERT INTO @DEP_TABLE
				SELECT OVR.RECORD, D.CODE, D.[NAME]
				FROM OBJECT_VAR_DEPARTMENT OVR, DICTIONARY_DEPARTMENT D
				WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
		END
		ELSE
		BEGIN
			INSERT INTO @DEP_TABLE
				SELECT D.LINK, D.CODE, D.[NAME] FROM DICTIONARY_DEPARTMENT D
			INSERT INTO @DEP_TABLE VALUES (0, '', '')
		END
	END
	ELSE
		INSERT INTO @DEP_TABLE
			SELECT D.LINK, D.CODE, D.[NAME]
			FROM dbo.DICTIONARY_DEPARTMENT D
			WHERE LINK = @intParamDep

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (20), KBK_NAME [VARCHAR] (254))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE,
			AP.NAME
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- Отбор ЭКР --- 
	DECLARE @TAB_EKR TABLE (LINK_EKR [INT], EKR_CODE  [VARCHAR] (20), EKR_NAME [VARCHAR] (254))
	IF LEN(@cVal_EKR)>0 BEGIN
		INSERT INTO @TAB_EKR
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_KOSGU OVR, dbo.KOSGU D
			WHERE D.LINK = OVR.RECORD AND OVR.LINK_UP = @nOtborLinkEKR
	END
	ELSE
	BEGIN
		INSERT INTO @TAB_EKR
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('EKR')
	END

-- select * from @TAB_EKR

	--- ДЕБЕТОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_DB TABLE (LINK_DOC INT, DEP INT, KBK INT, EKR INT, SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_DB
	SELECT T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		SUM (T1.SUMMA)
	FROM dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 0, DEFAULT, DEFAULT) T1
	INNER JOIN #TABLE_ACCT T2 ON (T2.LINK = T1.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	WHERE (@intSVOD_ZB = 1
			OR @intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
		AND ISNULL (T1.XOZ_OPER, 0) <> @intXO_ZACHET
	GROUP BY T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END

	--- КРЕДИТОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_KT TABLE (LINK_DOC INT, DEP INT, KBK INT, EKR INT, SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_KT
	SELECT T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		SUM (T1.SUMMA)
	FROM dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 1, DEFAULT, DEFAULT) T1
	INNER JOIN #TABLE_ACCT T2 ON (T2.LINK = T1.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	WHERE (@intSVOD_ZB = 1
			OR @intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
		AND ISNULL (T1.XOZ_OPER, 0) <> @intXO_ZACHET
	GROUP BY T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END

	--- ВХОДЯЩИЕ ОСТАТКИ ПО ЭКР --- 
	DECLARE @TAB_IN_REST TABLE (DEP INT, KBK INT, EKR INT, D_SUM_EKR NUMERIC (28,4), K_SUM_EKR NUMERIC (28,4))
	INSERT INTO @TAB_IN_REST 
	SELECT ISNULL (T_REST.DEP, 0) AS DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		SUM (T_REST.D_SUMMA),
		SUM (T_REST.K_SUMMA)
	FROM dbo.ARestTableByDate (@varKSdDate1, DEFAULT) T_REST
	INNER JOIN #TABLE_ACCT T_ACCT ON (T_ACCT.LINK = T_REST.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = ISNULL (T_REST.KBK, 0))
	WHERE (@intSVOD_ZB = 1
			AND T_REST.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR TYPE = 4))
		OR (@intSVOD_ZB = 0 AND T_REST.DEP_LINK = @varKSDEP_LINK)
	GROUP BY ISNULL (T_REST.DEP, 0),
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END

	--- ИСХОДЯЩИЕ ОСТАТКИ ПО ЭКР --- 
	SET @dDATE_OUT_REST = DATEADD (DAY, 1, @varKSdDate2)

	DECLARE @TAB_OUT_REST TABLE (DEP INT, KBK INT, EKR INT, D_SUM_EKR NUMERIC (28,4), K_SUM_EKR NUMERIC (28,4))

	INSERT INTO @TAB_OUT_REST 
	SELECT ISNULL (T_REST.DEP, 0) AS DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		SUM (T_REST.D_SUMMA),
		SUM (T_REST.K_SUMMA)
	FROM dbo.ARestTableByDate (@dDATE_OUT_REST, DEFAULT) T_REST
	INNER JOIN #TABLE_ACCT T_ACCT ON (T_ACCT.LINK = T_REST.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = ISNULL (T_REST.KBK, 0))
	WHERE (@intSVOD_ZB = 1
			AND T_REST.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR TYPE = 4))
		OR (@intSVOD_ZB = 0 AND T_REST.DEP_LINK = @varKSDEP_LINK)
	GROUP BY ISNULL (T_REST.DEP, 0),
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END
	--- ИТОГОВЫЕ ОСТАТКИ ПО КБК ---
	DECLARE @TAB_REST_KBK_IN TABLE (DEP INT, KBK INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_KBK_IN
	SELECT DEP, KBK,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_IN_REST
	GROUP BY DEP, KBK		

	DECLARE @TAB_REST_KBK_OUT TABLE (DEP INT, KBK INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_KBK_OUT
	SELECT DEP, KBK,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_OUT_REST
	GROUP BY DEP, KBK
	
	--- ИТОГОВЫЕ ОСТАТКИ ПО ОРГАНИЗАЦИЯМ ---
	DECLARE @TAB_REST_DEP_IN TABLE (DEP INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_DEP_IN
	SELECT DEP,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_IN_REST
	GROUP BY DEP		

	DECLARE @TAB_REST_DEP_OUT TABLE (DEP INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_DEP_OUT
	SELECT DEP,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_OUT_REST
	GROUP BY DEP

	--- ИТОГОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_OBOROT TABLE (LINK_DOC INT, DEP INT, KBK INT, EKR INT, DT_SUM NUMERIC (28,4), KT_SUM NUMERIC (28,4))

	INSERT INTO @TAB_OBOROT (LINK_DOC, DEP, KBK, EKR)
	SELECT LINK_DOC, DEP, KBK, EKR
	FROM @TAB_DB
	UNION 
	SELECT LINK_DOC, DEP, KBK, EKR
	FROM @TAB_KT

	UPDATE @TAB_OBOROT SET DT_SUM = COALESCE (DB.SUMMA, 0),
				KT_SUM = COALESCE (KT.SUMMA, 0)
	FROM @TAB_OBOROT T1
	LEFT OUTER JOIN @TAB_DB DB ON (DB.LINK_DOC = T1.LINK_DOC
		AND DB.DEP = T1.DEP
		AND DB.KBK = T1.KBK
		AND DB.EKR = T1.EKR)
	LEFT OUTER JOIN @TAB_KT KT ON (KT.LINK_DOC = T1.LINK_DOC
		AND KT.DEP = T1.DEP
		AND KT.KBK = T1.KBK
		AND KT.EKR = T1.EKR)

	--- СПИСОК ОРГАНИЗАЦИЙ, ПО КОТОРЫМ СОБИРАЕМ --- 
	DECLARE @TAB_ALL_REC TABLE (DEP INT, KBK INT, EKR INT)
	
	INSERT INTO @TAB_ALL_REC (DEP, KBK, EKR)
	SELECT DEP, KBK, EKR
	FROM @TAB_OBOROT
	UNION 
	SELECT DEP, KBK, EKR
	FROM @TAB_IN_REST
	WHERE D_SUM_EKR <> 0 OR K_SUM_EKR <> 0 
	UNION 
	SELECT DEP, KBK, EKR
	FROM @TAB_OUT_REST
	WHERE D_SUM_EKR <> 0 OR K_SUM_EKR <> 0 

-- SELECT * FROM @TAB_ALL_REC

	--- РЕЗУЛЬТАТЫ --- 
	DECLARE @TAB_RES TABLE (LINK_DOC INT, DEP INT, KBK INT, EKR INT,
		DOC_DATE VARCHAR (10), dDOC_DATE DATETIME, DOC_NUM VARCHAR (50),
		DOC_NAME VARCHAR (254),
		DATE_BEGIN VARCHAR (10), DATE_END VARCHAR (10),
		DATE_NEXT VARCHAR (10),
		DEP_CODE1 VARCHAR (10), DEP_NAME1 VARCHAR (254),
		DEP_CODE2 VARCHAR (10), DEP_NAME2 VARCHAR (254),
		EKR_CODE VARCHAR (10), EKR_NAME VARCHAR (254),
		KBK_CODE VARCHAR (20), KBK_NAME VARCHAR (254),
		GLBUH1 VARCHAR (30), GLBUH2 VARCHAR (30),
		DT_SUM NUMERIC (28,4), KT_SUM NUMERIC (28,4),
		DIN_SUM NUMERIC (28,4), KIN_SUM NUMERIC (28,4),
		DIN_SUM_K NUMERIC (28,4), KIN_SUM_K NUMERIC (28,4),
		DIN_SUM_E NUMERIC (28,4), KIN_SUM_E NUMERIC (28,4),
		DOUT_SUM NUMERIC (28,4), KOUT_SUM NUMERIC (28,4),
		DOUT_SUM_K NUMERIC (28,4), KOUT_SUM_K NUMERIC (28,4),
		DOUT_SUM_E NUMERIC (28,4), KOUT_SUM_E NUMERIC (28,4))

	SET @strDATE_BEGIN = CONVERT (VARCHAR (10), @varKSdDate1, 104)
	SET @strDATE_END = CONVERT (VARCHAR (10), @varKSdDate2, 104)
	SET @strDATE_OUT = CONVERT (VARCHAR (10), @dDATE_OUT_REST, 104)

	INSERT INTO @TAB_RES
	SELECT T1.LINK_DOC,
		ALL_REC.DEP,
		ALL_REC.KBK,
		ALL_REC.EKR,
		CONVERT (VARCHAR (10), G.DATE_PROV, 104),
		G.DATE_PROV,
		ISNULL (G.NUMBER, ''),
		ISNULL (dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT), ''),
		@strDATE_BEGIN,
		@strDATE_END,
		@strDATE_OUT,
		@varKSORG_Code, 
		@varKSORGNAME,
		D.DEP_CODE,
		D.DEP_NAME,
		E.EKR_CODE,
		E.EKR_NAME,
		K.KBK_CODE,
		K.KBK_NAME,
		@strGLBUH_NAME,
		ISNULL (OTV_B2.FACE_NAME, ''),
		ISNULL (T1.DT_SUM, 0),
		ISNULL (T1.KT_SUM, 0),
		ISNULL (TR_DEP_IN.D_SUMMA, 0),
		ISNULL (TR_DEP_IN.K_SUMMA, 0),
		ISNULL (TR_KBK_IN.D_SUMMA, 0),
		ISNULL (TR_KBK_IN.K_SUMMA, 0),
		ISNULL (TR_IN.D_SUM_EKR, 0),
		ISNULL (TR_IN.K_SUM_EKR, 0),
		ISNULL (TR_DEP_OUT.D_SUMMA, 0),
		ISNULL (TR_DEP_OUT.K_SUMMA, 0),
		ISNULL (TR_KBK_OUT.D_SUMMA, 0),
		ISNULL (TR_KBK_OUT.K_SUMMA, 0),
		ISNULL (TR_OUT.D_SUM_EKR, 0),
		ISNULL (TR_OUT.K_SUM_EKR, 0)
	FROM @TAB_ALL_REC ALL_REC
	INNER JOIN @DEP_TABLE D ON (D.LINK_DEP = ALL_REC.DEP) 
	INNER JOIN @TAB_EKR E ON (E.LINK_EKR = ALL_REC.EKR)
	INNER JOIN @TAB_KBK K ON (K.LINK_KBK = ALL_REC.KBK)
	LEFT OUTER JOIN @TAB_OBOROT T1 ON (T1.DEP = ALL_REC.DEP AND T1.EKR = ALL_REC.EKR)
	LEFT OUTER JOIN dbo.G_PROV G ON (G.LINK = T1.LINK_DOC)
	LEFT OUTER JOIN dbo.DICTIONARY_OTV_FACE OTV_B2 ON (OTV_B2.DEP_LINK = ALL_REC.DEP AND OTV_B2.[NAME] = 'Главный бухгалтер')
	LEFT OUTER JOIN @TAB_REST_DEP_IN TR_DEP_IN ON (TR_DEP_IN.DEP = ALL_REC.DEP)
	LEFT OUTER JOIN @TAB_REST_KBK_IN TR_KBK_IN ON (TR_KBK_IN.DEP = ALL_REC.DEP AND TR_KBK_IN.KBK = ALL_REC.KBK)
	LEFT OUTER JOIN @TAB_IN_REST TR_IN ON (TR_IN.DEP = ALL_REC.DEP AND TR_IN.KBK = ALL_REC.KBK AND TR_IN.EKR = ALL_REC.EKR)
	LEFT OUTER JOIN @TAB_REST_DEP_OUT TR_DEP_OUT ON (TR_DEP_OUT.DEP = ALL_REC.DEP)
	LEFT OUTER JOIN @TAB_REST_KBK_OUT TR_KBK_OUT ON (TR_KBK_OUT.DEP = ALL_REC.DEP AND TR_KBK_OUT.KBK = ALL_REC.KBK)
	LEFT OUTER JOIN @TAB_OUT_REST TR_OUT ON (TR_OUT.DEP = ALL_REC.DEP AND TR_OUT.KBK = ALL_REC.KBK AND TR_OUT.EKR = ALL_REC.EKR)

	SELECT * FROM @TAB_RES
		ORDER BY DEP_CODE1, DEP_CODE2, EKR_CODE, dDOC_DATE

	DROP TABLE #TABLE_ACCT
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_AKT_RESIVE_DEP1] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PF_REPORT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PF_REPORT]

GO
CREATE PROCEDURE [dbo].[SA_PF_REPORT]
	
	@YEAR  varchar (4), /* Год */
	@KVART varchar (4),	 /* Квартал */
	@PACHKA varchar (4) /* Номер пачка */

AS 
BEGIN

	DECLARE @DATE1 DATETIME,	/* Начало периода */
			@DATE2 DATETIME	/* Конец периода */

	-- Выборка линка организации 
	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT
	-- Дата начала периода
	set @DATE1 = (@YEAR + '0101')
	-- Дата окончания , по указанному кварталу 
	SET @DATE2 = (@YEAR + ''+(CASE WHEN @KVART = '1' THEN '0331'
								   WHEN @KVART = '2' THEN '0630' 
								   WHEN @KVART = '3' THEN '0930'
								   ELSE	'1231'
								END)+'')

	--Список физ лиц, по которым были начислены взносы

	CREATE TABLE #NACHISL0 (LINK INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
	
	INSERT INTO #NACHISL0 (LINK, SUM_STR, SUM_NAK)
	SELECT E.pers_link, SUM_STR = (CASE WHEN P.WAY_CALC = 6 THEN SUMMA ELSE 0 END), SUM_NAK = (CASE WHEN P.WAY_CALC = 7 THEN SUMMA ELSE 0 END)
	FROM 
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
		INNER JOIN dbo.EMPL E ON J.LINK_EMPL = E.LINK
	WHERE
		P.[OBJECT] = 3 AND P.WAY_CALC in (6,7)
		AND
		J.LINK_DEP = @LINK_DEP
		AND 
		J.PERIOD_BEGIN BETWEEN @DATE1 AND @DATE2
		And
		LINK_EMPL IS NOT NULL	

	INSERT INTO #NACHISL0 (LINK, SUM_STR, SUM_NAK)
	SELECT pers_link, SUM_STR = (CASE WHEN P.WAY_CALC = 6 THEN SUMMA ELSE 0 END), SUM_NAK = (CASE WHEN P.WAY_CALC = 7 THEN SUMMA ELSE 0 END)
	FROM 
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
	WHERE
		P.[OBJECT] = 3 AND P.WAY_CALC in (6,7)
		AND
		J.LINK_DEP = @LINK_DEP
		AND 		
		J.PERIOD_BEGIN BETWEEN @DATE1 AND @DATE2
		And
		LINK_EMPL IS NULL AND pers_link IS NOT NULL		

	CREATE TABLE #NACHISL (LINK INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
	
	INSERT INTO #NACHISL (LINK, SUM_STR, SUM_NAK)
	
	SELECT LINK, SUM(SUM_STR), SUM(SUM_NAK)
	FROM #NACHISL0
	GROUP BY LINK	

	--Пачки, из которых брать сведения о перечисленных суммах		
	CREATE TABLE #PACHKI (LINK INT)
	if exists (select link from DBO.SZV4_PACHKA where link = @PACHKA and LINK_DEP = @LINK_DEP)
	begin
		INSERT INTO #PACHKI(LINK)
		VALUES(@PACHKA)
	end
	WHILE EXISTS(
				SELECT P.LINK_SELF
				FROM 
					DBO.SZV4_PACHKA P 
					INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF and P.LINK_DEP = @LINK_DEP
				WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
					AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
					AND P2.YEAR_BEGIN = YEAR(@DATE2) AND P2.MONTH_END < MONTH(@DATE2)
				)
	BEGIN			

		INSERT INTO #PACHKI(LINK)
		SELECT P.LINK_SELF
		FROM 
			DBO.SZV4_PACHKA P 
			INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF and P.LINK_DEP = @LINK_DEP
		WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
			AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
			AND P2.YEAR_BEGIN = YEAR(@DATE2) AND P2.MONTH_END < MONTH(@DATE2)
	END

	--Сведения о перечисленных суммах
	CREATE TABLE #PERECHISL (LINK INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
	
	INSERT INTO #PERECHISL (LINK, SUM_STR, SUM_NAK)
	SELECT link_pers, SUM(SUM_STR), SUM(SUM_DOP)
	FROM
		#PACHKI P INNER JOIN dbo.SZV4_SVEDENIA S ON P.LINK = S.LINK_UP
	GROUP BY
		link_pers	
	
	--Список физ лиц, по которым есть сведения о начисленных, либо перечисленных суммах
	CREATE TABLE #PERS(LINK INT)
	
	INSERT INTO #PERS (LINK)
	SELECT DISTINCT LINK FROM #NACHISL
	UNION
	SELECT DISTINCT LINK FROM #PERECHISL

	SELECT
		P.LINK, 
		FIO = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.', 100),
		BIRTH = BIRTHDATE,
		INSUR_NUM,
		AGE_TYPE = CASE WHEN YEAR(P.BIRTHDATE) <= 1966 THEN 1 ELSE 2 END,
		NS.SUM_STR, SUM_STR_P = PS.SUM_STR,
		NS.SUM_NAK, SUM_NAK_P = PS.SUM_NAK
	FROM
		#PERS F
		INNER JOIN dbo.PERSON P ON P.LINK = F.LINK
		LEFT JOIN #NACHISL NS ON NS.LINK = F.LINK
		LEFT JOIN #PERECHISL PS ON PS.LINK = F.LINK
	ORDER BY
		FIO 	
	
	DROP TABLE #NACHISL
	DROP TABLE #PACHKI
	DROP TABLE #PERECHISL
	DROP TABLE #PERS

END



GO


GRANT EXECUTE ON dbo.[SA_PF_REPORT] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RN_IMPORT_FORM_0531467]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RN_IMPORT_FORM_0531467]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
CREATE PROCEDURE dbo.[RN_IMPORT_FORM_0531467]   
   @lvcKODF         VARCHAR(10),
   @lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
   @liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
   @bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0     -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON
DECLARE @liReturn     INT,
        @ltImportType TINYINT,
        @liLSF        INT,
        @lvcAdm       VARCHAR(3),                
        @lvcTXT   VARCHAR(8000),
        @lvcWord1 VARCHAR(8000),
        @lvcWord2 VARCHAR(8000),
        @lvcKBP   VARCHAR(50),
        @lvcVB    VARCHAR(50),
        @liORDER  INT,
        @i        INT,
		  @vcUK		varchar(100),
		  @iLinkOrg INT,
		  @cDate  VARCHAR(10),
		  @cOKATO VARCHAR(100),
        @cStr  VARCHAR(100),
        @region   VARCHAR(100)
        
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output 	
set @region=rtrim(isnull(@cstr,''))        

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   DECLARE curLSF CURSOR FOR
      SELECT [B].[LINK_SAVED_FORM]
      FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
      JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[KBP] = [B].[KBP] AND 
                                                  [A].[VB] = [B].[VB] AND 
                                                  [A].[LINK_FORM] = [B].[LINK_FORM] AND 
                                                  [A].[DT] = [B].[DT] AND 
                                                  [A].[PRD] = [B].[PRD] AND 
                                                  [A].[VF0] = [B].[VF0] AND 
                                                  [A].[IMPORT_DATE] >= [B].[IMPORT_DATE]
      WHERE [A].[LINK_SAVED_FORM] = @liRepeatRequest 
   
   OPEN curLSF
   
   FETCH NEXT 
   FROM curLSF
   INTO @liLSF
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
        
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liLSF,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode

      FETCH NEXT 
      FROM curLSF
      INTO @liLSF
   END
      
   CLOSE curLSF
   DEALLOCATE curLSF
   
   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  null,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'КОДФ=0531467')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  null,
                                                  @tMode

   RETURN @liReturn
END


CREATE TABLE #tabORG (ORDERS INT IDENTITY(1,1), OKATO VARCHAR(11), LINK_ORG INT, LINK_BUDG INT, KBP VARCHAR(20), VB VARCHAR(10))
if (select object_id('tempdb..#tmpIMPORT_TABLE')) is NOT NULL drop table #tmpIMPORT_TABLE 
create table #tmpIMPORT_TABLE(orders int IDENTITY(1, 1), txt varchar(8000), [FileName] varchar(128), OKATO VARCHAR(1000))
CREATE TABLE #treeORG (link INT, link_org INT, link_budg INT, KBP VARCHAR(20), VB VARCHAR(10), OKATO VARCHAR(20))

IF @region = 'МарийЭл'
BEGIN
   INSERT #tmpIMPORT_TABLE (txt, OKATO)
   SELECT txt, LEFT(dbo.RA_GETWORDNUM([txt],5,'|'),11) FROM #IMPORT_TABLE 
END
ELSE BEGIN    
   INSERT #tmpIMPORT_TABLE (txt, OKATO)
   SELECT txt, LEFT(dbo.RA_GETWORDNUM([txt],5,'|'),5)+'000000' FROM #IMPORT_TABLE
   
   -- Сгруппируем данные по первым 5 знакам ОКАТО
   UPDATE #tmpIMPORT_TABLE
   SET [TXT] = 
   LEFT([TXT],dbo.RA_GETWORDPOS([TXT],5,'|')-1)+SUBSTRING([TXT],dbo.RA_GETWORDPOS([TXT],5,'|'),5)+'000000|'+SUBSTRING([TXT],dbo.RA_GETWORDPOS([TXT],6,'|'),100)
   WHERE LEFT([TXT],7)='SDST|20'
END 



--SELECT * FROM #tmpIMPORT_TABLE
-- Вытащим дату отчета
   DECLARE @dtDateForm DATETIME
   SELECT @cDate = dbo.RA_GETWORDNUM([TXT], 3, '|') FROM #tmpIMPORT_TABLE WHERE LEFT([TXT],3)='SD|'

-- Первый день след. месяца
   IF PATINDEX('__.__.____', @cDate) > 0
	   BEGIN
         SELECT @i = 104
         SET @dtDateForm = CONVERT(DATETIME, @cDate, @i)
         SET @dtDateForm =  dateadd(month,1,dateadd(day,1-day(@dtDateForm),@dtDateForm))
	   END
   
-- Выберем все окато из текстового файла
INSERT #tabORG (OKATO)
SELECT DISTINCT OKATO FROM #tmpIMPORT_TABLE WHERE LEFT([TXT],7)='SDST|20'

   DECLARE @iHistory INT, @iCountOrg int
   SELECT @iHistory = dbo.RO_SVOD_TREE_Link_History(@dtDateForm)
-- пройдемся по дереву сверху вниз
   
   INSERT #treeOrg (link, link_org, link_budg, kbp, vb, okato)
   SELECT A.link, A.link_report_org, A.link_report_budg, B.budg, C.OUTCODE, REPLACE(B.OKATO, ' ', '')
   FROM  dbo.REPORT_SVOD_TREE A 
   INNER JOIN dbo.departments B ON A.LINK_REPORT_ORG = B.LINK
   INNER JOIN dbo.kl_budg_type C ON A.LINK_REPORT_BUDG = C.Link 
   WHERE A.LINK_HISTORY = @iHistory
         AND A.LINK_SELF IS NULL

   SELECT @iCountOrg = @@ROWCOUNT
         
-- Найдем все линки организаций, бюджетов
   WHILE @iCountOrg>0 
      BEGIN
         UPDATE #tabORG 
         SET LINK_ORG =  B.LINK_ORG,
            LINK_BUDG = B.LINK_BUDG,
            KBP = B.KBP,
            VB = B.VB
         FROM #tabORG A 
         INNER JOIN #treeOrg B ON A.OKATO = B.OKATO
         WHERE A.KBP IS NULL AND A.VB IS NULL

         INSERT #treeOrg (link, link_org, link_budg, kbp, vb, okato)
         SELECT A.link, A.link_report_org, A.link_report_budg, B.budg, C.OUTCODE, REPLACE(B.OKATO, ' ', '')
         FROM  dbo.REPORT_SVOD_TREE A 
         INNER JOIN dbo.departments B ON A.LINK_REPORT_ORG = B.LINK
         INNER JOIN dbo.kl_budg_type C ON A.LINK_REPORT_BUDG = C.Link 
         WHERE LINK_SELF IN (SELECT LINK FROM #treeOrg)
         AND NOT EXISTS (SELECT * FROM #treeOrg D WHERE D.LINK = A.LINK)
   
         SELECT @iCountOrg = @@ROWCOUNT
      END
   
      IF OBJECT_ID('tempdb..#IMPORT_TABLE') IS NOT NULL
      BEGIN
         DROP TABLE #IMPORT_TABLE
      END        

      CREATE TABLE #IMPORT_TABLE([TXT] VARCHAR(1000), 
                                 [ORDER] INT IDENTITY(1,1))     

WHILE EXISTS(SELECT * FROM #tabORG WHERE LINK_ORG IS NOT NULL  AND  KBP <>'' AND  VB<>'')
   BEGIN
      TRUNCATE TABLE #IMPORT_TABLE
      SELECT @lvcKBP = KBP, 
             @lvcVB =  VB,
             @i = ORDERS,
             @cOKATO = OKATO
      FROM #tabORG WHERE LINK_ORG IS NOT NULL 
      AND  KBP <>'' AND  VB<>''
      ORDER BY ORDERS
         
      DELETE #tabORG WHERE ORDERS = @i
      
      -- Заголовок
      INSERT #IMPORT_TABLE([TXT]) VALUES ('#%')
      INSERT #IMPORT_TABLE([TXT]) VALUES ('КОДФ=0531467')
      INSERT #IMPORT_TABLE([TXT]) VALUES ('ПРД=3')   
      INSERT #IMPORT_TABLE([TXT]) VALUES ('РДТ='+ISNULL(CONVERT(VARCHAR(10), @dtDateForm, 104),''))   
      INSERT #IMPORT_TABLE([TXT]) VALUES ('ВИД='+@lvcVB)   
      INSERT #IMPORT_TABLE([TXT]) VALUES ('ИСТ='+@lvcKBP)         

      INSERT #IMPORT_TABLE ([TXT]) VALUES ('РА=0')
      INSERT #IMPORT_TABLE ([TXT]) VALUES ('REPORTS_ATR_DATA_DAY=' + @cDate)
 
      INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=1')

      -- группировка по АДМ
      INSERT #IMPORT_TABLE([TXT])
      SELECT SUBSTRING([TXT], 12, 1000) + '|' + SUBSTRING([TXT], 12, 10) + '|' + SUBSTRING([TXT], 22, 4) + '|' + SUBSTRING([TXT], 26, 3)
      FROM #tmpIMPORT_TABLE 
      WHERE OKATO = @cOKATO
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  null,
                                                  @tMode
                                                      
   END
   

INSERT #t_Result ([TXT])
SELECT 'Не найдена организация с ОКАТО = ' + OKATO + CHAR(10)
FROM #tabORG WHERE LINK_ORG IS NULL

INSERT #t_Result ([TXT])
SELECT 'Нет КБП у организации с ОКАТО = ' + OKATO + CHAR(10)
FROM #tabORG WHERE LINK_ORG IS NOT NULL
 AND  KBP =''

RETURN @liReturn

GO
GRANT ALL ON dbo.[RN_IMPORT_FORM_0531467] 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].[RO_WEB_SAVE_0503360]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_SAVE_0503360]
GO






CREATE         PROCEDURE dbo.[RO_WEB_SAVE_0503360]
	@iLinkSF	int output,
	@bExcess tinyint = 0 output,	-- FOR WEB only
	@cText	varchar(50) = '' output,	-- FOR WEB only
	@RepeatRequest	int = NULL	-- повторный запуск
AS
SET @bExcess = 0
SET @cText='Результат'
if @RepeatRequest = 1 -- отчет не сохраняем
begin
	SET @bExcess = 1
	select '' as res
	return 0
end
create table #Res (orders int, resCode varchar(50), res varchar(8000))

DECLARE	@varKSintLINK	int,
	@varKSLinkF	int,
	@varKSVers	smallint,
	@varKSBDAte	datetime,
	@varKSpTYPE	tinyint,
	@varKSPNomber	tinyint,
	@varKSLinkOrg	int,
	@varKSisSvod	tinyint,
	@iRes	INT,
	@varKSisCalcItog INT,
	@varKSIsRO	tinyint,
	@varKSNote	varchar(500),
	@varKSLinkTypeSvod int,
	@varKSNewCountSave int,
	@varKSOldCountSave int,
	@varKSFIO varchar(500),
	@varKSLogin varchar(500),
	@varKSHostName varchar(500),
	@varKSDate varchar(500),
	@varKSEvent varchar(500),
	@varKSText varchar(500),
	@varKSWarMessage varchar(800),
	@varKSCodeForm	char(20),
   @lcPERIOD_YEAR CHAR(4), @Check INT 
-- Сохраняем заголовок
IF object_id('tempdb..#REP_HEAD') is NOT NULL 
begin
	SET @iRes = 0
	SELECT @varKSintLINK=link, @varKSLinkF=link_form, @varKSCodeForm = Code, @varKSVers=Version,
		@varKSBDAte = case period_type when 1 then LTRIM(STR(period_year)) + '1231' 
				when 2 then dateadd(quarter, period_number, LTRIM(STR(period_year)) + '0101') -1
				else dateadd(month, period_number, LTRIM(STR(period_year)) + '0101') - 1 end,

		@varKSpTYPE = period_type, @varKSPNomber = period_number,
		@varKSLinkOrg = link_organization, @varKSisSvod = IsSvod, @varKSisCalcItog = isCalcItog,
		@varKSIsRO = IsRO, @varKSNote = Note, @varKSLinkTypeSvod = Link_Type_Svod, @varKSNewCountSave = CountSave,
	   @lcPERIOD_YEAR     = LTRIM(STR([PERIOD_YEAR]))
	FROM #REP_HEAD


	EXEC dbo.[RA_WEB_DECODE_PERIOD] @varKSpTYPE   OUTPUT,
									@varKSPNomber OUTPUT,
									@varKSBDAte   OUTPUT,
									@lcPERIOD_YEAR  


	-- проверяем было ли произведено сохранение формы дргуим клиентом во время редактирования 
	-- т.е. изменился ли CountSave
	Select @varKSOldCountSave = CountSave from dbo.report_saved_forms where link_saved_form = @varKSintLINK
	SET @varKSNewCountSave = isnull(@varKSNewCountSave, 0)
	SET @varKSOldCountSave = isnull(@varKSOldCountSave, 0)
	If @varKSNewCountSave <> @varKSOldCountSave 
	begin
		SET @iLinkSF = @varKSintLINK
		SET @bExcess = 1
		-- определим кто сохранил

		SET @varKSFIO = '<не указан>'
		SET @varKSLogin = '<не указан>'
		SET @varKSHostName = '<не указан>'
		SET @varKSDate = '<не указан>'
		SET @varKSEvent = ' '
		SET @varKSText = ' '

		select 
		 @varKSFIO      = coalesce(ltrim(rtrim(sj.FIO)),'<не указан>'),
		 @varKSLogin    = coalesce(ltrim(rtrim(sj.Login)),'<не указан>'),
		 @varKSHostName = coalesce(ltrim(rtrim(sj.Hostname)),'<не указан>'),
		 @varKSDate  = coalesce(ltrim(rtrim(sj.Date)),'<не указан>'),
		 @varKSEvent = coalesce(ltrim(rtrim(sj.Event)),' '),
		 @varKSText  = coalesce(ltrim(rtrim(sj.Text)),' ')
		from sys_jurnal sj where sj.link = (select link_jurnal from dbo.REPORT_saved_forms where link_Saved_Form = @varKSintLINK)

	Set @varKSWarMessage = 'ОШИБКА СОХРАНЕНИЯ ДОКУМЕНТА: '
	Insert into #Res (orders, res)
	Values (0, @varKSWarMessage)
	Set @varKSWarMessage = 'Во время редактирования произошло сохранение документа другим пользователем. '
	Insert into #Res (orders, res)
	Values (1, @varKSWarMessage)
	Set @varKSWarMessage = '  Сотрудник: ' + @varKSFIO 
	Insert into #Res (orders, res)
	Values (2, @varKSWarMessage)
	Set @varKSWarMessage = '  Логин:     ' + @varKSLogin 
	Insert into #Res (orders, res)
	Values (3, @varKSWarMessage)
	Set @varKSWarMessage = '  Хост:      ' + @varKSHostName 
	Insert into #Res (orders, res)
	Values (4, @varKSWarMessage)
	Set @varKSWarMessage = '  Дата:      ' + @varKSDate
	Insert into #Res (orders, res)
	Values (5, @varKSWarMessage)
	Set @varKSWarMessage = '  Событие:   ' + @varKSEvent + @varKSText 
	Insert into #Res (orders, res)
	Values (6, @varKSWarMessage)
	Set @varKSWarMessage =  'Выйдите без сохранения и откройте обновленный отчет.'
	Insert into #Res (orders, res)
	Values (7, @varKSWarMessage)
		select res from #Res order by orders
		drop table #Res
		RETURN -1 --Ошибка сохранения заголовка формы
	end
	else
	begin
		Set @varKSNewCountSave=@varKSNewCountSave+1
	end




	IF @varKSLinkOrg is null or @varKSLinkOrg = 0
	begin
	SET @iLinkSF = @varKSintLINK
	SET @bExcess = 1
	Insert into #Res (orders, res)
	values (0, 'Ошибка сохранения документа: НЕ УКАЗАНА ОРГАНИЗАЦИЯ')
	select res from #Res order by orders
	drop table #Res
	RETURN -1 --Ошибка сохранения заголовка формы
	end

	if (select count(*) from report_saved_forms where link_saved_form = @varKSintLINK) = 0
		set  @varKSintLINK = 0	

	if not exists(select * from dbo.RO_SVOD_TREE where LINK_REPORT_ORG = @varKSLinkOrg and LINK_REPORT_BUDG = @varKSLinkTypeSvod) and @varKSLinkTypeSvod is not NULL
		set @varKSLinkTypeSvod = dbo.RO_SVOD_BUDG_FOR_ORG(@varKSLinkOrg)
/*
	if IS_MEMBER('Свод-КС') = 1 and dbo.RO_SVOD_STATUS_ACCESS(@varKSLinkTypeSvod, @varKSLinkOrg, @varKSisSvod, @varKSLinkF, @varKSpTYPE, @varKSPNomber, @varKSBDAte) < 255
	begin
		if @varKSISRO = 2
		begin
			Insert into #Res (orders, res)
			 select 0, 'Ошибка сохранения документа: НЕ ДОСТУПЕН СТАТУС ''' + Status_Name + ''''
				from report_status where Status = @varKSISRO
		end
		else begin
			Insert into #Res (orders, res)
			 select 0, 'Ошибка сохранения документа: ОТЧЕТ ДАННОЙ ФОРМЫ ОТЧЕТНОСТИ НЕ МОЖЕТ БЫТЬ ИЗМЕНЕН, ТАК КАК ОН УЖЕ ВКЛЮЧЕН В СВОД'
		end
		SET @iLinkSF = @varKSintLINK
		SET @bExcess = 1
		select res from #Res order by orders
		drop table #Res
		RETURN -1 --Ошибка сохранения заголовка формы
	end
*/
declare @catr_val varchar(250),@atr varchar(250),@atributs varchar(250),@li int,@str_val varchar(250),@cexec varchar(4000)
set @atributs=''
set @catr_val=''
create table #TMP_STR_VAL (str_val varchar(250))
IF object_id('tempdb..#REP_ATR') is not null 
    begin
    select @atributs=rtrim(atributs) from report_forms where link_form= @varKSLinkF
    set @li=1
    set @catr_val=''
    IF @atributs<>''
       begin 
        WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
                delete #TMP_STR_VAL                  
                set @cexec='INSERT #TMP_STR_VAL SELECT TOP 1 '+@atr+' FROM #REP_ATR'
                print @cexec
                execute(@cexec)
                select @str_val=ISNULL((select str_val from #TMP_STR_VAL),ISNULL(dbo.get_val(@atr,'DEFAULT_VALUE',0),'')) 
                set @catr_val=@catr_val+case when @catr_val<>'' then ',' else '' end+ RTRIM(@atr)+'='+rtrim(@str_val)
                set @li=@li+1
            end
        END
    END
    

	if @RepeatRequest = 0 -- отчет перезаписываем
	begin
		if exists(select top 1 * from report_saved_forms where Link_Form = @varKSLinkF and Begin_Date = @varKSBDAte and period_type = @varKSpTYPE and period_number = @varKSPNomber and Link_Organization = @varKSLinkOrg and IsSvod = @varKSisSvod and Link_Type_Svod = @varKSLinkTypeSvod and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 = 0)
		begin -- нет прав удалить отчеты
			SET @bExcess = 1
			SET @cText='Результат'
			Insert into #Res (orders, res)
			 select 0, 'Невозможно перезаписать отчет! Нет доступа!'
			select res from #Res order by orders
			drop table #Res
			RETURN 0 --Ошибка сохранения заголовка формы
		end
		delete report_saved_forms
		where Link_Form = @varKSLinkF and Begin_Date = @varKSBDAte and period_type = @varKSpTYPE and period_number = @varKSPNomber and Link_Organization = @varKSLinkOrg and IsSvod = @varKSisSvod and Link_Type_Svod = @varKSLinkTypeSvod and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 > 0	
	end

	EXEC @iRes = I_REPORT_SAVE_FORM @varKSintLINK output, @varKSLinkF, @varKSVers, @varKSBDAte, @varKSpTYPE, @varKSPNomber, @varKSLinkOrg, @varKSisSvod, default, default, default, default, @varKSIsRO, @varKSNote, 0, @varKSLinkTypeSvod, @varKSNewCountSave, 0, 0, @catr_val
	if @iRes = 11000 -- возникает только тогда когда стоит настройка
	begin
		SET @bExcess = 2
		SET @cText='Результат @ 0 - Да @ 1 - Нет'
		Insert into #Res (orders, res)
		 select 0, 'Такой отчет уже существует! Перезаписать существующий отчет на этот (ДАННЫЕ СУЩЕСТВУЮЩЕГО ОТЧЕТА ПОТЕРЯЮТСЯ) ?'
		select res from #Res order by orders
		drop table #Res
		RETURN 0 --Ошибка сохранения заголовка формы
	END
   IF object_id('tempdb..#REP_ATR') is not null 
       begin
       select @atributs=rtrim(atributs) from report_forms where link_form= @varKSLinkF
       set @li=1
       set @catr_val=''
       IF @atributs<>''
          begin 
           WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
               begin
                   set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
                   delete #TMP_STR_VAL                  
                   set @cexec='INSERT #TMP_STR_VAL SELECT TOP 1 '+@atr+' FROM #REP_ATR'
                   print @cexec
                   execute(@cexec)
                   select @str_val=ISNULL((select str_val from #TMP_STR_VAL),ISNULL(dbo.get_val(@atr,'DEFAULT_VALUE',0),'')) 

				   -- провека атрибутов на наличие в справочнике
				   exec @Check = dbo.RO_CHECK_ATR_FROM_DICT @atr,@str_val
				   if @Check <> 0
				   begin
					   SET @bExcess = 1
					   Insert into #Res (orders, res)
					   values (0, 'Ошибка сохранения документа: ЗНАЧЕНИЕ АТРИБУТА ОТСУТСТВУЕТ В СПРАВОЧНИКЕ')
					   select res from #Res order by orders
					   drop table #Res
					   RETURN -1 --Ошибка сохранения заголовка формы
				   end
				   -- ---------

                   exec dbo.RN_SAVE_ATRIBUT_VALUES    @varKSintLINK,@atr,@str_val
                   set @li=@li+1
               end
           END
       end
   
	IF @iRes<>0 or @varKSintLINK<=0
		RETURN -1 --Ошибка сохранения заголовка формы
end

-- 1. - список таблиц
DECLARE @ilTable	int,
	@iTOrders	tinyint,
	@iLCol		int,
	@iCOrders	tinyint,
	@cRunStr	varchar(200),
	@Shifr		varchar(10)

IF object_id('tempdb..#REP_TABLE') is NOT NULL 
begin
	--перенос формы из архивной базы
	exec RN_MOVE_FORM_FROM_ARH @varKSintLINK
	create table #dest (orders int identity(1,1), link_up int, txt varchar(1000))

	exec text2varchar
		@cTableSour ='#REP_TABLE',
		@cValueSour ='value',
		@cKeySour ='link',
		
		@cTableDest ='#dest',
		@cValueDest ='txt',
		@cKeyUpDest ='link_up'
	
	select @varKSintLINK = link_up from  #dest

	exec dbo.rn_save_text_form @varKSintLINK, '#dest', 0
	drop table #dest
end


SET @iLinkSF = @varKSintLINK

declare @ord int, @cCodeOrg varchar (50), @cNameOrg varchar(250)
select @ord = max(orders) from #Res
if @ord is null
	set @ord = 1


select resCode, res from #Res order by orders
drop table #Res
EXEC dbo.droptemptable '#TMP_STR_VAL'



GO
GRANT ALL ON dbo.[RO_WEB_SAVE_0503360] 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.[RO_EXPORT_FORM_372]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_372]
END
GO



/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_372]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @vcOKATO VARCHAR(100), @vcPPP VARCHAR(100) , @iOrder INT 

DECLARE @tabFileExport TABLE ([TXT]	        VARCHAR(800), 
							         [NAMEFILE]    VARCHAR(100), 
                              [NAMEFILEARH] VARCHAR(100),
							         [ORDERS]      INT IDENTITY(1,1))  


EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders <= (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=01')
   ORDER BY ORDERS

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders > (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=02')
         AND orders < (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = '#&')
         AND TXT NOT LIKE '%|0|00011|000|%'
   ORDER BY ORDERS

   UPDATE @tabFileExport
   SET TXT = REPLACE(TXT, '999|9999|9999999|999|9|99999|999|999|', '***|****|*******|***|*|*****|***|***|')
   WHERE TXT LIKE '999|9999|9999999|999|9|99999|999|999|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#@<LN>ТБ=02', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport   
   
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT NOT LIKE '888|8888|8888|88|8888|8|88888|888|888|%'
         AND orders > (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=01')
         AND orders < (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=02')
         AND TXT NOT LIKE '%|0|00011|000|%'
   ORDER BY ORDERS

   UPDATE @tabFileExport
   SET TXT = REPLACE(TXT, '777|7777|7777|77|7777|7|77777|777|777|', '***|****|****|**|****|*|*****|***|***|')
   WHERE TXT LIKE '777|7777|7777|77|7777|7|77777|777|777|%'      
   

   
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 'ТБ=03<LN>#$', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   
   SELECT @iOrder = MIN(ORDERS) -1
   FROM #FileExportReport
   WHERE TXT LIKE '%|0|00011|000|%' AND TXT not LIKE '%|0|00011|000|000|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT '11|' + RIGHT('000' + LTRIM(RTRIM(STR(orders - ISNULL(@iOrder,0)))),3) + SUBSTRING(TXT, CHARINDEX('|0|00011|000|', TXT) +  16, 8000), [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT LIKE '%|0|00011|000|%' AND TXT not LIKE '%|0|00011|000|000|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT   '11|***|' + SUBSTRING(TXT, CHARINDEX('|0|00011|000|', TXT) +  17, 8000), [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT LIKE '%|0|00011|000|000|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT   '**|***|' + SUBSTRING(TXT, CHARINDEX('|0|00011|000|', TXT) +  17, 8000), [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT LIKE '%|0|00011|000|000|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport   
   
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#@<LN>ТБ=04<LN>#$', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT REPLACE(TXT, '888|8888|8888|88|8888|8|88888|888|888|', '***|**************|*|*****|***|***|'), [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT LIKE '888|8888|8888|88|8888|8|88888|888|888|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport


   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders >= (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = '#&')
   ORDER BY ORDERS

   UPDATE @tabFileExport
   SET TXT = LEFT(REPLACE(TXT, '000|0000|0000000|000|', '***|****|*******|***|'),33) + '***' + SUBSTRING(TXT, CHARINDEX('|', TXT, 34), 8000)
   WHERE RTRIM(TXT) LIKE '000|0000|0000000|000|%|-|' AND dbo.[RA_GETWORDNUM](TXT, 8, '|') ='000'

   UPDATE @tabFileExport
   SET TXT = LEFT(REPLACE(TXT, '000|0000|0000|00|0000|', '***|****|****|**|****|'),34) + '***' + SUBSTRING(TXT, CHARINDEX('|', TXT, 35), 8000)
   WHERE RTRIM(TXT) LIKE '000|0000|0000|00|0000|%|-|' AND dbo.[RA_GETWORDNUM](TXT, 9, '|') ='000'

   DELETE #FileExportReport
   
   INSERT #FileExportReport ([TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS]
   FROM @tabFileExport
                                  
END



GO
GRANT ALL ON dbo.RO_EXPORT_FORM_372 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_SAVE_G_PROV2_AP_LIMIT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_SAVE_G_PROV2_AP_LIMIT]
GO


CREATE	PROCEDURE [dbo].[FB_SAVE_G_PROV2_AP_LIMIT]
	@varKSnLINK_GP1  INT,		
	@varKSnTYP_LINK INT,			
	@varKSnSumma	NUMERIC(28,2) = 0.00,		
	@varKSdCALC_DATE DATETIME = NULL, 	
	@varKSnKBK		INT,
	@varKSnEKR		INT,
	@varKSnDOP_CL	INT,
	@varKSdDATEB	DATETIME,
	@varKSnDEP		INT,
	@varKSnDEP_ACC	INT, 
	@varKScG2_NAME	VARCHAR(254),
	@varKScTypeBudg char(1),
	@varKSnDEP_POL	INT = NULL,
	@varKSnACC_POL	INT = NULL,
	@iDtACC			INT = NULL,
	@inYear			int = 0,
	@iAssign		int = 0,
	@iOsnovLink		int = NULL
	




AS

DECLARE @varKScSOU_CODE CHAR(1),
	@varKSnSUB INT,
	@varKSnEMP INT,
	@varKSnNOMEN INT,
	@varKSnINV INT,
	@varKSnKAU INT,
	@varKSnTMC INT,
	@varKSnAP1 INT,
	@varKSnAP3 INT,
	@varKSnSGU_DT INT,
	@varKSnSGU_KT INT,
	@varKSnG2_LINK  INT,
	@varKSnG2_ECON_OPER INT,
	@varKSnG2_ORDERS INT,
	@varKSnGAP_ACCOUNT_DT INT,
	@varKSnGAP_ACCOUNT_KT INT,
	@varKSnLINK_GP2 INT,
	@varKSnLINK_ACC_DT INT,
	@varKSnLINK_ACC_KT INT,
	@varKSxRet INT,
	@varKSnDEP1 INT,
	@varKSnDEP_ACC1 INT,
	@iAnalitEKR	int,
	@iNewEconOperLink int,
	@iDEP_ACC2 INT
	

set @inYear = isnull(@inYear,0)	
set @iAssign = isnull(@iAssign,0)	
set @varKSnDEP_POL = isnull(@varKSnDEP_POL,@varKSnDEP)
	
DECLARE G2_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT LINK, /*NAME,*/ ECON_OPER, ORDERS FROM G_PROV2 WHERE LINK_UP = @varKSnTYP_LINK

IF @varKSnLINK_GP1 IS NULL
	RETURN -1	

IF @varKSdCALC_DATE IS NULL
	SELECT @varKSdCALC_DATE = WORKDATE FROM USER_INFO


OPEN G2_CUR
FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK, /*@varKScG2_NAME,*/ @varKSnG2_ECON_OPER, @varKSnG2_ORDERS

WHILE @@FETCH_STATUS = 0
BEGIN
	
	SET @varKSnLINK_GP2 = NULL
	set @varKSnLINK_ACC_DT = null
	set @varKSnLINK_ACC_KT = null
	EXEC @varKSxRet = X_UPDATE_G_PROV2 @varKSnLINK_GP2 OUTPUT, @varKSnLINK_GP1, NULL,
		@varKSnSumma,0, 0, @varKScG2_NAME, @varKSnG2_ECON_OPER,  @varKSnG2_ORDERS
	IF @varKSxRet <> 0
		RETURN @varKSxRet
	IF @varKSnLINK_GP2 IS NULL
		RETURN -3

	SELECT GAP.*
	INTO #GAP_CUR
	FROM G_PROV_AP GAP
	WHERE GAP.LINK_UP = @varKSnG2_LINK

	SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT, 
			@varKSnSGU_DT = SGU, 
			@varKSnSUB = SUB, 
			@varKSnEMP= EMP, 
			@varKSnNOMEN = NOMEN, 
			@varKSnINV = INV, 
			@varKSnTMC = TMC, 
			@varKSnKAU = KAU,
			@varKSnAP1 = isnull(@iOsnovLink,AP1), 
			@varKSnAP3 = AP3
	FROM #GAP_CUR WHERE DB_KR = 0

	if @iDtACC is not null
		set @varKSnGAP_ACCOUNT_DT = @iDtACC

	
	SELECT TOP 1 @varKSnLINK_ACC_DT = SA2.LINK, @iAnalitEKR = SA2.ANALIT_EKR FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2 WHERE SA1.LINK = @varKSnGAP_ACCOUNT_DT 
		AND SA2.ZABALANS = SA1.ZABALANS
		AND (@inYear = 0 and SA2.cAnalit = SA1.cAnalit or @inYear <> 0 and SA2.cAnalit = cast(@inYear as char(1)) + right(SA1.cAnalit,1))
		AND ((LEN(SA1.cSinth) = 3 AND (SA1.cSinth = SA2.cSinth and @iAssign = 0 or SA2.cSinth = left(SA1.cSinth,2) + '3' and @iAssign = 1)) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
		AND SA2.cUser = SA1.cUser
		AND ((LEN(SA1.cAnalit) = 2 and SA2.cSource = @varKScTypeBudg) or LEN(SA1.cAnalit) < 2 )
	if @varKSnLINK_ACC_DT is null 
		SELECT TOP 1 @varKSnLINK_ACC_DT = SA2.LINK, @iAnalitEKR = SA2.ANALIT_EKR FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2 WHERE SA1.LINK = @varKSnGAP_ACCOUNT_DT 
			AND SA2.ZABALANS = SA1.ZABALANS
			AND (@inYear = 0 and SA2.cAnalit = SA1.cAnalit or @inYear <> 0 and SA2.cAnalit = cast(@inYear as char(1)) + right(SA1.cAnalit,1))
			AND ((LEN(SA1.cSinth) = 3 AND (SA1.cSinth = SA2.cSinth and @iAssign = 0 or SA2.cSinth = left(SA1.cSinth,2) + '3' and @iAssign = 1)) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
			AND SA2.cUser = SA1.cUser
			AND ((LEN(SA1.cAnalit) = 2 and SA2.cSource = SA1.cSource) or LEN(SA1.cAnalit) < 2)
	if @iAnalitEKR is not null and @iAnalitEKR <> @varKSnEKR
			select @varKSnLINK_ACC_DT = LINK 
			from dbo.S_ACCOUNTS
			where left(code,5) = (select left(code,5) from dbo.S_ACCOUNTS where link = @varKSnLINK_ACC_DT) 
				and @varKSnEKR = ANALIT_EKR	

	if @varKSnLINK_ACC_DT is null
		return - 12
	if exists(SELECT * FROM dbo.S_ACCOUNTS where LINK_SELF = @varKSnLINK_ACC_DT)
		return - 13

	IF @varKSnDEP_POL IS NULL
		SET @varKSnDEP_POL = @varKSnDEP

	IF @varKSnACC_POL IS NULL
		SET @varKSnACC_POL = @varKSnDEP_ACC
	
	if @varKSnSGU_DT is null  or @varKSnSGU_DT not in (select SGU_LINK from dbo.PLAN_ACCOUNTS_SGU where DB_KR = 0 and account = @varKSnLINK_ACC_DT)
		set @varKSnSGU_DT = (select top 1 SGU_LINK from dbo.PLAN_ACCOUNTS_SGU where DB_KR = 0 and account = @varKSnLINK_ACC_DT) 
	if exists(SELECT * FROM dbo.S_ACCOUNTS where LINK = @varKSnLINK_ACC_DT and p_KASSA = 1)
		set @varKSnSGU_DT = @varKSnEKR
	
	EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 0, @varKSnLINK_ACC_DT, @varKSnKBK, @varKSnEKR, @varKSnDEP,
			@varKSnSUB, @varKSnEMP, @varKSnNOMEN, @varKSnINV, @varKSnKAU, @varKSnDEP_ACC, @varKSnTMC, @varKSdDATEB, @varKSnAP1,  @varKSnDOP_CL, @varKSnAP3, @varKSnSGU_DT
	
	IF @varKSxRet <> 0
		RETURN @varKSxRet
	
	SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT, 
			@varKSnSGU_KT = SGU, 
			@varKSnSUB = SUB, 
			@varKSnEMP= EMP, 
			@varKSnNOMEN = NOMEN, 
			@varKSnINV = INV, 
			@varKSnTMC = TMC, 
			@varKSnAP1 = isnull(@iOsnovLink,AP1), 
			@varKSnAP3 = AP3
	FROM #GAP_CUR WHERE DB_KR = 1

	SELECT TOP 1 @varKSnLINK_ACC_KT = SA2.LINK, @iAnalitEKR = SA2.ANALIT_EKR FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2 WHERE SA1.LINK = @varKSnGAP_ACCOUNT_KT 
		AND SA2.ZABALANS = SA1.ZABALANS
		AND (@inYear = 0 and SA2.cAnalit = SA1.cAnalit or @inYear <> 0 and SA2.cAnalit = cast(@inYear as char(1)) + right(SA1.cAnalit,1))
		AND ((LEN(SA1.cSinth) = 3 AND (SA1.cSinth = SA2.cSinth and @iAssign = 0 or SA2.cSinth = left(SA1.cSinth,2) + '3' and @iAssign = 1)) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
		AND SA2.cUser = SA1.cUser
		AND ((LEN(SA1.cAnalit) = 2 and SA2.cSource = @varKScTypeBudg) or LEN(SA1.cAnalit) < 2 )
	
	if @varKSnLINK_ACC_KT is null 
		SELECT TOP 1 @varKSnLINK_ACC_KT = SA2.LINK, @iAnalitEKR = SA2.ANALIT_EKR FROM S_ACCOUNTS SA1, S_ACCOUNTS SA2 WHERE SA1.LINK = @varKSnGAP_ACCOUNT_KT 
			AND SA2.ZABALANS = SA1.ZABALANS
			AND (@inYear = 0 and SA2.cAnalit = SA1.cAnalit or @inYear <> 0 and SA2.cAnalit = cast(@inYear as char(1)) + right(SA1.cAnalit,1))
			AND ((LEN(SA1.cSinth) = 3 AND (SA1.cSinth = SA2.cSinth and @iAssign = 0 or SA2.cSinth = left(SA1.cSinth,2) + '3' and @iAssign = 1)) OR (LEN(SA1.cSinth) < 3 AND SA2.cSinth LIKE (RTRIM(SA1.cSinth) + '%') ))
			AND SA2.cUser = SA1.cUser
			AND ((LEN(SA1.cAnalit) = 2 and SA2.cSource = SA1.cSource) or LEN(SA1.cAnalit) < 2 )
	
	if @iAnalitEKR is not null and @iAnalitEKR <> @varKSnEKR
			select @varKSnLINK_ACC_KT = LINK 
			from dbo.S_ACCOUNTS
			where left(code,5) = (select left(code,5) from dbo.S_ACCOUNTS where link = @varKSnLINK_ACC_KT) 
				and @varKSnEKR = ANALIT_EKR
		
	if @varKSnLINK_ACC_KT is null
		return - 6

	if exists(SELECT * FROM dbo.S_ACCOUNTS where LINK_SELF = @varKSnLINK_ACC_KT)
		return - 7

	if @varKSnSGU_KT is null or @varKSnSGU_KT not in (select SGU_LINK from dbo.PLAN_ACCOUNTS_SGU where DB_KR = 1 and account = @varKSnLINK_ACC_KT)
		set @varKSnSGU_KT = (select top 1 SGU_LINK from dbo.PLAN_ACCOUNTS_SGU where DB_KR = 1 and account = @varKSnLINK_ACC_KT) 

	if exists(SELECT * FROM dbo.S_ACCOUNTS where LINK = @varKSnLINK_ACC_KT and p_KASSA = 1)
		set @varKSnSGU_KT = @varKSnEKR
		

	if exists(SELECT * FROM dbo.S_ACCOUNTS where LINK = @varKSnLINK_ACC_KT and left(cSinth,2) = '50' and right(cAnalit,1) = '3') and @varKSnDEP_POL <> @varKSnDEP
	begin
		select @iDEP_ACC2 = LINK from dbo.DEPARTMENT_ACCOUNTS where CODE = (select TOP 1 CODE from dbo.DEPARTMENT_ACCOUNTS where link = @varKSnACC_POL) and LINK_UP = @varKSnDEP
		if @iDEP_ACC2 is null
			set @varKSnACC_POL = @varKSnDEP_ACC
		else 
			set @varKSnACC_POL = @iDEP_ACC2
	end
	
		
	EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 1, @varKSnLINK_ACC_KT, @varKSnKBK, @varKSnEKR, @varKSnDEP_POL,
		@varKSnSUB, @varKSnEMP, @varKSnNOMEN, @varKSnINV, @varKSnKAU, @varKSnACC_POL, @varKSnTMC, @varKSdDATEB, @varKSnAP1, @varKSnDOP_CL, @varKSnAP3, @varKSnSGU_KT
	IF @varKSxRet <> 0
		RETURN @varKSxRet

	set @iNewEconOperLink = (select top 1 LINK from dbo.BX_BPROV_VIBOR_ECON_OPER(@varKSnLINK_ACC_DT, @varKSnLINK_ACC_KT))
	
	if @iNewEconOperLink is not null and @iNewEconOperLink <> @varKSnG2_ECON_OPER and @varKSnG2_ECON_OPER not in (select LINK from dbo.BX_BPROV_VIBOR_ECON_OPER(@varKSnLINK_ACC_DT, @varKSnLINK_ACC_KT))
	begin 
		update dbo.G_PROV2 
		set ECON_OPER = @iNewEconOperLink, NAME = (select NAME from dbo.XOZ_OPER where LINK = @iNewEconOperLink)
		where LINK = @varKSnLINK_GP2
		if @varKSnG2_ORDERS = 1
			update dbo.G_PROV1 
			set NAME_OPER = (select NAME from dbo.XOZ_OPER where LINK = @iNewEconOperLink)
			where LINK = @varKSnLINK_GP1
	end
	set @iNewEconOperLink = null

	
	FETCH NEXT FROM G2_CUR INTO @varKSnG2_LINK,/* @varKScG2_NAME,*/ @varKSnG2_ECON_OPER, @varKSnG2_ORDERS
	DROP TABLE #GAP_CUR
END

CLOSE G2_CUR
DEALLOCATE G2_CUR



RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHECK_KS_OUTSIDE_125]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHECK_KS_OUTSIDE_125]
GO

CREATE PROCEDURE [dbo].[RO_CHECK_KS_OUTSIDE_125]
AS
SET NOCOUNT ON 
declare @link_sf     int,
		@link_f        int,
		@fo_grbs       int,
		@ksbu          varchar(9),
		@nomErr        int,
		@curr_form     varchar(50),
      @j             INT,
      @table         TINYINT,
      @iLink_Table   INT,
      @self_okato    VARCHAR(250),
      @link_f_125    INT,
      @period_type   TINYINT,
      @period_number TINYINT,
      @period_date   DATETIME,
      @cGroupKS      VARCHAR(30),
      @nn            INT,
      @ppp           CHAR(3),
      @okato         VARCHAR(20),
      @summa_dt      NUMERIC(20,4),
      @summa_kt      NUMERIC(20,4),
      @cCODE_RULE    CHAR(9),
      @link_f_425    INT,
      @self_ppp      CHAR(3),
      @el_budg       CHAR(2),
      @okato_org     VARCHAR(20),
      @org_link      INT,
      @cFilter       VARCHAR(8000),
      @cExecStr      VARCHAR(8000),
      @iLinkOrgFoms INT,
      @vcCodeForm    VARCHAR(30),
      @li INT ,
      @i INT,
      @vcPostFix VARCHAR(10),
      @vcMask VARCHAR(50)

CREATE TABLE #mdks_125 ([CODE_RULE]       CHAR(9),
                        [KSBU]            CHAR(9),
                        [SIGN]            CHAR(2),
                        [FILTER]          VARCHAR(8000),
                        [ORDER_TABLE]     TINYINT,
                        [PART]           TINYINT,
                        [GROUP_OKATO_ORG] TINYINT,
                        [GROUP_OKATO_DATA] TINYINT,
                        [FO_GRBS]        TINYINT,
                        [DT_KT]          TINYINT,
                        [IS_ABS]          TINYINT,
                        [I]               INT,
                        [TYPE_RULE]       TINYINT) -- 1 - ФО-ФО
                                               -- 2 - ГРБС-ГРБС
                                               -- 3 - ФО - ГРБС
                                               -- 4 - ФО - ФОМС
                                               -- 5 - ГРБС - ФОМС 

CREATE TABLE #mdks_125_filter (
                        [KSBU]            CHAR(9),
                        [SIGN]            CHAR(2),
                        [ORDER_TABLE]     TINYINT,
                        [PART]           TINYINT,
                        [GROUP_OKATO_ORG] TINYINT,
                        [GROUP_OKATO_DATA] TINYINT,
                        [FO_GRBS]        TINYINT,
                        [DT_KT]          TINYINT,
                        [IS_ABS]          TINYINT,
                        [TYPE_RULE]       TINYINT,
                        [I]               INT IDENTITY(1,1))
                        
CREATE TABLE #summand_reports_125([CODE_RULE]       CHAR(9),
                           [PART]            TINYINT,
                           [LSF]             INT,
                           [ORDER_TABLE]     TINYINT,
                           [DT_KT]           TINYINT,
                           [GROUP_OKATO_DATA] TINYINT,
                           [GROUP_OKATO_ORG] TINYINT,
                           [FO_GRBS]        TINYINT,                           
                           [SIGN]            CHAR(2),
                           [FILTER]          VARCHAR(8000),
                           [PPP]             CHAR(3),
                           [OKATO]           VARCHAR(20),
                           [IS_ABS]          TINYINT,
                           [GROUP_CODE]      VARCHAR(50),
                           [I]               INT,
                           [TYPE_RULE]       TINYINT)

CREATE TABLE #summand_125( [CODE_RULE]       CHAR(9),
                           [PART]            TINYINT,
                           [LSF]             INT,
                           [ORDER_TABLE]     TINYINT,
                           [DT_KT]           TINYINT,
                           [CODE]            VARCHAR(250),
                           [CODE_ROW]        VARCHAR(250),
                           [SIGN]            CHAR(2),
                           [VALUE]           NUMERIC(20,4),
                           [PPP]             CHAR(3),
                           [OKATO]           VARCHAR(20),
                           [FO_GRBS]         TINYINT,
                           [FILTER]          VARCHAR(8000),
                           [IS_ABS]          TINYINT,
                           [TYPE]            VARCHAR(10),
                           [I]               INT)

CREATE TABLE #Result_125 ([CODE_RULE]        CHAR(9),
                          [CODE]             VARCHAR(250),
                          [PART]             TINYINT,
                          [VALUE]            NUMERIC(20,2))                             

CREATE TABLE #Result_sr_125 ([CODE_RULE]        CHAR(9),
                             [CODE]             VARCHAR(250),
                             [LEFT_VALUE]       NUMERIC(20,4),
                             [RIGHT_VALUE]      NUMERIC(20,4))
                             
CREATE TABLE #report_dinamics_125 (Link_SF INT, Link_Col INT, Code_Row VARCHAR(50), Float_Val FLOAT, Str_val VARCHAR(8000))
CREATE INDEX #IX_report_dinamics_125 ON #report_dinamics_125 (Link_SF, LINK_COL, CODE_ROW)                              
CREATE INDEX #IX_report_dinamics_125_1 ON #report_dinamics_125 (Link_SF)
CREATE INDEX #IX_report_dinamics_125_2 ON #report_dinamics_125 (Link_SF, Link_Col)
                             
exec DropTempTable '#report'
create table #report (nn int identity(1,1), ppp varchar(3), okato varchar(11), el_budg varchar(2), code_acc varchar(9), summa_dt numeric(20,4), summa_kt numeric(20,4), korr_acc varchar(9), tab int)

exec DropTempTable '#report_org'
create table #report_org (nn int identity(1,1), ppp varchar(3), summa_dt numeric(20,4), summa_kt numeric(20,4), tab int, okato varchar(20), el_budg varchar(2))

SET @vcPostFix = ''
IF OBJECT_ID('tempdb..#t_PeriodType') IS NOT NULL
BEGIN
   IF (SELECT PeriodType FROM #t_PeriodType) = 1
      SET @vcPostFix = 'G'
   ELSE
      SET @vcPostFix = 'M'      
END    

SELECT TOP 1 @link_sf = lf.lsf,
       @cGroupKS = cGroupKS,
       @vcCodeForm = RTRIM(CodeForm),
       @link_f = lf.linkForm,
       @fo_grbs = 1 - dbo.RT_IS_GRBS(lf.lsf),
       @ksbu = dbo.RN_GET_ATR_VALUE (lf.lsf ,'REPORTS_ATR_ACC_2011')
                    
FROM   #ListForms AS lf
WHERE  lf.linkForm IN (SELECT link_form
                       FROM   dbo.report_forms
                       WHERE  code LIKE '%425' + @vcPostFix + '%')

IF @link_sf IS NULL
BEGIN
   SELECT TOP 1 @link_sf = lf.lsf,
          @cGroupKS = cGroupKS,
          @vcCodeForm = RTRIM(CodeForm),
          @link_f = lf.linkForm,
          @fo_grbs = 1 - dbo.RT_IS_GRBS(lf.lsf),
          @ksbu = dbo.RN_GET_ATR_VALUE (lf.lsf ,'REPORTS_ATR_ACC_2011')                  
   FROM   #ListForms AS lf
   WHERE  lf.linkForm IN (SELECT link_form
                          FROM   dbo.report_forms
                          WHERE  code LIKE '%0503125' + @vcPostFix + '%')
END                        
                              
SELECT @period_type = rsf.[Period_Type], @period_number = rsf.[Period_Number], @period_date = rsf.[Begin_Date], @self_okato = ',' + REPLACE(d.[OKATO], ' ', ''), @self_ppp = d.[VED], @org_link = rsf.[Link_Organization]   
FROM dbo.[REPORT_SAVED_FORMS] rsf JOIN dbo.[DICTIONARY_DEPARTMENT] d ON [LINK] = rsf.[Link_Organization]
WHERE rsf.[Link_Saved_Form] = @link_sf

SELECT @self_okato = RTRIM(@self_okato) + ',' + REPLACE(d.[OKATO], ' ', '')
FROM dbo.[REPORT_SAVED_FORMS] rsf
       JOIN dbo.[REPORT_SVOD_TREE] rst ON rst.[Link_report_Org] = rsf.[Link_Organization] AND ISNULL(rsf.[Link_Type_Svod], 0) = ISNULL(rst.[Link_report_Budg], 0)
                                     AND rst.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](rsf.[Begin_Date])
      JOIN dbo.[REPORT_SVOD_TREE] rst2 ON rst.[Link] = rst2.[Link_Self]                                   
      JOIN dbo.[REPORT_SVOD_TREE] rst3 ON rst2.[Link] = rst3.[Link_Self]
      join dbo.[DICTIONARY_DEPARTMENT] d ON d.[LINK] = rst3.[LINK_REPORT_ORG]
WHERE rsf.[Link_Saved_Form] = @link_sf

SELECT @iLinkOrgFoms = link_org  
FROM dbo.[RO_SVOD_TREE] rst 
WHERE rst.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](@period_date)
   AND link_report_budg = (SELECT link FROM dbo.kl_budg_type WHERE code = 'ТГ')
   AND TYPE = 1    

if @iLinkOrgFoms is NULL
   SELECT @iLinkOrgFoms = link_org  
   FROM dbo.[RO_SVOD_TREE] rst
   WHERE rst.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](@period_date)
      AND link_report_budg = (SELECT link FROM dbo.kl_budg_type WHERE code = 'ВФ')
      AND TYPE = 1    

IF @iLinkOrgFoms = @org_link -- значит проверка из ФФОМС:
BEGIN
   SET @fo_grbs = 2
END
       

SELECT top 1 @link_f_425 = rf.[Link_Form]
FROM dbo.[REPORT_FORMS] rf
WHERE rf.code = '425' + REPLACE(REPLACE(@vcCodeForm, '425', ''), '0503125', '') AND YEAR(rf.[Start_Date]) = (SELECT YEAR(rf2.[Start_Date]) FROM dbo.[REPORT_FORMS] rf2 WHERE rf2.[Link_Form] = @link_f)
ORDER BY rf.[Start_Date] DESC 
 
                           
SELECT top 1 @link_f_125 = rf.[Link_Form]
FROM dbo.[REPORT_FORMS] rf
WHERE rf.code = '0503125' + REPLACE(REPLACE(@vcCodeForm, '425', ''), '0503125', '') AND YEAR(rf.[Start_Date]) = (SELECT YEAR(rf2.[Start_Date]) FROM dbo.[REPORT_FORMS] rf2 WHERE rf2.[Link_Form] = @link_f)  
ORDER BY rf.[Start_Date] DESC 
 
 
DECLARE @t_col_corr TABLE (lc INT, lt INT )

INSERT @t_col_corr (lc, lt)
SELECT link_col, rc.link_table
FROM dbo.[REPORT_COLOUMNS] rc
   JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] 
   JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form] AND rf.link_form IN (@link_f_125, @link_f_425)
WHERE (rt.orders IN (1,3) AND rc.orders = 10) OR (rt.[Orders] = 2 AND rc.[Orders] = 12)

if @link_sf is null begin
	select @nomErr=MAX(ORDERS) FROM #res 
	insert #Res(orders, res, cdoc, ctable,cCol,cValue,ckod)	
	select @nomErr+1,'-','Проверка отменена! Не найден сохраненный отчёт по ф.0503125 или ф.425','','','',''
   RETURN
end

----
-- заполняем таблицу #report (отчёт) текущего отчёта
set @j = 0
set @table = 1
while @table !> 3 begin
	select @iLink_Table = link_table from dbo.report_tables where link_form = @link_f and Orders = @table
	if @table in (1,3) begin
		insert into #report (ppp, okato, el_budg, code_acc, summa_dt, summa_kt, korr_acc)
		select 
			substring(coalesce(rd2.Str_Val,''),1,3),
			substring(coalesce(rd3.Str_Val,''),1,11),
			substring(coalesce(rd4.Str_Val,''),1,2),
			@ksbu,
			isnull(rd7.Float_Val,0.00),
			isnull(rd8.Float_Val,0.00),
			substring(coalesce(rd9.Str_Val,''),1,9)
		from (
				select Code_Row from dbo.report_dinamics_all
				where link_sf = @link_sf 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 dbo.report_dinamics_all as rd1 on rd1.link_sf = @link_sf 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 dbo.report_dinamics_all as rd2 on rd2.link_sf = @link_sf 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 dbo.report_dinamics_all as rd3 on rd3.link_sf = @link_sf 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 dbo.report_dinamics_all as rd4 on rd4.link_sf = @link_sf 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 dbo.report_dinamics_all as rd5 on rd5.link_sf = @link_sf 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 dbo.report_dinamics_all as rd6 on rd6.link_sf = @link_sf 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 dbo.report_dinamics_all as rd7 on rd7.link_sf = @link_sf 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 dbo.report_dinamics_all as rd8 on rd8.link_sf = @link_sf 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 dbo.report_dinamics_all as rd9 on rd9.link_sf = @link_sf 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 dbo.report_dinamics_all as rd10 on rd10.link_sf = @link_sf 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)
	end
	else begin
		insert into #report (ppp, okato, el_budg, code_acc, summa_dt, summa_kt, korr_acc)
		select 
			substring(coalesce(rd2.Str_Val,''),1,3),
			substring(coalesce(rd3.Str_Val,''),1,11),
			substring(coalesce(rd4.Str_Val,''),1,2),
			@ksbu,
			isnull(rd9.Float_Val,0.00),
			isnull(rd10.Float_Val,0.00),
			substring(coalesce(rd11.Str_Val,''),1,9)			
		from (
				select Code_Row from dbo.report_dinamics_all
				where link_sf = @link_sf 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 dbo.report_dinamics_all as rd1 on rd1.link_sf = @link_sf 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 dbo.report_dinamics_all as rd2 on rd2.link_sf = @link_sf 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 dbo.report_dinamics_all as rd3 on rd3.link_sf = @link_sf 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 dbo.report_dinamics_all as rd4 on rd4.link_sf = @link_sf 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 dbo.report_dinamics_all as rd5 on rd5.link_sf = @link_sf 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 dbo.report_dinamics_all as rd6 on rd6.link_sf = @link_sf 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 dbo.report_dinamics_all as rd7 on rd7.link_sf = @link_sf 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 dbo.report_dinamics_all as rd8 on rd8.link_sf = @link_sf 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 dbo.report_dinamics_all as rd9 on rd9.link_sf = @link_sf 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 dbo.report_dinamics_all as rd10 on rd10.link_sf = @link_sf 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 dbo.report_dinamics_all as rd11 on rd11.link_sf = @link_sf 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 dbo.report_dinamics_all as rd12 on rd12.link_sf = @link_sf and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12 and Link_Table = @iLink_Table)
	end
	set @table = @table + 1
END

--
--select * from #report
--
IF not exists(select * from #report) and @link_sf is not null begin
	select @nomErr=MAX(ORDERS) FROM #res 
	insert #Res(orders,res,cdoc,ctable,cCol,cValue,ckod)	
	select @nomErr+1,'-','Отсутствуют строки с данными отчёта по форме ' + @vcCodeForm + ' по КСБУ= '+@ksbu,'','','',''

	select @nomErr=MAX(ORDERS) FROM #res 
	insert #Res(orders, res, cdoc, ctable,cCol,cValue,ckod)	
	select @nomErr+1,'','','','','',''
end
--

INSERT #mdks_125 ([CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [PART],
         [GROUP_OKATO_ORG],
         [GROUP_OKATO_DATA],
         [FO_GRBS],
         [DT_KT],
         [IS_ABS])
SELECT   [CODE_RULE],
         [KSBU],
         [SIGN],
         [FILTER],
         [ORDER_TABLE],
         [iPART],
         [iGROUP_OKATO_ORG],
         [iGROUP_OKATO_DATA],
         [iFO_GRBS], -- 1 - ФО, 0 - ГРБС, 2 - ФОМС
         [iDT_KT],
         [iIS_ABS]
FROM dbo.[RO_MDKS_125] rm 
WHERE rm.[GROUP_MDKS] = @cGroupKS
   AND EXISTS(SELECT TOP 1 * FROM dbo.[RO_MDKS_125] rm1 WHERE rm1.[GROUP_MDKS] = @cGroupKS AND rm.[CODE_RULE] = rm1.[CODE_RULE] AND [KSBU] = @ksbu AND  [iFO_GRBS] = @fo_grbs)

UPDATE #mdks_125
SET [TYPE_RULE] = 1
WHERE [FO_GRBS] = 1
      AND NOT EXISTS(SELECT * FROM #mdks_125 M WHERE M.[CODE_RULE] = #mdks_125.[CODE_RULE] AND M.[FO_GRBS] <> 1)   

UPDATE #mdks_125
SET [TYPE_RULE] = 2
WHERE [FO_GRBS] = 0
      AND isnull(TYPE_RULE,0) = 0
      AND NOT EXISTS(SELECT * FROM #mdks_125 M WHERE M.[CODE_RULE] = #mdks_125.[CODE_RULE] AND M.[FO_GRBS] <> 0)
      

UPDATE #mdks_125
SET [TYPE_RULE] = 3
WHERE [FO_GRBS] IN (0,1)
      AND isnull(TYPE_RULE,0) = 0
      AND NOT EXISTS(SELECT * FROM #mdks_125 M WHERE M.[CODE_RULE] = #mdks_125.[CODE_RULE] AND M.[FO_GRBS] NOT IN  (0,1))   

UPDATE #mdks_125
SET [TYPE_RULE] = 4
WHERE [FO_GRBS] IN (1,2)
      AND isnull(TYPE_RULE,0) = 0
      AND NOT EXISTS(SELECT * FROM #mdks_125 M WHERE M.[CODE_RULE] = #mdks_125.[CODE_RULE] AND M.[FO_GRBS] NOT IN  (2,1))   

UPDATE #mdks_125
SET [TYPE_RULE] = 5
WHERE [FO_GRBS] IN (0, 2)
      AND isnull(TYPE_RULE,0) = 0
      AND NOT EXISTS(SELECT * FROM #mdks_125 M WHERE M.[CODE_RULE] = #mdks_125.[CODE_RULE] AND M.[FO_GRBS] NOT IN  (2,0))
      
UPDATE M
SET [FO_GRBS] = CASE WHEN [FO_GRBS] = 1 THEN 3 WHEN [FO_GRBS] = 0 THEN 4 ELSE -1 END 
FROM #mdks_125 M
WHERE NOT EXISTS(SELECT * FROM  #mdks_125 M1 WHERE M.[CODE_RULE] = M1.[CODE_RULE] AND m1.[FO_GRBS] <> @fo_grbs)
      AND part <> (SELECT TOP 1 M1.[PART]
                     FROM  #mdks_125 M1 WHERE M.[CODE_RULE] = M1.[CODE_RULE] AND m1.[ksbu] = @ksbu)

INSERT #mdks_125_filter (
         [KSBU],
         [SIGN],
         [ORDER_TABLE],
         [PART],
         [GROUP_OKATO_ORG],
         [GROUP_OKATO_DATA],
         [FO_GRBS],
         [DT_KT],
         [IS_ABS],
         [TYPE_RULE])
SELECT   [KSBU],
         [SIGN],
         [ORDER_TABLE],
         [PART],
         [GROUP_OKATO_ORG],
         [GROUP_OKATO_DATA],
         [FO_GRBS],
         [DT_KT],
         [IS_ABS],
         [TYPE_RULE]
FROM  #mdks_125
GROUP BY [KSBU],
         [SIGN],
         [ORDER_TABLE],
         [PART],
         [GROUP_OKATO_ORG],
         [GROUP_OKATO_DATA],
         [FO_GRBS],
         [DT_KT],
         [IS_ABS],
         [TYPE_RULE] 

UPDATE  M
SET I = F.I
FROM #mdks_125 M
      JOIN #mdks_125_filter F ON M.[KSBU] = F.[KSBU] AND
         M.[SIGN] = F.[SIGN] AND
         M.[ORDER_TABLE] = F.[ORDER_TABLE] AND
         M.[PART] = F.[PART] AND
         M.[GROUP_OKATO_ORG] = F.[GROUP_OKATO_ORG] AND
         M.[GROUP_OKATO_DATA] = F.[GROUP_OKATO_DATA] AND
         M.[FO_GRBS] = F.[FO_GRBS] AND
         M.[DT_KT] = F.[DT_KT] AND
         M.[IS_ABS] = F.[IS_ABS] AND
         M.[TYPE_RULE] = F.[TYPE_RULE]    
   
IF NOT EXISTS(SELECT TOP 1 * FROM #mdks_125) -- нет правил для данного КСБУ
   RETURN
   
insert into #report_org (ppp, okato, el_budg, summa_dt, summa_kt)
select ppp, left(ltrim(rtrim(okato))+'000',11), el_budg, sum(summa_dt), sum(summa_kt) 
from #report 
--where left(okato,5)<>'00000' 
group by okato, el_budg, ppp having len(okato)>0 OR len(ppp)>0 

IF not exists(select * from #report_org) and exists(select * from #report) and @link_sf is not null 
begin
   select @nomErr=MAX(ORDERS) FROM #res 
   insert #Res(orders,res,cdoc,ctable,cCol,cValue,ckod)	
   select @nomErr+1,'-','Отсутствуют строки с заполненой графой Глава по БК или ОКАТО, отчёта по форме ' + @vcCodeForm + ' по КСБУ= '+@ksbu,'','','',''

   select @nomErr=MAX(ORDERS) FROM #res 
   insert #Res(orders, res, cdoc, ctable, cCol, cValue, ckod)	
   select @nomErr+1, '', '', '', '', '', ''
END


insert into #report_org (ppp, okato, summa_dt, summa_kt) -- добавляем еще другие ГРБСы, в котором есть ссылка на данный ОКАТО и нет этих ГРБСов в данном отчете
select isnull(kab.code,''), '', 1, 1
from dbo.report_saved_forms as rsf
inner join dbo.departments as d
on rsf.link_organization = d.link
left join dbo.kl_admin_bs as kab
on d.ved_link = kab.link
where rsf.link_form = @link_f_125
AND rsf.del = 0
and rsf.period_type = @period_type
and rsf.period_number = @period_number
and rsf.begin_date = @period_date
/*	and ((rsf.atr_code like '%=' + rtrim(@ksbu_GRBS) + '%') or 
	   (@ksbu_FO = '120551560' and @ksbu_GRBS = '120551660' and rsf.atr_code like '%=120651660%')
	   or (@ksbu_FO = /*'120505660'*/'120551660' and @ksbu_GRBS = /*'120612560'*/'120651560' and rsf.atr_code like '%=130251830%')
	   or (@ksbu_FO = /*'120505660'*/'120551660' and @ksbu_GRBS = /*'130212830'*/'130251830' and rsf.atr_code like '%=120651560%'))*/
and dbo.RT_IS_GRBS(rsf.link_saved_form) = 1 -- грбс
and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
and d.type = 1 -- корреспондент
and isnull(kab.code,'') not in (select R.ppp from #report_org R)
and 1 = (select max([type]) from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
and rsf.Version = (select max(rsf1.Version) 
   from dbo.report_saved_forms as rsf1
   where rsf1.link_form = @link_f_125
   AND rsf1.del = 0
   and rsf1.period_type = @period_type
   and rsf1.period_number = @period_number
   and rsf1.begin_date = @period_date
   and rsf1.atr_code = rsf.atr_code
   and rsf.link_organization = rsf1.link_organization
   and isnull(rsf.link_type_svod, -1) = isnull(rsf1.link_type_svod, -1))
and exists(select top 1 * from dbo.report_dinamics_all RD where RD.link_sf = RSF.link_saved_form 
               and (CHARINDEX(',' + SUBSTRING(RD.Code_Row,4,5), @self_okato) > 0  OR @fo_grbs <> 1) 
               and (left(RD.Code_Row,3) = @self_ppp OR @fo_grbs <> 0)
               and float_val <> 0)
               
insert into #report_org (okato, ppp, summa_dt, summa_kt) -- добавляем еще другие ФО, в котором есть ссылка на данный ГРБС и нет этих ОКАТО в данном отчете
select replace(isnull(d.okato,''), ' ', ''), '',  1, 1
from dbo.report_saved_forms as rsf
inner join dbo.departments as d
on rsf.link_organization = d.link
where rsf.link_form in (@link_f_425, @link_f_125)
AND rsf.del = 0
and rsf.period_type = @period_type
and rsf.period_number = @period_number
and rsf.begin_date = @period_date
--	and (rsf.atr_code like '%=' + rtrim(@ksbu_FO) + '%')
and dbo.RT_IS_GRBS(rsf.link_saved_form) = 0 -- фо
and rsf.link_type_svod not in (isnull((select link from kl_budg_type where code = 'СБ'),-1),isnull((select link from kl_budg_type where code = 'СП'),-1))
and left(ltrim(replace(d.okato,' ',''))+'           ',11) not in ( select R.okato from #report_org R)
and (len(d.okato)>0 or @okato is null)
and 1 = (select max([type]) from dbo.report_svod_tree where link_report_org = rsf.link_organization and link_report_budg = rsf.link_type_svod and link_history = (select max(link_history) from dbo.report_svod_tree))
and rsf.Version = (select max(rsf1.Version) 
	from dbo.report_saved_forms as rsf1
	where rsf1.link_form in (@link_f_425, @link_f_125)
   AND rsf1.del = 0
	and rsf1.period_type = @period_type
	and rsf1.period_number = @period_number
	and rsf1.begin_date = @period_date
	and rsf1.atr_code = rsf.atr_code
	and rsf.link_organization = rsf1.link_organization
	and isnull(rsf.link_type_svod, -1) = isnull(rsf1.link_type_svod, -1)
)
and exists(select top 1 * from dbo.report_dinamics_all RD where RD.link_sf = RSF.link_saved_form 
                and (CHARINDEX(',' + SUBSTRING(RD.Code_Row,4,5), @self_okato) > 0 OR @fo_grbs <> 1) 
               and (left(RD.Code_Row,3) = @self_ppp OR @fo_grbs <> 0)
 and float_val <> 0)
 
set @vcmask = isnull((SELECT Val_str FROM dbo.report_options WHERE razdel = 'Form_125' AND Code = 'Mask'), 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')                                                                                                                                                                                                                 
IF @vcmask = ''
   SET @vcMask =  'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
   

while exists(select * from #report_org) -- движемся по строчкам текущего отчёта 
begin 
   select top 1 @nn = nn, @ppp = rtrim(ppp), @okato = okato,  @okato_org =  LEFT(okato,5) + '000000',  @summa_dt = summa_dt, @summa_kt = summa_kt from #report_org order by ppp, okato

   
     INSERT #summand_reports_125  (
                        [PART],
                        [LSF],
                        [ORDER_TABLE],
                        [DT_KT],
                        [GROUP_OKATO_DATA],
                        [GROUP_OKATO_ORG],
                        [FO_GRBS],
                        [SIGN],
                        [PPP],
                        [OKATO],
                        [IS_ABS],
                        [i],
                        [GROUP_CODE],
                        [TYPE_RULE])
    SELECT  M.[PART],
            CASE WHEN [FO_GRBS] = @fo_grbs AND [KSBU] = @ksbu THEN @link_sf
                  WHEN [FO_GRBS] = @fo_grbs THEN dbo.[RT_GET_LSF](   @link_f /*@link_f*/,
			                                                            @period_type /*@period_type*/,
			                                                            @period_number /*@period_number*/,
			                                                            @period_date /*@period_date*/,
			                                                            /*'120505660'*/ [ksbu] /*@ksbu*/,
			                                                            null/*@is_grbs*/,
			                                                            null /*@org_type*/,
			                                                            null /*@ppp*/,
			                                                            null /*@okato*/,
			                                                            @org_link)
                   WHEN  [FO_GRBS] IN (0,4) THEN  dbo.[RT_GET_LSF]( @link_f_125 /*@link_f*/,
                                                                           @period_type /*@period_type*/,
                                                                           @period_number /*@period_number*/,
                                                                           @period_date /*@period_date*/,
                                                                           [KSBU] /*@ksbu*/,
                                                                           1 /*@is_grbs*/,
                                                                           1 /*@org_type*/,
                                                                           @ppp /*@ppp*/,
                                                                           null /*@okato*/,
                                                                           null /*@org_link*/)  
                           WHEN  [FO_GRBS] IN (1,3) THEN  CASE WHEN [GROUP_OKATO_ORG] = 1 
                                                                        THEN dbo.[RT_GET_LSF1]( @link_f_425 /*@link_f*/,
			                                                                        @period_type /*@period_type*/,
			                                                                        @period_number /*@period_number*/,
			                                                                        @period_date /*@period_date*/,
			                                                                        [KSBU] /*@ksbu*/,
			                                                                        0 /*@is_grbs*/,
			                                                                        null /*@org_type*/,
			                                                                        null /*@ppp*/,
			                                                                        @okato_org /*@okato*/,
			                                                                        null,
			                                                                        @el_budg)
                                                                         ELSE dbo.[RT_GET_LSF1]( @link_f_425 /*@link_f*/,
			                                                                        @period_type /*@period_type*/,
			                                                                        @period_number /*@period_number*/,
			                                                                        @period_date /*@period_date*/,
			                                                                        [KSBU] /*@ksbu*/,
			                                                                        0 /*@is_grbs*/,
			                                                                        null /*@org_type*/,
			                                                                        null /*@ppp*/,
			                                                                        @okato /*@okato*/,
			                                                                        null,
			                                                                        @el_budg) END
                     WHEN [FO_GRBS] = 2 THEN dbo.[RT_GET_LSF](   @link_f_425 /*@link_f*/,
	                                                            @period_type /*@period_type*/,
	                                                            @period_number /*@period_number*/,
	                                                            @period_date /*@period_date*/,
	                                                            /*'120505660'*/ [ksbu] /*@ksbu*/,
	                                                            null /*@is_grbs*/,
	                                                            null /*@org_type*/,
	                                                            null /*@ppp*/,
	                                                            null /*@okato*/,
	                                                            @iLinkOrgFoms) END,
            [ORDER_TABLE],
            [DT_KT],
            [GROUP_OKATO_DATA],
            [GROUP_OKATO_ORG],
            [FO_GRBS],
            [SIGN],
            CASE WHEN [FO_GRBS] = @fo_grbs THEN '' ELSE @ppp END,
            CASE WHEN [FO_GRBS] = @fo_grbs THEN '' ELSE CASE WHEN [GROUP_OKATO_ORG] = 1 THEN left(@okato, 5) + '000000'  ELSE @okato END  END,
            [IS_ABS],
            I,
            CASE WHEN FO_GRBS <> @fo_grbs THEN  CASE WHEN [FO_GRBS] IN (1,3) THEN CASE WHEN [GROUP_OKATO_ORG] = 1 THEN left(@okato, 5) + '______'  ELSE RTRIM(@okato) END WHEN [FO_GRBS] IN (0, 4) THEN @ppp ELSE '' END ELSE '' END,
            [TYPE_RULE]                    
    FROM #mdks_125_filter M

--    UPDATE M
--    SET GROUP_CODE =   
--    FROM #summand_reports_125 M
--    WHERE FO_GRBS <> @fo_grbs
    
    UPDATE M
    SET GROUP_CODE = RTRIM(M1.[GROUP_CODE])   
    FROM #summand_reports_125 M JOIN #summand_reports_125 M1 ON M1.[TYPE_RULE] = M.[TYPE_RULE]
    WHERE isnull(M.GROUP_CODE, '') = '' AND isnull(M1.GROUP_CODE, '') <> ''
    
    DELETE #summand_reports_125 WHERE [TYPE_RULE] IN (SELECT [TYPE_RULE] FROM #summand_reports_125 WHERE isnull(GROUP_CODE, '') = '' AND FO_GRBS <> @fo_grbs )
         AND  [TYPE_RULE] NOT IN (SELECT [TYPE_RULE] FROM #summand_reports_125 WHERE fo_grbs = 2 AND FO_GRBS <> @fo_grbs )
    
   UPDATE #summand_reports_125
    SET GROUP_CODE = ISNULL(GROUP_CODE, '')
    
      INSERT #report_dinamics_125 (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
       SELECT rda.Link_SF, rda.Link_Col, rda.Code_Row, Float_Val, Str_Val
       FROM dbo.[report_dinamics_all] rda
         JOIN (SELECT distinct LSF FROM #summand_reports_125) r ON r.LSF = RDA.LINK_SF
         JOIN dbo.[REPORT_COLOUMNS] rc ON rc.[LINK_COL] = rda.[LINK_COL]
         JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] 
       WHERE --rda.link_sf IN (SELECT distinct LSF FROM #summand_reports_125)
          NOT EXISTS(SELECT * FROM #report_dinamics_125 rda1 WHERE rda.link_sf = rda1.link_sf)     
         AND ((rc.[Orders] IN (7, 8, 10) AND rt.orders IN (1,3)) OR (rc.[Orders] IN (9 , 10, 12) AND rt.orders IN (2)))

--    IF @@ROWCOUNT > 0
--    BEGIN 
--       INSERT #report_dinamics_125 (Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
--       SELECT Link_SF, Link_Col, Code_Row, Float_Val, Str_Val
--       FROM dbo.[report_dinamics_all] rda JOIN  @t_col_corr t ON RDA.[LINK_COL] = t.[lc]
--            JOIN (SELECT distinct LSF FROM #summand_reports_125) r ON r.LSF = RDA.Link_SF 
--       WHERE NOT EXISTS(SELECT * FROM #report_dinamics_125 rda1 JOIN  @t_col_corr t ON RDA.[LINK_COL] = t.[lc] WHERE rda.link_sf = rda1.link_sf )
--       
--       
--       
--    END

  INSERT #summand_125([CODE_RULE],
                        [PART],
                        [LSF],
                        [ORDER_TABLE],
                        [DT_KT], -- 1 - дебет, 0 - кредит
                        [CODE],
                        [CODE_ROW],
                        [SIGN],
                        [VALUE],
                        [PPP],
                        [OKATO],
                        [FO_GRBS],
                        [FILTER],
                        [IS_ABS],
                        [TYPE],
                        [I])
    SELECT DISTINCT R.[CODE_RULE],
           R.[PART],
           R.[LSF],
           R.[ORDER_TABLE],
           R.[DT_KT],
           MAX(CASE WHEN [GROUP_OKATO_DATA] = 0 THEN [GROUP_CODE]
                  ELSE
                    CASE WHEN LEN([GROUP_CODE]) = 3 THEN  RTRIM([GROUP_CODE]) ELSE '' END  + SUBSTRING(D.[CODE_ROW],4,11)
                     
           END),
           D.[CODE_ROW],--dbo.RA_MASK(D.[CODE_ROW], @vcMask),
           R.[SIGN],
           [VALUE] = CASE WHEN R.[IS_ABS] = 1 THEN
                              CASE WHEN (R.[SIGN] = '+' AND R.[DT_KT] = 1)  
                              THEN ABS(SUM(CASE WHEN C.orders IN (7,9) THEN D.[FLOAT_VAL] ELSE -D.[FLOAT_VAL] END))
                              WHEN (R.[SIGN] = '+' AND R.[DT_KT] = 0)
                              THEN ABS(SUM(CASE WHEN C.orders IN (7,9) THEN -D.[FLOAT_VAL] ELSE +D.[FLOAT_VAL] END))
                              WHEN (R.[SIGN] = '-' AND R.[DT_KT] = 1)                                                                        
                              THEN -ABS(SUM(CASE WHEN C.orders IN (7,9) THEN D.[FLOAT_VAL] ELSE -D.[FLOAT_VAL] END))
                              WHEN (R.[SIGN] = '-' AND R.[DT_KT] = 0)                                                                        
                              THEN -ABS(SUM(CASE WHEN C.orders IN (7,9) THEN -D.[FLOAT_VAL] ELSE D.[FLOAT_VAL] END)) END                    
                     ELSE     CASE WHEN (R.[SIGN] = '+' AND R.[DT_KT] = 1) OR (R.[SIGN] = '-' AND R.[DT_KT] = 0) 
                              THEN SUM(CASE WHEN C.orders IN (7,9) THEN D.[FLOAT_VAL] ELSE -D.[FLOAT_VAL] END)
                              ELSE -SUM(CASE WHEN C.orders IN (7,9) THEN D.[FLOAT_VAL] ELSE -D.[FLOAT_VAL] END) END END,
           R.[PPP],
           R.[OKATO],
           R.[FO_GRBS],
           R.[FILTER],
           R.[IS_ABS],
           ISNULL(RDT.Str_val,'') ,
           R.[I]
    FROM #summand_reports_125 R
         LEFT JOIN dbo.#report_dinamics_125 D ON R.[LSF] = D.[LINK_SF]
         JOIN dbo.report_coloumns C ON C.[LINK_COL] = D.[LINK_COL] AND C.[Col_Type] = 0
         JOIN dbo.[REPORT_TABLES] T ON T.[Link_Table] = C.[Link_Table] AND T.[Orders] = R.[ORDER_TABLE]
         join dbo.report_coloumns Ct on Ct.[link_table] = T.[link_table] and ((CT.orders = 10 and T.orders in(1,3)) or (CT.orders = 12 and T.orders =2))
         left join dbo.#report_dinamics_125 rdt on rdt.link_sf = d.link_sf and rdt.link_col = ct.link_col and rdt.code_row = d.code_row
         LEFT JOIN #summand_125 RES ON RES.[I] = R.[I] AND RES.[PART] = R.[PART] AND ISNULL(RES.[LSF], 0) =   ISNULL(R.[LSF], 0)
                           AND RES.[CODE_ROW] = D.[CODE_ROW] /*dbo.RA_MASK(D.[CODE_ROW], @vcMask)*/ AND RES.[FO_GRBS] = R.[FO_GRBS]                         
    WHERE RES.I IS NULL AND ( (([GROUP_OKATO_DATA] = 0 
               AND ((LEFT(D.[CODE_ROW],14) like CASE WHEN R.FO_GRBS = @FO_GRBS 
                                                   THEN RTRIM([GROUP_CODE]) + SUBSTRING(D.CODE_ROW,4,11) 
                                                   ELSE case when R.fo_grbs =4 THEN @self_ppp ELSE  LEFT(D.Code_Row,3)  end
                                                               + CASE WHEN @fo_grbs = 2 OR R.fo_grbs = 4
                                                                       THEN SUBSTRING(D.Code_Row,4,11) 
                                                                       ELSE  CASE WHEN [GROUP_OKATO_ORG] = 1 THEN SUBSTRING(@self_okato, 2,5) + '______' ELSE dbo.RA_GETWORDNUM(@self_okato,2,',') END END   END
                                AND LEN([GROUP_CODE]) = 3) -- группировачный код ппп
                     OR (LEFT(D.[CODE_ROW],14) like CASE WHEN R.FO_GRBS = @FO_GRBS 
                                                      THEN LEFT(D.[CODE_ROW],3) +  [GROUP_CODE]
                                                      ELSE case when @fo_grbs = 2  OR R.fo_grbs = 3
                                                            THEN LEFT(D.[CODE_ROW],3) 
                                                            ELSE RTRIM(@self_ppp) END + case when R.fo_grbs =3 THEN CASE WHEN [GROUP_OKATO_ORG] = 1 THEN SUBSTRING(@self_okato, 2, 5) + '______' ELSE dbo.RA_GETWORDNUM(@self_okato,2,',') END ELSE SUBSTRING(D.[CODE_ROW],4,11) END END 
                                 AND LEN([GROUP_CODE]) > 3) -- группировачный код окато
                     OR (LEFT(D.[CODE_ROW],14) = CASE WHEN R.FO_GRBS = @FO_GRBS 
                                                      THEN LEFT(D.[CODE_ROW],14)
                                                      ELSE case when @fo_grbs = 1 
                                                            THEN LEFT(D.[CODE_ROW],3) + dbo.RA_GETWORDNUM(@self_okato,2,',') 
                                                            ELSE RTRIM(@self_ppp) + SUBSTRING(D.[CODE_ROW],4,11) END  END 
                                 AND LEN([GROUP_CODE]) = 0))) -- группировачный кода нет
         OR ([GROUP_OKATO_DATA] = 1 
               AND ((((CHARINDEX(',' + CASE WHEN [GROUP_OKATO_ORG] = 1 THEN  SUBSTRING(D.[CODE_ROW], 4, 5) ELSE  SUBSTRING(D.[CODE_ROW], 4, 11) END ,
                     
                      @self_okato) >0 AND  R.FO_GRBS <> @FO_GRBS AND R.fo_grbs not in (2,4))
                     OR (R.FO_GRBS = @FO_GRBS AND LEFT(D.Code_Row,3) = [GROUP_CODE]) 
                     OR (R.FO_GRBS = 4 AND LEFT(D.Code_Row,3) = @self_ppp))
                      
                                 AND LEN([GROUP_CODE]) = 3) 
                       OR (LEFT(D.[CODE_ROW],14) like CASE WHEN R.FO_GRBS = @FO_GRBS 
                                                         THEN LEFT(D.[CODE_ROW],14)-- + [GROUP_CODE]
                                                      ELSE case when @fo_grbs = 2  OR R.fo_grbs = 3
                                                            THEN LEFT(D.[CODE_ROW],3) 
                                                            ELSE RTRIM(@self_ppp) END + case when R.fo_grbs =3 THEN CASE WHEN [GROUP_OKATO_ORG] = 1 THEN SUBSTRING(@self_okato, 2, 5) + '______' ELSE dbo.RA_GETWORDNUM(@self_okato,2,',') END ELSE SUBSTRING(D.[CODE_ROW],4,11) END END 
                                AND LEN([GROUP_CODE]) > 3 )
                     OR (LEFT(D.[CODE_ROW],14) = CASE WHEN R.FO_GRBS = @FO_GRBS 
                                                      THEN LEFT(D.[CODE_ROW],3) + @okato
                                                      ELSE case when @fo_grbs = 1 
                                                            THEN LEFT(D.[CODE_ROW],3) + @okato 
                                                            ELSE RTRIM(@self_ppp) + @okato END  END 
                                 AND LEN([GROUP_CODE]) = 0)))))
--      AND NOT EXISTS (SELECT * FROM #summand_125 RES WHERE RES.[I] = R.[I] AND RES.[PART] = R.[PART] AND ISNULL(RES.[LSF], 0) =   ISNULL(R.[LSF], 0)
--                           AND RES.[CODE_ROW] = dbo.RA_MASK(D.[CODE_ROW], @vcMask) AND RES.[FO_GRBS] = R.[FO_GRBS])                              
    GROUP BY R.[CODE_RULE],
           R.[PART],
           R.[LSF],
           R.[ORDER_TABLE],
           R.[DT_KT],
           R.[SIGN],
           D.[CODE_ROW],
           --dbo.RA_MASK(D.[CODE_ROW], @vcMask),
           R.[PPP],
           R.[OKATO],
           R.[FO_GRBS],
           R.[FILTER],
           R.[IS_ABS],
           ISNULL(RDT.Str_val,''),
           R.I

             
    TRUNCATE TABLE #summand_reports_125
   delete from #report_org where nn = @nn
END

----------------
-- ПРИМЕНЕНИЕ ФИЛЬТРА
DECLARE CUR_FILTER CURSOR LOCAL STATIC FOR 
SELECT FILTER, I, MAX(CODE_RULE) CODE_RULE FROM #mdks_125 
WHERE ISNULL(FILTER, '') <> '' 
GROUP BY FILTER, I

OPEN CUR_FILTER
FETCH NEXT FROM CUR_FILTER INTO @cFilter, @i, @cCODE_RULE
WHILE @@FETCH_STATUS = 0
BEGIN
   SET @cExecStr = 'insert  #summand_125 ([CODE_RULE],
                        [PART],
                        [LSF],
                        [ORDER_TABLE],
                        [DT_KT], -- 1 - дебет, 0 - кредит
                        [CODE],
                        [CODE_ROW],
                        [SIGN],
                        [VALUE],
                        [PPP],
                        [OKATO],
                        [FO_GRBS],
                        [FILTER],
                        [IS_ABS],
                        [TYPE])
                    select ''' +@cCODE_RULE + ''',
                        [PART],
                        [LSF],
                        [ORDER_TABLE],
                        [DT_KT], -- 1 - дебет, 0 - кредит
                        [CODE],
                        dbo.RA_MASK([CODE_ROW],''' + @vcMask + '''),
                        [SIGN],
                        sum([VALUE]),
                        [PPP],
                        [OKATO],
                        [FO_GRBS],
                        '''',
                        [IS_ABS],
                        [TYPE]
                    from #summand_125
                    where i = ' + STR(@i) + ' and (' + @cFilter + ')
                    group by [PART],[LSF],[ORDER_TABLE],[DT_KT],[CODE],dbo.RA_MASK([CODE_ROW],''' + @vcMask + '''),[SIGN],[PPP],[OKATO],[FO_GRBS],[IS_ABS],[TYPE]'
                    
   EXECUTE (@cExecStr)
   FETCH NEXT FROM CUR_FILTER INTO @cFilter, @i, @cCODE_RULE
END
CLOSE CUR_FILTER
DEALLOCATE CUR_FILTER

DELETE #summand_125 WHERE isnull(code_rule,'') = ''



----------------
-- ФОРМИРОВАНИЕ ПРОТОКОЛА
INSERT #Result_125 ([CODE_RULE],
                    [CODE],
                    [PART],
                    [VALUE])
SELECT [CODE_RULE],
        [CODE],
        [PART],
        SUM([VALUE]) 
FROM #summand_125
GROUP BY [CODE_RULE],
         [CODE],
         [PART]     
         
INSERT #Result_sr_125 ([CODE_RULE],
                    [CODE],
                    [LEFT_VALUE],
                    [RIGHT_VALUE])
SELECT ISNULL(L.[CODE_RULE], R.[CODE_RULE]),
        ISNULL(L.[CODE],R.[CODE]),
        ISNULL(L.[VALUE], 0),
        ISNULL(R.[VALUE], 0) 
FROM (select * from #Result_125 WHERE part = 1) L 
      FULL JOIN 
      (select * from #Result_125 WHERE part <> 1) R ON L.[CODE_RULE] = R.[CODE_RULE] AND R.[CODE] = L.[CODE]
WHERE abs(ISNULL(L.[VALUE], 0) - ISNULL(R.[VALUE], 0)) > 0.001

-- чтобы не было дублирующих ошибок:
DELETE #Result_sr_125
WHERE EXISTS(SELECT TOP 1 * FROM #t_MDKS_PROC b WHERE b.[CODE] = '125' AND b.[TXT] = RTRIM(#Result_sr_125.[CODE_RULE]) + '#' + #Result_sr_125.[CODE])


INSERT  #t_MDKS_PROC ([CODE], [TXT])
SELECT '125', RTRIM([CODE_RULE]) + '#' + [CODE]
FROM #Result_sr_125

-- для ускорения протокола
declare @t table (orders int)
	insert @t values(1)
	insert @t values(3)
	insert @t values(6)
	insert @t values(7)
	insert @t values(8)

   
insert #Res (orders, res, cDoc, cPeriod, cBudg, cKod, cTable, cCol, cValue)
select orders, isnull(res,''), isnull(cDoc,''), cPeriod, cBudg, isnull(cKod,''), isnull(cTable,''), isnull(cCol, ''), isnull(cValue, '') from
(select orders, case orders when 1 then '№' + [CODE_RULE] else '' end as Res,
	case orders when 1 then dbo.RO_CHECK_KS_OUTSIDE_MDKS_125_STR(@cGroupKS, S.[CODE_RULE]) when 6 then 'Результат слева' when 7 then 'Результат справа' when 8 then 'Отклонение' else '' end as cDoc, case orders when 1 then 'Группа: ' + isnull(@cGroupKS, '') else '' end as cPeriod, '' as cBudg,
	 case orders when 1 then '' when 3 then '=' else '' end as cKod, '' as cTable, '' as cCol, case orders when 6 then ltrim(dbo.[rn_convert_number]([LEFT_VALUE],2,' ')) when 7 then ltrim(dbo.[rn_convert_number]([RIGHT_VALUE],2,' ')) when 8 then '<font color="#ff0000">' + ltrim(dbo.[rn_convert_number]([LEFT_VALUE]-[RIGHT_VALUE],2, ' ')) else '' end as cValue, [CODE], [CODE_RULE], '' as OrderRow
from #Result_sr_125 S left join @t on 1 = 1
union all
select 2 + (1-part) * 2, '', isnull(rf.Code, '') + ' ' + RSF.[atr] + CASE WHEN S.[FO_GRBS] <> @fo_grbs THEN ' Организация: ' + dbo.GetDepName(rsf.[Link_Organization], rsf.[Begin_Date]) + CASE WHEN S.[FO_GRBS] IN (1,3) THEN ' ОКАТО: ' + isnull(S.[OKATO],'') WHEN S.[FO_GRBS] IN (0,4) THEN  ' ППП: ' + isnull(S.[PPP], '') ELSE '' END ELSE '' END,
       '' AS cPeriod, isnull(kbt.[Name],''), 
      [sign] + CASE WHEN S.[IS_ABS] = 1 THEN '|' ELSE '' END 
      + CASE WHEN LEN(S.Code_Row) > 50 THEN S.Code_Row ELSE 
               CASE WHEN LEFT(S.Code_Row,3) = '000' THEN '' ELSE 'ППП: ' + LEFT(S.Code_Row,3) END  + 
               CASE WHEN SUBSTRING(S.Code_Row,4, 11) = '0000000000' THEN '' ELSE ' ОКАТО: ' + SUBSTRING(S.Code_Row,4, 11) END  + 
               CASE WHEN SUBSTRING(S.Code_Row, 15, 2) = '00' THEN '' ELSE ' Элемент: ' + SUBSTRING(S.Code_Row, 15, 2) END + 
               CASE WHEN SUBSTRING(S.Code_Row, 17, 3) = '000' THEN '' ELSE ' АДМ: ' + SUBSTRING(S.Code_Row, 17, 3) END + 
               CASE WHEN SUBSTRING(S.Code_Row, 20, 14) = '00000000000000' THEN '' ELSE   ' КБК: ' + SUBSTRING(S.Code_Row, 20, 14) END + 
               CASE WHEN SUBSTRING(S.Code_Row, 34, 9) = '00000000' THEN '' ELSE ' Корр.счет: ' + SUBSTRING(S.Code_Row, 34, 9)  END END
           + CASE WHEN S.[IS_ABS] = 1 THEN '|' ELSE '' END ,  
      '№' + LTRIM(STR([ORDER_TABLE])), CASE WHEN S.[DT_KT] = 1 THEN 'Дебет' ELSE 'Кредит' END, ltrim(dbo.[rn_convert_number](S.[VALUE], 2, ' ')),  S.[CODE], S.[CODE_RULE], LTRIM(STR([PART])) 
from #summand_125 S inner join #Result_sr_125 R on S.[CODE_RULE] = R.[CODE_RULE] and isnull(S.[CODE], '') = isnull(R.[CODE], '') 
   left join dbo.report_saved_forms RSF ON RSF.[Link_Saved_Form] = S.[LSF]
   LEFT JOIN dbo.report_forms RF ON RF.[Link_Form] = RSF.[Link_Form]
   LEFT JOIN dbo.[KL_BUDG_TYPE] kbt ON kbt.[Link] = RSF.[Link_Type_Svod]) A
order by [CODE_RULE], [CODE], orders, OrderRow


select 0 

EXEC dbo.DropTempTable '#report_dinamics_125'

EXEC dbo.DropTempTable '#mdks_125'

EXEC dbo.DropTempTable '#mdks_125_filter'
                        
EXEC dbo.DropTempTable '#summand_reports_125'

EXEC dbo.DropTempTable '#summand_125'

EXEC dbo.DropTempTable '#Result_125'                             

EXEC dbo.DropTempTable '#Result_sr_125'
 
GO
GRANT EXECUTE ON [dbo].[RO_CHECK_KS_OUTSIDE_125] 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.[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_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)
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(20))

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_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 dbo.REPORT_CALC C 
INNER JOIN @t_Col RC on RC.Link_Col = C.Link_Col
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)
--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 dbo.report_calc C 
INNER join @t_Col RC on RC.Link_Col = C.Link_Col
INNER join dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 

/*	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
from dbo.report_calc C 
join @t_Col RC on RC.Link_Col = C.Link_Col
join dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or 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, 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 dbo.report_calc C 
join @t_Col RC on RC.Link_Col = C.Link_Col
join dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or 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)
--- Удаление лишних корреспонденций ---

----------------------------------------------------------------------
-- РАССЧИТЫВАЕМ
-- CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
---------------- проводки ----------------------------
insert #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
SELECT 
CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6)
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '') + '000', 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	SUM(CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END), 
--CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END,
	TMP.Calc_Order

--g.*

FROM dbo.G_PROV G
INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK
	AND DT.DB_KR = 0)
LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK
	AND KT.DB_KR = 1)

LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
LEFT JOIN dbo.KOSGU DTE ON (DTE.Link = DT.EKR)
LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
LEFT JOIN dbo.KOSGU KTE ON (KTE.Link = KT.EKR)

INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
		AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 0)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 0)

LEFT JOIN dbo.S_ACCOUNTS SA ON (TMP.DT_KT = 0 AND SA.LINK = DT.ACCOUNT
	OR TMP.DT_KT = 1 AND SA.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK
		OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
LEFT JOIN @filter_kbk F on KBK.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
WHERE G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
--and tmp.link_col = 57755
	--and tmp.Code_Row = '162'
	AND G.DEP = @iDEP_LINK
	AND (F.kbk IS NOT NULL
		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link
				and xor.link_dt = dt.account and xor.link_kt = kt.account
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 0)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 0))

GROUP BY CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '') + '000', 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	TMP.Calc_Order

----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на начало периода
	INSERT #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
	SELECT 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		@LC,
		SUM(CASE
			WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				THEN  k_summa - d_summa
			ELSE d_summa - k_summa END),
		R.Calc_Order
	FROM dbo.ARestTableByDateAccounts(@ldBegin, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = A.account and R.Link_Col = @LC and R.[Type] = 2
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	GROUP BY 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3)
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		R.Calc_Order

	-- остаток на конец периода
	insert #tTemp(KBK, Link_Col, SUMMA, Calc_Order)
	select 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		@LC,
	        sum(case
			when (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),
		R.Calc_Order
	from dbo.ARestTableByDateAccounts(@ldEnd, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19  
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')

/*		join @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
		left join dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end)>0)
		LEFT JOIN @filter_kbk F on F.kbk = K.Code 
		left join dbo.KOSGU S on (S.Link = A.EKR)  -- and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		left join dbo.KOSGU E on E.Link = A.EKR
		left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0 or R1.ekr =''))
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
*/	group by 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3)
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		R.Code_Row, R.Calc_Order

-- 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.[SD_VAC_CHILD_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_VAC_CHILD_FILL]

GO


CREATE  PROCEDURE dbo.SD_VAC_CHILD_FILL
/*Расчет по уходу за ребенком*/
@varKSnMonth int,
@varKSnYear int
AS

DECLARE @varKSDateS DATETIME
SET @varKSDateS = dbo.ConvertDMY2Date(1,@varKSnMonth,@varKSnYear)

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @DATE_BEG DATETIME, @DATE_END DATETIME
SET @DATE_BEG = dbo.DateBeginOfMonth(@varKSDateS)
SET @DATE_END = dbo.DateEndOfMonth(@varKSDateS)

CREATE TABLE #EMPL (LINK INT, LINK_EMPL INT, SYST_PAY TINYINT, SUBDIV_NAME VARCHAR(254), POST_NAME VARCHAR(254), LINK_SFIN INT)	
INSERT INTO #EMPL (LINK, LINK_EMPL, SYST_PAY, SUBDIV_NAME, POST_NAME, LINK_SFIN)	
SELECT C.LINK, C.LINK_EMPL, E.SYST_PAY, SUBDIV_NAME, POST_NAME, E.LINK_KBK
FROM 
	dbo.VAC_CHILD C
	INNER JOIN dbo.KU_EMPL_PLACING E ON C.LINK_EMPL = E.LINK
WHERE	
	C.DATE1<=@DATE_END 
	and C.DATE2>=@DATE_BEG
	AND E.DEP_LINK = @DEP_LINK	


CREATE TABLE #OLD (LINK INT, LINK_EMPL INT, LINK_SFIN INT, LINK_PAYS INT, SUMMA_OLD NUMERIC(18,2))	
INSERT INTO #OLD (LINK, LINK_EMPL, LINK_SFIN, LINK_PAYS, SUMMA_OLD)	
SELECT 
C.LINK, C.LINK_EMPL, SD.LINK_SFIN, C.LINK_PAYS, SUM(SD.SUMMA)
FROM 
	dbo.VAC_CHILD C
	INNER JOIN dbo.SDOC_ACHILD_TABLE SD ON C.LINK = SD.LINK_VAC_CHILD	
	INNER JOIN dbo.SDOC D ON D.LINK = SD.LINK_UP
	INNER JOIN #EMPL E ON C.LINK = E.LINK
WHERE
	D.[DATE] BETWEEN @DATE_BEG AND @DATE_END
	AND 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
GROUP BY
	C.LINK, C.LINK_EMPL, SD.LINK_SFIN, C.LINK_PAYS

CREATE TABLE #RES (
	[LINK] int,
	[LINK_EMPL] int,
	[TAB_NUM] varchar(10),
	[NAME_EMPL] varchar(100),
	[COMMENT] varchar(254),
	[DATE_R] datetime,
	[DATE1] datetime,
	[DATE2] datetime,
	[SUMMA] numeric(18, 2),
	[LINK_PAYS] int,
	[CODE_PAYS] varchar(10),
	[NAME_PAYS] varchar(60),
	[TYP_CALC] int,
	[DEP_LINK] int,
	[name_dep] varchar(254),
	[CNT] int,
	[LINK_R] int,
	[LINK_KBK] int,
	[CODE_KBK] varchar(20),
	[INSTRUCT] tinyint,
	[date1_m] datetime,
	[date2_m] datetime,
	[SYST_PAY] tinyint,
	[SUMMA_OLD] numeric(18, 2),
	SUBDIV_NAME VARCHAR(254), 
	POST_NAME VARCHAR(254))

INSERT INTO #RES (LINK,LINK_EMPL,TAB_NUM,NAME_EMPL,COMMENT,DATE_R,DATE1,DATE2,SUMMA,LINK_PAYS,CODE_PAYS,NAME_PAYS,TYP_CALC,DEP_LINK,
	name_dep,CNT,LINK_R,LINK_KBK,CODE_KBK,INSTRUCT,date1_m,date2_m,SYST_PAY,SUMMA_OLD,SUBDIV_NAME,POST_NAME)
SELECT 
	DV.LINK,DV.LINK_EMPL,DV.TAB_NUM,DV.NAME_EMPL,DV.COMMENT,DV.DATE_R,DV.DATE1,DV.DATE2,DV.SUMMA,DV.LINK_PAYS,DV.CODE_PAYS,DV.NAME_PAYS,
	DV.TYP_CALC,DV.DEP_LINK,DV.name_dep,DV.CNT,DV.LINK_R,
	ISNULL(DV.LINK_KBK,E.LINK_SFIN),ISNULL(DV.CODE_KBK,F.CODE),
	DV.INSTRUCT,
	[date1_m] = (case when DV.DATE1<=@DATE_BEG then @DATE_BEG else  DV.DATE1 end),
	[date2_m] = (case when DV.DATE2>=@DATE_END then @DATE_END else  DV.DATE2 end),
	E.SYST_PAY, 
	ISNULL(O.SUMMA_OLD,0),
	SUBDIV_NAME,
	POST_NAME
FROM 
	dbo.DICTIONARY_VAC_CHILD DV
	INNER JOIN #EMPL E ON E.LINK = DV.LINK
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = E.LINK_SFIN
	LEFT JOIN #OLD O ON O.LINK = DV.LINK
WHERE 
	DV.DATE1<=@DATE_END
	and DV.DATE2>=@DATE_BEG 
	AND DV.DEP_LINK = @DEP_LINK

SELECT *,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 1 THEN dbo.NORM_DAY_DH(t1.link_empl,t1.date1_m, t1.Date2_m) ELSE 0 END)
			WHEN 3 THEN DAY(date2_m)
		END as DAYS, 
		 
		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 2 THEN dbo.NORM_HOUR_DH(t1.link_empl,t1.date1_m, t1.Date2_m) ELSE 0 END)
			WHEN 3 THEN 0
		END as HOURS,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 1 THEN dbo.norm_days(t1.link_empl,@varKSnMonth,@varKSnYear) ELSE 0 END)
			WHEN 3 THEN DAY(dbo.DateEndOfMonth(date2_m))
		END as NORM_DAYS,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 2 THEN dbo.norm_hours(t1.link_empl,@varKSnMonth,@varKSnYear) ELSE 0 END)
			WHEN 3 THEN 0
		END as NORM_HOURS,

		NAME_CALC = CASE TYP_CALC WHEN 1 THEN 'без учёта дней' WHEN 2 THEN 'пропорц.раб.вр.' ELSE 'пропорц.календ.дн.' END
FROM
	#RES T1

DROP TABLE #EMPL
DROP TABLE #RES





GO


GRANT EXECUTE ON dbo.[SD_VAC_CHILD_FILL] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
SET ANSI_WARNINGS OFF
GO
SET LOCK_TIMEOUT -1
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_REPORT_ANALITICS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_REPORT_ANALITICS]
GO

CREATE procedure [dbo].[RT_REPORT_ANALITICS]
	@nPeriod_Type int,
	@nPeriod_Date_Start datetime,
	@nPeriod_Number_Start int,
	@nPeriod_Date_Stop datetime,
	@nPeriod_Number_Stop int,
	@nStatus int,
    @cProgressTable varchar(254) = null,
    @to_cube int = 0,
    @nLink_Up int = NULL,
    @bWeb tinyint = 0
as

-- нормализация даты
declare @cDate varchar(8)
set @cDate = cast(year(@nPeriod_Date_Start) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Start) end as varchar),2) + '01'
set @nPeriod_Date_Start =  dateadd(dd,-1,dateadd(mm,1,@cDate))
set @cDate = cast(year(@nPeriod_Date_Stop) as varchar(4)) + right('00'+cast(case @nPeriod_Type when 1 then 12 else month(@nPeriod_Date_Stop) end as varchar),2) + '01'
set @nPeriod_Date_Stop =  dateadd(dd,-1,dateadd(mm,1,@cDate))

print @nPeriod_Date_Start
print @nPeriod_Date_Stop

-----------нижеследующие строчки нужны для нормализации наименования кбк в 317 форме-----------------
-----------------------------------------------------------------------------------------------------
declare @LF int,@LT int,@LC int
select @LF=link_form from report_forms where code='0503317M' and  start_date='20100101'

if exists(select * from #analitics_links where link_f = @LF) begin

    select @LT=link_table from report_tables where orders=1 and link_form=@LF 
    select @LC=Link_col from report_coloumns where orders=1 and link_table=@LT

    update report_dinamics
    set str_val= (select long_name from RN_VIEW_0503317M_01_2010 A where A.code=code_row)
    where link_sf in (select link_saved_form from report_saved_forms where link_form=@LF)
    and link_col=@LC
    and str_val<>(select long_name from RN_VIEW_0503317M_01_2010 A where A.code=code_row)


    select @LT=link_table from report_tables where orders=3 and link_form=@LF
    select @LC=Link_col from report_coloumns where orders=1 and link_table=@LT

    update report_dinamics
    set str_val= (select long_name from RN_VIEW_0503317M_03_2010 A where A.code=code_row)
    where link_sf in (select link_saved_form from report_saved_forms where link_form=@LF)
    and link_col=@LC and str_val<>(select long_name from RN_VIEW_0503317M_03_2010 A where A.code=code_row)
end
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------

declare @strProgressExec varchar(1000)
--------------------------------------------------------------------------------
declare @allow_empty tinyint, -- 0 - запрет пустых значений, !0 - пустые значения разрешены
		@inThousand tinyint,
		@fullNameOrg tinyint,
		@alt tinyint,
		@hg tinyint,
		@nFormVersion int

select top 1
@allow_empty = case when (cast(str_val as int)& 0x01) > 0 then 1 else 0 end,
@inThousand =  case when (cast(str_val as int)& 0x02) > 0 then 1 else 0 end,
@fullNameOrg = case when (cast(str_val as int)& 0x04) > 0 then 1 else 0 end,
@hg =		   case when (cast(str_val as int)& 0x10) > 0 then 1 else 0 end,
@alt =         case when (cast(str_val as int)& 0x20) > 0 then 1 else 0 end,
@nFormVersion = int_val
from
#selectedNAS
----ограничение диапазона сохранненых форм--------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Создание списка сохранённых форм'', percents = 12'
execute(@strProgressExec)
end
--------------------------------------------------------------------------------
--declare @sid varbinary(85)
--set @sid = suser_sid()
--if @calledfrom = 1
--	EXEC dbo.RM_SubDepAccessBySID @sid

--  предположим, что в таблице #analitics_links находятся линки форм и колонок, выборки за начальный период
--  link_f, link_t, link_c, col_type

--  сначала необходимо произвести проверочку на то, что в списке АП есть PERIOD
/* --решил закомментировать. Если период не выбран то все данные будут просто суммироваться
if not exists(select * from #analitics_ap where code = 'PERIOD')begin
		set @nPeriod_Date_Stop = @nPeriod_Date_Start
		set @nPeriod_Number_Stop = @nPeriod_Number_Start
end -- таким образом, если в списке АП нет периода, то правая граница временного диапазона = левой, и выборка данных происходит за один (начальный) период
*/

-- создаём таблицу с периодами
exec DropTempTable '#analitics_period'
create table #analitics_period (nn int, period_type int, period_number int, period_date datetime)
create table #analitics_period_copy (period_type int, period_number int, period_date datetime)

declare @cSqlStr varchar(8000)

set @cSqlStr = ''
if exists(select * from #analitics_periods)
	set @cSqlStr = 'insert into #analitics_period (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_periods'
else 
	set @cSqlStr = 'exec dbo.RT_ANALITICS_GET_PERIODS '+convert(varchar,@nPeriod_Date_Start,112)+', '+convert(varchar,@nPeriod_Date_Stop,112)+', '+cast(@nPeriod_Type as varchar)+', ''#analitics_period'''

execute(@cSqlStr)

--  необходимо получить таблицу, примерно следующего вида:
--  period_type, period_date, period_number, link_form, link_table, link_col
--  линки формы будут получены по коду формы, по имени или ордеру таблицы, по имени или ордеру колонки

create table #analitics_period_links (period_type int, period_date datetime, period_number int, link_form int, link_table int, link_col int, link_col_base int, col_type tinyint, keyflag tinyint, tab_type int)

declare	@this_link_form int,
		@this_link_table int,
		@nthis_table_order int,
		@cthis_table_name varchar(254),
		@this_link_col int,
		@nthis_col_order int,
		@cthis_col_name varchar(254),
		@this_link_col_type tinyint,
		@new_link_form int,
		@new_link_table int,
		@new_link_col int,
		@new_link_col_type tinyint,
		@cCodeForm varchar(50),
		@lpt int,
		@lpn int,
		@lpd datetime

while exists(select * from #analitics_links) begin -- цикл по отмеченным формам (потому что может быть отмечена более чем одна форма)
	select top 1 @this_link_form = link_f, @this_link_table = link_t, @this_link_col = link_c, @this_link_col_type = col_type from #analitics_links
	-- заполняем таблицу #analitics_period_links. каждому периоду будет соответствовать акуальная в том периоде форма
	select @nthis_table_order = orders, @cthis_table_name = [name] from dbo.report_tables where link_table = @this_link_table
	select @nthis_col_order = orders, @cthis_col_name = [name] from dbo.report_coloumns where link_col = @this_link_col

	-- код формы
	select @cCodeForm = rf0.code from dbo.report_forms as rf0 (nolock) where rf0.link_form = @this_link_form -- линк формы ищется по коду формы вне зависимости от даты

	-- цикл по периодам 
	insert into #analitics_period_copy (period_type, period_number, period_date) select period_type, period_number, period_date from #analitics_period

	while exists(select * from #analitics_period_copy) begin
		select top 1 @lpt = period_type, @lpn = period_number, @lpd = period_date from #analitics_period_copy
		-- линк формы в новом периоде
		set @new_link_form = null
		select top 1 @new_link_form = rsf.link_form
		--select rsf.period_type, rsf.begin_date, rsf.period_number, rsf.link_form
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = (select top 1 rf.link_form from dbo.report_forms as rf (nolock) where rf.code = (@cCodeForm) and rsf.begin_date between rf.start_date and isnull(rf.end_date,'20501231')) -- линк формы ищется по коду формы
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd

		-- линк таблицы в новом периоде
		set @new_link_table = null
		select top 1 @new_link_table = rt0.link_table
		from
			dbo.report_tables as rt0 (nolock)
		where
			rt0.link_form = @new_link_form
			and rt0.[name] = @cthis_table_name
		-- если не нашли таблицу по имени, ищем её по ордеру
		if @new_link_table is null begin
			select top 1 @new_link_table = rt0.link_table
			from
				dbo.report_tables as rt0 (nolock)
			where
				rt0.link_form = @new_link_form
				and rt0.orders = @nthis_table_order
		end

		-- линк колонки в новом периоде
		-- существует вероятность, что наименования колонок будут дублироваться в пределах одной формы. Поэтому если дублирование имеет место, переходим к поиску колонки по ордеру
		if (select count(*) from dbo.report_coloumns as rc0 (nolock) where rc0.link_table = @new_link_table and rtrim(rc0.[name]) = rtrim(@cthis_col_name)) = 1 begin
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
				rc0.link_table = @new_link_table
				and rc0.[name] = @cthis_col_name
			--print 'теперь линк колонки =' + cast(@new_link_col as varchar)
		end
		else begin
			-- если не нашли колонку, или колонок с этим именем оказалось несколько, ищем её по ордеру проверяя тип
			set @new_link_col = null
			select top 1 @new_link_col = rc0.link_col
			from
				dbo.report_coloumns as rc0 (nolock)
			where
			rc0.link_table = @new_link_table
			and rc0.orders = @nthis_col_order
			and rc0.col_type = @this_link_col_type
		end
		insert into #analitics_period_links (period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, col_type, keyflag, tab_type)
		select distinct
			rsf.period_type,
			rsf.begin_date,
			rsf.period_number,
			rsf.link_form,
			[link_table] = @new_link_table,
			[link_col] = @new_link_col,
			link_col_base = @this_link_col,
			col_type = @this_link_col_type,
			null,
			(select val_type from dbo.report_tables where link_table = @new_link_table)
		from
			dbo.report_saved_forms as rsf (nolock)
		where
			rsf.link_form = @new_link_form
			and rsf.period_type = @lpt
			and rsf.period_number = @lpn
			and rsf.begin_date = @lpd
		
		delete from #analitics_period_copy where period_type = @lpt and period_number = @lpn and period_date = @lpd
	end
	delete from #analitics_links where link_c = @this_link_col
end
update #analitics_period_links
set keyflag = (case when apl.link_col = (select a.link_code_col from dbo.report_tables as a where a.link_table = apl.link_table) then 1 else 0 end)
from #analitics_period_links as apl

exec DropTempTable '#tree_link'
create table #tree_link (link int)
insert into #tree_link (link)
select t.link
from dbo.report_svod_tree t
where t.link in (
    select cast((left(ltrim(f.[value]),charindex('@@',ltrim(f.[value]))-1)) as int) from #analitics_filters as f where f.code = 'DEP' or f.code = 'NAME_DEP'
)

/*
exec DropTempTable '#organizationen_link'
create table #organizationen_link (link int)
insert into #organizationen_link (link)
select d.link
from dbo.departments as d (nolock)
where d.link in (
    select link_report_org 
    from dbo.report_svod_tree
    where link in (
        select cast((left(ltrim(f.[value]),charindex('@@',ltrim(f.[value]))-1)) as int) from #analitics_filters as f where f.code = 'DEP' or f.code = 'NAME_DEP'
    )
)
or d.[budg] in (select rtrim(f.[value]) from #analitics_filters as f where f.code = 'BUDG')
*/

-- Создание таблицы сохранённых форм
exec DropTempTable '#sf'
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)
-- предполагается, что к этому моменту существует таблица #analitics_filters, содержащая среди прочего код аналитического признака CODE и текстовое значение VALUE


insert into #sf
select distinct
	rsf.link_saved_form,
	rsf.link_form,
	rsf.period_type,
	rsf.period_number,
	rsf.begin_date,
	rsf.link_organization,
	[btype] = (select [name] from dbo.BI_DICTION_BUDG_TYPE (nolock) where link = rsf.link_type_svod),
rsf.link_type_svod
from report_saved_forms as rsf (nolock)
	inner join (select distinct period_type, period_date, period_number, link_form from #analitics_period_links) as apl
	on
		apl.link_form = rsf.link_form
		and apl.period_date = rsf.begin_date
		and apl.period_type = rsf.period_type
		and apl.period_number = rsf.period_number
    inner join dbo.report_svod_tree as rst
    on 
        rsf.link_organization = rst.link_report_org
        and rsf.link_type_svod = rst.link_report_budg
        and (
            (
                rst.link_report_org in (select dep_link from user_form_access where SID = suser_sid())
                and
                rst.link_report_budg in (select budg_link from user_form_access where SID = suser_sid())
            )
            or @bWeb = 0 or (is_member('db_owner') = 1 and not exists(select top 1 * from user_form_access where SID = suser_sid()))
        )
WHERE
   del = 0
   AND rsf.version =
		case
			when @nFormVersion < 0 or @nFormVersion is null
			then(
				select top 1 version
	 			from report_saved_forms as lrsf (nolock)
				where lrsf.link_form = rsf.link_form
            AND 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 lrsf.atr_code = rsf.atr_code
				order by  version desc
			)
			else @nFormVersion
		end		
	and rsf.IsSvod in (
case when @nStatus&0x10 = 0x10 then 1 else -1 end,
		case when @nStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (
case when @nStatus&0x01 = 0x01 then 0 else -1 end,
		case when @nStatus&0x02 = 0x02 then 1 else -1 end,
		case when @nStatus&0x04 = 0x04 then 2 else -1 end,
		case when @nStatus&0x08 = 0x08 then 3 else -1 end,
		case when @nStatus&0x40 = 0x40 then 4 else -1 end,
		case when @nStatus&0x80 = 0x80 then 5 else -1 end)
--	and (
--		rsf.link_organization in (select link from #organizationen_link)
--		or not exists(select * from #analitics_filters where code = 'DEP' or code = 'NAME_DEP' or code = 'BUDG')
--	)
    and (
        rst.link in (select link from #tree_link)
        or not exists(select * from #tree_link)
    )
--    and (
--        rsf.link_organization in (select dep_link from user_form_access where SID = suser_sid())
--        or @bWeb = 0
--    )
    and (
		rsf.link_type_svod in (
			select b.link from dbo.kl_budg_type as b (nolock) where b.code in (select rtrim(f.[value]) from #analitics_filters as f where f.code = 'BUD_TYPE')
		)
		or not exists(select * from #analitics_filters where code = 'BUD_TYPE')
	)
	and (
		rsf.link_saved_form in (
			select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = dbo.RA_GETWORDNUM(f.code, 1, '|') and (rav.str_val = f.[value] /*or rav.int_val = cast(f.[value] as int)*/)
			                  JOIN dbo.REPORT_SAVED_FORMS rsfa ON rsfa.Link_Saved_Form = rav.link_saved_form JOIN dbo.REPORT_FORMS rfa ON rfa.Link_Form = rsfa.Link_Form AND (CHARINDEX('|',f.code) = 0 OR dbo.RA_GETWORDNUM(f.code,2,'|') = rfa.code)
			 where f.type = 2
--			case
--				when exists(select * from #analitics_filters where [type] = 2 and code in (select rav.code_atr from dbo.report_atribut_values as rav where rav.link_saved_form = rsf.link_saved_form))
--				then (select rav.link_saved_form from dbo.report_atribut_values as rav inner join #analitics_filters as f on rav.code_atr = f.code and (rav.str_val = f.[value] or rav.int_val = cast(f.[value] as int)) where f.type = 2)
--				else 0
--			end
		)
		or not exists(select * from #analitics_filters f where [type] = 2 and dbo.RA_GETWORDNUM(code, 1, '|') in (select rav.code_atr from dbo.report_atribut_values as rav JOIN dbo.REPORT_SAVED_FORMS rsfa ON rsfa.Link_Saved_Form = rav.link_saved_form JOIN dbo.REPORT_FORMS rfa ON rfa.Link_Form = rsfa.Link_Form AND (CHARINDEX('|',f.code) = 0 OR dbo.RA_GETWORDNUM(f.code,2,'|') = rfa.code) where rav.link_saved_form = rsf.link_saved_form ))
	)

if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Определение рабочих данных'', percents = 23'
execute(@strProgressExec)
end

-- 
--SELECT * FROM #analitics_period_links
--RETURN 

exec DropTempTable '#report_forms'
create table #report_forms (Link_Form int,[Name] varchar(200),Code varchar(20),[Start_Date] datetime,Periodic tinyint,IsSvod tinyint,Form_Type int,atributs varchar(1000),End_Date datetime)
insert into #report_forms 
select distinct Link_Form,[Name],Code,[Start_Date],Periodic,IsSvod,Form_Type,atributs,End_Date
from dbo.report_forms where link_form in (select distinct link_form from #analitics_period_links)
create index ixx_f on #report_forms (Link_Form)

exec DropTempTable '#report_tables'
create table #report_tables (Link_Table int,[Name]varchar(50),Link_Form int,Orders tinyint,Link_Code_Col int,Val_Type tinyint)
insert into #report_tables 
select distinct Link_Table,[Name],Link_Form,Orders,Link_Code_Col,Val_Type
from dbo.report_tables where link_table in (select distinct link_table from #analitics_period_links)
create index ixx_t on #report_tables (Link_Table,Link_Form)

exec DropTempTable '#report_coloumns'
create table #report_coloumns (Link_Col int,Orders tinyint,[Name] varchar(70),Link_Table int,IsExported tinyint,Col_Type tinyint,Export_Order tinyint,Calc_Orders tinyint,IsEdited tinyint,Val_Len int,Dictionary varchar(100),Dictionary_Columns_List varchar(250),Dictionary_Fields_List varchar(250),input_mask varchar(200),[property] int,STR_PROPERTY varchar)
insert into #report_coloumns 
select distinct Link_Col,Orders,[Name],Link_Table,IsExported,Col_Type,Export_Order,Calc_Orders,IsEdited,Val_Len,Dictionary,Dictionary_Columns_List,Dictionary_Fields_List,input_mask,[property],STR_PROPERTY
from dbo.report_coloumns where link_col in (select distinct link_col from #analitics_period_links)
create index ixx_c on #report_coloumns (Link_col,Link_Table)

exec DropTempTable '#report_rows'
create table #report_rows (Link_Row int,Orders smallint,Link_Table int,Calc_Orders smallint,Print_Null tinyint)
insert into #report_rows 
select distinct Link_Row,Orders,Link_Table,Calc_Orders,Print_Null
from dbo.report_rows where link_table in (select distinct link_table from #report_tables)
create index ixx_r on #report_rows (Link_row,Link_Table)

exec DropTempTable '#report_formula'
create table #report_formula (Link_Row int,Link_col int, Formula varchar(8000))
insert into #report_formula 
select distinct Link_Row,Link_col,Formula
from dbo.report_formula where link_col in (select distinct link_col from #report_coloumns)

insert into #report_formula 
select distinct Link_Row,Link_col,Formula
from dbo.report_formula RF
where link_col in (select distinct link_code_col from #report_tables)
      AND NOT EXISTS(SELECT * FROM #report_formula RF1 WHERE rf.[Link_Row] = rf1.[Link_Row] AND rf.[Link_Col] = rf1.[Link_col])

create index ixx_fla on #report_formula (Link_row, Link_col)


exec DropTempTable '#report_string'
create table #report_string (Link_saved_form int,Link_col int, Link_row int, str_val varchar(8000))
insert into #report_string 
select distinct Link_saved_form,Link_col,Link_Row,str_val
from dbo.report_string 
where Link_saved_form in (select distinct link_sf from #sf)
and link_col in (select distinct link_col from #report_coloumns)
create index ixx_str on #report_string (link_saved_form, Link_row, Link_col)

exec DropTempTable '#report_summa'
create table #report_summa (Link_saved_form int,Link_col int, Link_row int, summa float(53))
insert into #report_summa 
select distinct Link_saved_form,Link_col,Link_Row,summa
from dbo.report_summa_all 
where Link_saved_form in (select distinct link_sf from #sf)
and link_col in (select distinct link_col from #report_coloumns)
create index ixx_sum on #report_summa (link_saved_form, Link_row, Link_col)

exec DropTempTable '#report_dinamics'
create table #report_dinamics (Link_sf int,Link_col int, code_row varchar(50), float_val numeric(20,4), str_val varchar(8000))
insert into #report_dinamics 
select distinct Link_sf,Link_col,Code_Row,float_val,str_val
from dbo.report_dinamics_all 
where Link_sf in (select distinct link_sf from #sf)
and link_col in (select distinct link_col from #report_coloumns)
create index ixx_din on #report_dinamics (Link_sf, Link_col, code_row)

if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Нормализация данных по периодам'', percents = 24'
execute(@strProgressExec)
end

--select * from #report_coloumns
--select * from #sf
--return
---------------------------------
declare @num_flt int
select @num_flt = count(*) 
from(
	select code
	from #analitics_filters
	where[type] = 1
	group by code
) as A

-- "оцифровываем" фильтр по текстовым колонкам							
create table #analitics_filters_col(
	period_type int,
	period_date datetime,
	period_number int,
	link_form int, 
	link_table int, 
	link_col int,
	[value] varbinary(254),
	[type] tinyint, 
	table_type tinyint)		
insert into #analitics_filters_col (period_type, period_date, period_number, link_form, link_table, link_col, [value], [type], table_type)								
select apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, apl.link_col, cast(left(ltrim(rtrim(af.[value])),254) as varbinary(254)), af.[type], rt.val_type
from #analitics_period_links as apl
inner join #analitics_filters as af
	on apl.link_col_base = cast(right(rtrim(af.code),len(af.code)-1) as int)
inner join #report_coloumns as rc
	on rc.link_col = apl.link_col
inner join #report_tables as rt
	on rc.link_table = rt.link_table
where apl.col_type = 1
	and af.[type] = 1

create index #ixx001 on #analitics_filters_col (period_type, period_date, period_number, link_form, link_table, link_col)

-- находим в частности линк роу для последующей фильтрации
create table #analitics_filters_col_ext1(
	/*link_sf int,*/
	period_type int,
	period_date datetime,
	period_number int,
	link_form int,
	link_table int,
	link_col int,
	link_col_base int, 
	link_row int, 
	code_row varchar(50),
	table_type tinyint)
   
create index #ixx0011 on #analitics_filters_col_ext1 (period_type, period_number, period_date, link_form, link_table, link_row)   

create table #analitics_filters_col_ext (
	/*link_sf int,*/
	period_type int,
	period_date datetime,
	period_number int,
	link_form int,
	link_table int,
	link_col int, 
	link_col_base int, 
	link_row int, 
	code_row varchar(50),
	table_type tinyint)

insert into #analitics_filters_col_ext (/*link_sf,*/ period_type, period_date, period_number, link_form, link_table, link_col, 	link_col_base, link_row, code_row, table_type)
select distinct /*sf.link_sf,*/ apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, rs.link_col, apl.link_col_base, rs.link_row, null, 0--, cast(left(ltrim(rtrim(rs.str_val)),254) as varbinary(254)), flt.[value]
from #sf as sf
	inner join #report_string as rs
		on sf.link_sf = rs.link_saved_form
	inner join #report_coloumns as rc
		on rc.link_col = rs.link_col
		and rc.isEdited = 1
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and apl.link_col = rs.link_col
		and not exists (select * from dbo.report_forms where left(code,7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col)))
	inner join #analitics_filters_col as flt
		on  apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rs.link_col = flt.link_col
where cast(REPLACE(left(ltrim(rtrim(rs.str_val)),254),'''','"') as varbinary(254)) = flt.[value]

insert into #analitics_filters_col_ext (/*link_sf,*/ period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, link_row, code_row, table_type)
select distinct /*sf.link_sf,*/ apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, rf.link_col, apl.link_col_base, rf.link_row, null, 0--, cast(left(ltrim(rtrim(rf.formula)),254) as varbinary(254)), flt.[value]
from #sf as sf
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join #report_formula as rf
		on rf.link_col = apl.link_col
	inner join #report_coloumns as rc
		on rc.link_col = rf.link_col
		and rc.isEdited = 0
	inner join #analitics_filters_col as flt
		on  apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rf.link_col = flt.link_col
where cast(REPLACE(left(ltrim(rtrim(rf.formula)),254),'''','"') as varbinary(254)) = flt.[value]

-- теперь то же самое только для динамических таблиц
insert into #analitics_filters_col_ext (/*link_sf,*/ period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, link_row, code_row, table_type)
select distinct /*sf.link_sf,*/ apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, rd.link_col, apl.link_col_base, null, rd.code_row, 1
from #sf as sf
	inner join #report_dinamics as rd
		on sf.link_sf = rd.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rd.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
		and rt.link_code_col <> rc.link_col
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rd.link_col = apl.link_col
	inner join #analitics_filters_col as flt
		on  apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rc.link_col = flt.link_col
where cast(REPLACE(left(ltrim(rtrim(dbo.RT_BOK14(rd.str_val))),254),'''','"') as varbinary(254)) = flt.[value]

insert into #analitics_filters_col_ext (/*link_sf,*/ period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, link_row, code_row, table_type)
select distinct /*sf.link_sf,*/ apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, apl.link_col, apl.link_col_base, null, rdt.code_row, 1
from #sf as sf
	inner join #report_dinamics as rdt
		on sf.link_sf = rdt.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rdt.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rt.link_code_col = apl.link_col
	inner join #analitics_filters_col as flt
		on  apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and apl.link_col = flt.link_col
where cast(REPLACE(left(ltrim(rtrim(dbo.RT_BOK14(rdt.code_row))),254),'''','"') as varbinary(254)) = flt.[value]
/*option(merge join)*/

insert into #analitics_filters_col_ext (/*link_sf,*/ period_type, period_date, period_number, link_form, link_table, link_col, link_col_base, link_row, code_row, table_type)
select distinct /*sf.link_sf,*/ apl.period_type, apl.period_date, apl.period_number, apl.link_form, apl.link_table, rf.link_col, apl.link_col_base, null, rdt.code_row, 1
from #sf as sf
	inner join #report_dinamics as rdt
		on sf.link_sf = rdt.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rdt.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join #report_formula as rf
		on rf.link_col = apl.link_col
		and exists (select * from dbo.report_forms where left(code,7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = rf.link_col and orders = 1)))
		and rf.link_row = [dbo].[RT_BIND14](rt.link_table, rdt.code_row)
	inner join #analitics_filters_col as flt
		on  apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rf.link_col = flt.link_col
where cast(REPLACE(left(ltrim(rtrim(rf.formula)),254),'''','"') as varbinary(254)) = flt.[value]

create index ixx002 on #analitics_filters_col_ext (period_type, period_date, period_number, link_form, link_table, link_col, link_row, code_row)

--select * from #analitics_filters_col
--select * from #analitics_filters_col_ext
--return
--------------------------------------------------------------------------------------------------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Преобразование фильтра'', percents = 30'
execute(@strProgressExec)
end
--------------------------------------------------------------------------------------------------------------------------------
-- начало блока. Этот блок добавлен, чтобы осуществлять фильтрацию по условию "И"
exec DropTempTable '#filter_help'
create table #filter_help (period_type tinyint, period_date datetime, period_number tinyint, code_form varchar(50), order_table int, num_col int)
insert into #filter_help (period_type, period_date, period_number, code_form, order_table, num_col)
select 
    A.period_type,
    A.period_date,
    A.period_number,
    A.code_form, 
    A.order_table,
    count(A.link_col_base)
from 
    (select 
        B.period_type,
        B.period_date,
        B.period_number,
        (select code from #report_forms where link_form = B.link_form) as code_form,
        (select orders from #report_tables where link_table = B.link_table) as order_table, 
        B.link_col_base as link_col_base
    from #analitics_filters_col_ext as B
    group by B.period_type,B.period_date,B.period_number,B.link_form, B.link_table, B.link_col_base) as A 
group by A.period_type,A.period_date,A.period_number,A.code_form, A.order_table   


--select * from #analitics_filters_col_ext
--select * from #filter_help
--return

-- конец блока --

insert into #analitics_filters_col_ext1(period_type,period_date,period_number,link_form,link_table,link_col,link_row,code_row,table_type)
select afc.period_type,afc.period_date,afc.period_number,afc.link_form,afc.link_table,afc.link_col,afc.link_row,afc.code_row,afc.table_type
from #analitics_filters_col_ext afc
where 
    (
        select num_col 
        from #filter_help 
        where code_form = (select code from #report_forms where link_form = afc.link_form)
        and order_table = (select orders from #report_tables where link_table = afc.link_table)
        and period_type = afc.period_type
        and period_date = afc.period_date
        and period_number = afc.period_number
    ) 
=   (
        select 
            count(A.link_col_base)
        from 
            (select 
                B.period_type,
                B.period_date,
                B.period_number,
                (select code from #report_forms where link_form = B.link_form) as code_form,
                (select orders from #report_tables where link_table = B.link_table) as order_table, 
                B.link_col_base as link_col_base
            from #analitics_filters_col_ext as B
            where afc.period_type = B.period_type
            AND (select code from #report_forms where link_form = B.link_form) = (select code from #report_forms where link_form = afc.link_form)
            and afc.period_date = B.period_date
            and afc.period_number = B.period_number
            and afc.code_row = B.code_row
            and afc.table_type = B.table_type
            group by B.period_type,B.period_date,B.period_number,link_form, link_table, link_col_base) as A 
        group by A.code_form, A.order_table    
    )
and afc.table_type = 1

insert into #analitics_filters_col_ext1(period_type,period_date,period_number,link_form,link_table,link_col,link_row,code_row,table_type)
select distinct afc.period_type,afc.period_date,afc.period_number,afc.link_form,afc.link_table,afc.link_col,afc.link_row,afc.code_row,afc.table_type
from #analitics_filters_col_ext afc
where 
    (
        select num_col 
        from #filter_help 
        where code_form = (select code from #report_forms where link_form = afc.link_form)
        and order_table = (select orders from #report_tables where link_table = afc.link_table)
        and period_type = afc.period_type
        and period_date = afc.period_date
        and period_number = afc.period_number
    ) 
=   (
        select 
            count(A.link_col_base)
        from 
            (select 
                B.period_type,
                B.period_date,
                B.period_number,
                (select code from #report_forms where link_form = B.link_form) as code_form,
                (select orders from #report_tables where link_table = B.link_table) as order_table, 
                B.link_col_base as link_col_base
            from #analitics_filters_col_ext as B
            where afc.period_type = B.period_type
            and afc.period_date = B.period_date
            and afc.period_number = B.period_number
            and afc.link_row = B.link_row
            and afc.table_type = B.table_type
            group by B.period_type,B.period_date,B.period_number,link_form, link_table, link_col_base) as A 
        group by A.code_form, A.order_table    
    )
and afc.table_type = 0

--------------------------------------------------------------------------------------------------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Фильтрация данных'', percents = 33'
execute(@strProgressExec)
END
--------------------------------------------------------------------------------------------------------------------------------
-- здесь создаётся нормализованная, обобщённая табличка со статическими данными
create table #report_static_table (link_sf int, link_table int, link_col int, link_row int, str_val varchar(8000), summa numeric(20,4))

IF @allow_empty <> 0
BEGIN
   INSERT #report_static_table ([LINK_SF],
                                [LINK_TABLE],
                                [LINK_COL],
                                [LINK_ROW],
                                [STR_VAL],
                                [SUMMA])
   SELECT [A].[LINK_SF], 
          [E].[LINK_TABLE], 
          [D].[LINK_COL],
          [C].[LINK_ROW], 
          NULL, 
          0
   FROM #sf                     [A]
   JOIN #report_tables          [B] ON [A].[LINK_FORM] = [B].[LINK_FORM] AND
                                       [B].[VAL_TYPE] = 0                                       
   JOIN #report_rows            [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
   JOIN #report_coloumns        [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE] AND
                                       [D].[COL_TYPE] = 0
   JOIN #analitics_period_links [E] ON [A].[PERIOD_TYPE] = [E].[PERIOD_TYPE] AND 
                                       [A].[PERIOD_NUMBER] = [E].[PERIOD_NUMBER] AND 
                                       [A].[BEGIN_DATE] = [E].[PERIOD_DATE] AND 
                                       [A].[LINK_FORM] = [E].[LINK_FORM] AND 
                                       [D].[LINK_COL] = [E].[LINK_COL]
   LEFT JOIN (SELECT [PERIOD_TYPE], 
                     [PERIOD_NUMBER], 
                     [PERIOD_DATE], 
                     [LINK_FORM], 
                     [LINK_TABLE], 
                     [LINK_ROW] 
              FROM #analitics_filters_col_ext1 
              WHERE [TABLE_TYPE] = 0) [F] ON [E].[PERIOD_TYPE] = [F].[PERIOD_TYPE] AND 
                                             [E].[PERIOD_NUMBER] = [F].[PERIOD_NUMBER] AND 
                                             [E].[PERIOD_DATE] = [F].[PERIOD_DATE] AND
		                                       [E].[LINK_FORM] = [F].[LINK_FORM] AND 
                                             [E].[LINK_TABLE] = [F].[LINK_TABLE] AND 
                                             [C].[LINK_ROW] = [F].[LINK_ROW]
   WHERE ([F].[LINK_ROW] IS NOT NULL) OR 
         NOT EXISTS(SELECT * 
                    FROM #analitics_filters_col/*#analitics_filters_col_ext1*/ 
                    WHERE [TABLE_TYPE] = 0)
   
END

insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa)
select sf.link_sf, apl.link_table, rsu.link_col, rsu.link_row, rs.str_val, rsu.summa
from #sf as sf
	inner join #report_summa as rsu
		on sf.link_sf = rsu.link_saved_form
	left join #report_string as rs
		on sf.link_sf = rs.link_saved_form
		and rs.link_col = rsu.link_col
		and rs.link_row = rsu.link_row
-- 	left join dbo.report_formula as rf
-- 		on rsu.link_col = rf.link_col
-- 		and rsu.link_row = rf.link_row
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and apl.link_col = rsu.link_col
		and not exists (select * from dbo.report_forms where left(code,7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col)))
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, link_row from #analitics_filters_col_ext1 where table_type = 0) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rsu.link_row = flt.link_row
where 
	(flt.link_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where table_type = 0)

--select * from #analitics_filters_col_ext1
--select * from #report_static_table
--return

insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa)
select sf.link_sf, apl.link_table, rf.link_col, rf.link_row, rf.formula, 0.0
from #sf as sf
	inner join #report_static_table as rst
		on sf.link_sf = rst.link_sf
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and apl.link_col <> rst.link_col
	inner join #report_formula as rf
		on rf.link_col = apl.link_col
		and rf.link_row = rst.link_row
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, link_row from #analitics_filters_col_ext1 where table_type = 0) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rf.link_row = flt.link_row
where 
	(flt.link_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where table_type = 0)

insert into #report_static_table (link_sf, link_table, link_col, link_row, str_val, summa)
select sf.link_sf, apl.link_table, rs.link_col, rs.link_row, rs.str_val, 0.0
from #sf as sf
	inner join #report_static_table as rst
		on sf.link_sf = rst.link_sf
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and apl.link_col <> rst.link_col
	inner join #report_string as rs
		on rs.link_saved_form = rst.link_sf
		and rs.link_col = apl.link_col
		and rs.link_row = rst.link_row
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, link_row from #analitics_filters_col_ext1 where table_type = 0) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rs.link_row = flt.link_row
where 
	(flt.link_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where table_type = 0)
 
--select * from #report_static_table
--return

-- этот апдейт нужен исключительно для того чтобы "выровнять" линки колонок
update #report_static_table
set link_col = apl.link_col_base/*, link_table = (select link_table from #analitics_period_links where link_col = apl.link_col_base group by link_table)*/
from #report_static_table as rst
	inner join #analitics_period_links as apl
		on rst.link_col = apl.link_col

create index ixx0 on #report_static_table (link_sf, link_table, link_col, link_row)


-------------------------------------------------------------------------------
-- здесь создаётся нормализованная, обобщённая табличка с динамическими данными
create table #report_dynamic_table (link_sf int, link_table int, link_col int, code_row varchar(50), str_val varchar(8000), summa numeric(20,4))
insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa)
select sf.link_sf, apl.link_table, rd.link_col, rd.code_row, rd.str_val, rd.float_val
from #sf as sf
	inner join #report_dinamics as rd
		on sf.link_sf = rd.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rd.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
		and rt.link_code_col <> rc.link_col
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rd.link_col = apl.link_col
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, code_row from #analitics_filters_col_ext1 where table_type = 1) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rtrim(rd.code_row) = rtrim(flt.code_row)
where 
	(flt.code_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where (table_type = 1 or exists(select top 1 * from dbo.report_forms where link_form = apl.link_form and left(code,7) LIKE '050307[45]')))

insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa)
select distinct sf.link_sf, apl.link_table, rt.link_code_col, rdt.code_row, dbo.RT_BOK14(rdt.code_row), 0.0
from #sf as sf
	inner join #report_dynamic_table as rdt
		on sf.link_sf = rdt.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rdt.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
		and rt.link_code_col = apl.link_col
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, code_row from #analitics_filters_col_ext1 where table_type = 1) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rdt.code_row = flt.code_row
where 
	(flt.code_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where table_type = 1)

insert into #report_dynamic_table (link_sf, link_table, link_col, code_row, str_val, summa)
select distinct sf.link_sf, apl.link_table, rf.link_col, rdt.code_row, rf.formula, 0.0
from #sf as sf
	inner join #report_dynamic_table as rdt
		on sf.link_sf = rdt.link_sf
	inner join #report_coloumns as rc
		on rc.link_col = rdt.link_col
	inner join #report_tables as rt
		on rt.link_table = rc.link_table
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join #report_formula as rf
		on rf.link_col = apl.link_col
		and exists (select * from dbo.report_forms where left(code,7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = rf.link_col and orders = 1)))
		and rf.link_row = [dbo].[RT_BIND14](rt.link_table, rdt.code_row)
	left join (select /*link_sf,*/ period_type, period_number, period_date, link_form, link_table, code_row from #analitics_filters_col_ext1 where table_type = 1) as flt
		on /*sf.link_sf = flt.link_sf
		and*/ apl.period_type = flt.period_type
		and apl.period_number = flt.period_number
		and apl.period_date = flt.period_date
		and apl.link_form = flt.link_form
		and apl.link_table = flt.link_table
		and rdt.code_row = flt.code_row
where 
	(flt.code_row is not null) or not exists(select * from #analitics_filters_col/*#analitics_filters_col_ext1*/ where table_type = 1)


update #report_dynamic_table
set link_col = apl.link_col_base/*, link_table = (select link_table from #analitics_period_links where link_col = apl.link_col_base group by link_table)*/
from #report_dynamic_table as rdt
	inner join #analitics_period_links as apl
		on rdt.link_col = apl.link_col

create index ixx1 on #report_dynamic_table (link_sf, link_table, link_col, code_row)

--select * from #analitics_filters_col
--select * from #analitics_filters_col_ext1
--select * from #report_static_table
--select * from #report_dynamic_table
--return

--select ltrim(rtrim(f.[value])) from #analitics_filters as f where f.[type] = 0 and f.[code] = 'KEY_COL'

-----------------------------------------------------------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка данных'', percents = 40'
execute(@strProgressExec)
END





/* for dinamic */
CREATE TABLE #restab(nn int IDENTITY, form char(20),begin_date datetime, period_type tinyint, [period_number] tinyint, [period] varchar(50), [link_table] int, tab varchar(50),dep varchar(50),deplink int,budg varchar(10),name_dep varchar(254),key_col varchar(250),link_row varchar(50),col varchar(70),link_col int,ord_col varchar(3),bud_type varchar(250),summa float(53),lsf int)
insert into #restab
select distinct	
	[form] 	= rf.code, /*код формы*/
	[begin_date]= sf.begin_date,
	[period_type] = sf.period_type,--cast(DATEPART(yyyy, sf.begin_date) as varchar) + right('0'+cast(DATEPART(mm,sf.begin_date) as varchar),2) + right('0'+cast(DATEPART(dd,sf.begin_date) as varchar),2) + dbo.rt_GetPeriod(sf.period_type,sf.period_number,sf.begin_date), -- dbo.rm_GetPeriodName(SF.period_type,SF.period_number,SF.begin_date),
	[period_number] = sf.period_number,
	[period] = null,
	[link_table] = rt.[link_table],
	[tab]	= rt.[name], /*код таблицы*/
	[dep]	= dep.code, /*код источника (организации)*/
	[deplink] = dep.link,
	[budg] = dep.budg, /*код БП источника (организации)*/
	[name_dep] = 
	case 
		when exists(select * from dbo.departments_hist where link_up = dep.link)
		then case 
				when @fullNameOrg <> 0 
				then (select rtrim(full_name) from dbo.departments_hist where link_up = dep.link and date_begin = (select max(date_begin) from dbo.departments_hist where link_up = dep.link))
				else (select rtrim(name) from dbo.departments_hist where link_up = dep.link and date_begin = (select max(date_begin) from dbo.departments_hist where link_up = dep.link))
			 end
		else
		case when @fullNameOrg <> 0 then dep.full_name else dep.[name] end
	end,
	[key_col]= dbo.RT_BOK14(rd.code_row), /*код боковика*/
	[link_row] = rd.code_row, /*линк строчки*/
	[col]	= rc.[name], /*код колонки*/
	[link_col]	= rc.link_col, /*код колонки*/
	[ord_col]= right('000' + ltrim(rtrim(cast(case /*весь этот бардак - заглушка для 317 форм*/
		when rf.CODE like '%0503317M' or rf.CODE like '%0503317G'
		then /*(case
		when RC.[orders] = 2
		then 0
		when RC.[orders] > 2
		then RC.[orders] - 1
		else RC.[orders]
		end)*/
		rc.[export_order]
		else rc.[orders]
		end as varchar(3)))),3),

	[bud_type] = isnull(sf.btype,'Бюджет не определен'),
	[summa] = case when @inThousand <> 0 then (rd.summa)/1000.0 else rd.summa end, /*номер колонки*/ 	
	[lsf] = sf.link_sf
from 	
	#sf as sf
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join #report_coloumns as rc (nolock)
		on rc.link_col = apl.link_col
	inner join #report_forms as rf (nolock)
		on rf.link_form = apl.link_form
	inner join #report_dynamic_table as rd
		on rd.link_sf = sf.link_sf
		and rd.link_col = apl.link_col_base
	left join #report_tables as rt (nolock)
		on rt.link_table = rd.link_table
	inner join dbo.departments as dep (nolock)
		on dep.link = sf.link_organization
where
(rd.summa <> 0.0 or (rc.col_type = 0 and @allow_empty <> 0)) /*or exists (select * from dbo.report_forms where left(code,7) = '0503074' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = rc.link_col and orders = 1)))*/
and (
        (rtrim(ltrim(dbo.RT_BOK14(rd.code_row))) 
        in (
            select ltrim(rtrim(f.[value])) 
            from #analitics_filters as f 
            where f.[type] = 0 
            and f.[code] = 'KEY_COL'
            )
        ) 
        or(not exists(select * from #analitics_filters as f where f.[type] = 0 and f.[code] = 'KEY_COL'))
)
union
/* for static */
select distinct
	[form] 	= rf.code, /*код формы*/
	[begin_date] = sf.begin_date,
	[period_type]= sf.period_type,--cast(DATEPART(yyyy, sf.begin_date) as varchar) + right('0'+cast(DATEPART(mm,sf.begin_date) as varchar),2) + right('0'+cast(DATEPART(dd,sf.begin_date) as varchar),2) + dbo.rt_GetPeriod(sf.period_type,sf.period_number,sf.begin_date), -- dbo.rm_GetPeriodName(SF.period_type,SF.period_number,SF.begin_date),
	[period_number] = sf.period_number,
	[period] = null,
	[link_table] = rt.[link_table],
	[tab]	= rt.[name], /*код таблицы*/
	[dep]	= dep.code, /*код источника (организации)*/
	[deplink] = dep.link,
	[budg] = dep.budg, /*код БП источника (организации)*/
	[name_dep] = 
	case 
		when exists(select * from dbo.departments_hist where link_up = dep.link)
		then case 
				when @fullNameOrg <> 0 
				then (select rtrim(full_name) from dbo.departments_hist where link_up = dep.link and date_begin = (select max(date_begin) from dbo.departments_hist where link_up = dep.link))
				else (select rtrim(name) from dbo.departments_hist where link_up = dep.link and date_begin = (select max(date_begin) from dbo.departments_hist where link_up = dep.link))
			 end
		else
		case when @fullNameOrg <> 0 then dep.full_name else dep.[name] end
	end,
	[key_col]= (select ltrim(rtrim(formula)) from #report_formula where link_row = rst.link_row and link_col = (select link_code_col from #report_tables where link_table = rt.[link_table])),
	[link_row] = convert(varchar(50),rst.link_row), /*линк строчки*/
	[col]	= rc.[name], /*код колонки*/
	[link_col]	= rc.link_col, /*код колонки*/
	[ord_col]= right('000' + ltrim(rtrim(cast(rc.[orders] as varchar(3)))),3), /*номер колонки*/
	[bud_type] = isnull(sf.btype,'Бюджет не определен'),
	[summa] = case when @inThousand <> 0 then (rst.summa)/1000.0 else rst.summa end, /*сумма*/ 	
	[lsf] = sf.link_sf
from
	#sf as sf
	inner join #analitics_period_links as apl
		on sf.period_type = apl.period_type
		and sf.period_number = apl.period_number
		and sf.begin_date = apl.period_date
		and sf.link_form = apl.link_form
	inner join #report_coloumns as rc (nolock)
		on rc.link_col = apl.link_col
	inner join #report_forms as rf (nolock)
		on rf.link_form = apl.link_form
	inner join #report_static_table as rst
		on rst.link_sf = sf.link_sf
		and rst.link_col = apl.link_col_base
	inner join #report_tables as rt (nolock)
		on rt.link_table = rst.link_table
	inner join dbo.departments as dep (nolock)
		on dep.link = sf.link_organization
where	
(rst.summa<>0.0 or (rc.col_type = 0 and @allow_empty <> 0))
and (
        (
            (
                select ltrim(rtrim(formula)) 
                from #report_formula 
                where link_row = rst.link_row 
                and link_col = (
                    select link_code_col 
                    from #report_tables 
                    where link_table = rt.[link_table]
                )
            ) in (select ltrim(rtrim(f.[value])) from #analitics_filters as f where f.[type] = 0 and f.[code] = 'KEY_COL')
        )
        or not exists(select * from #analitics_filters as f where f.[type] = 0 and f.[code] = 'KEY_COL')
    )

update #restab
set period = cast(DATEPART(yyyy, begin_date) as varchar) + right('0'+cast(DATEPART(mm,begin_date) as varchar),2) + right('0'+cast(DATEPART(dd,begin_date) as varchar),2) + dbo.rt_GetPeriod(period_type,period_number,begin_date,period_type)
from #restab

------------------------------------------------------------------------------------------------------
--select * from #restab
--select * from #report_dynamic_table
--select * from #report_static_table
-----------------------------------------------------------------------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Построение сводной таблицы'', percents = 65'
execute(@strProgressExec)
end

declare @alt_summ tinyint

if exists(select * from #analitics_ap where code = 'PERIOD') and @alt = 1
    set @alt_summ = 1
else
    set @alt_summ = 0

declare @cSqlJoins varchar(8000),
		@cSqlSelect varchar(8000),
		@cSqlGroupBy varchar(8000),
		@cSqlWhere varchar(8000),
		@col_an_str varchar(1000), -- строка содержащая список аналитических признаков в столбцах
		@row_an_str varchar(1000), -- строка содержащая список аналитических признаков в строках
		@col_an_str_group varchar(1000), -- строка содержащая список аналитических признаков в столбцах, по которым нужно группировать
		@row_an_str_group varchar(1000), -- строка содержащая список аналитических признаков в строках, по которым нужно группировать
		@strExcec varchar (8000),
		@strWhere varchar(8000),
		@cSqlJoinsAtr varchar(8000),
		@j int,
		@i int,
		@nMaxOrders int,
		@cStr_val varchar(1000),
		@res_set_num int

set @cSqlSelect = ''
set @cSqlWhere = ''
set @cSqlJoins = ''
set @cSqlJoinsAtr = ''
set @cSqlGroupBy = ''

--select * from #analitics_period
----
--select * from #analitics_period_links
----
--select period_type, min(period_number) as period_number, min(period_date) as period_date from #analitics_period group by period_type
----

select -- формирование джоинов с текстовыми столбцами
	@cSqlJoins = @cSqlJoins +
	case
		when apl.tab_type = 0 and not exists (select * from dbo.report_forms where left(ltrim(code),7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col_base/* and [name] like 'Код%'*/)))
		then 'left join (select distinct rst.link_sf as link_sf, rst.link_table as link_table, rst.link_col as link_col, convert(varchar(50),rst.link_row) as link_row, rst.str_val as str_val from #report_static_table as rst where rst.link_col = '+cast(apl.link_col_base as varchar)+') as C' + cast(apl.link_col_base as varchar) + '$ on res$.lsf = C' + cast(apl.link_col_base as varchar) + '$.link_sf and res$.link_table = C' + cast(apl.link_col_base as varchar) + '$'
		when apl.tab_type = 1 or exists (select * from dbo.report_forms where left(ltrim(code),7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col_base/* and [name] like 'Код%'*/)))
		then 'left join (select distinct rdt.link_sf as link_sf, rdt.link_table as link_table, rdt.link_col as link_col, rdt.code_row as code_row, rdt.str_val as str_val from #report_dynamic_table as rdt where rdt.link_col = '+cast(apl.link_col_base as varchar)+') as C' + cast(apl.link_col_base as varchar) + '$ on res$.lsf = C' + cast(apl.link_col_base as varchar) + '$.link_sf and res$.link_table = C' + cast(apl.link_col_base as varchar) + '$'
		else ''
	end + 
	case
		when apl.tab_type = 0  and not exists (select * from dbo.report_forms where left(ltrim(code),7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col_base/* and [name] like 'Код%'*/)))
		then '.link_table and res$.link_row = C' + cast(apl.link_col_base as varchar) + '$.link_row '--and res.link_col = C' + cast(apl.link_col as varchar) + '.link_col '
		when apl.tab_type = 1 or exists (select * from dbo.report_forms where left(ltrim(code),7) LIKE '050307[45]' and link_form = (select link_form from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = apl.link_col_base/* and [name] like 'Код%'*/)))
		then '.link_table and res$.link_row = C' + cast(apl.link_col_base as varchar) + '$.code_row '--and res.link_col = C' + cast(apl.link_col as varchar) + '.link_col '
		else ''
	end
--select apl.link_col, apl.col_type, apl.tab_type
from #analitics_period_links as apl
--inner join (select period_type, min(period_number) as period_number, min(period_date) as period_date from #analitics_period group by period_type) as p
--on apl.period_type = p.period_type
--	and apl.period_date = p.period_date
-- 	and apl.period_number = p.period_number


where apl.link_col_base in (select cast(right(rtrim(aa.code),len(aa.code)-1) as int) from #analitics_ap as aa where aa.[type] = 1 /*and aa.visibility = 1*/ and code not in ('itog', 'formula'))
group by apl.link_col_base, apl.col_type, apl.tab_type
having apl.col_type = 1

select @cSqlJoinsAtr = @cSqlJoinsAtr + 'left join (select rav.str_val as str_val, rav.link_saved_form as link_sf from dbo.report_atribut_values as rav join dbo.report_saved_forms rsfa on rav.link_saved_form = rsfa.link_saved_form join dbo.report_forms rfa on rfa.link_form = rsfa.link_form where rav.code_atr = '''+dbo.RA_GETWORDNUM(aa.code,1,'|') + CASE WHEN CHARINDEX('|', aa.code) > 0 THEN ''' and rfa.code = ''' + dbo.RA_GETWORDNUM(aa.code,2,'|') ELSE '' END  + ''') as [' + aa.code + '$] on res$.lsf = [' + aa.code + '$].link_sf '
from #analitics_ap as aa
where aa.[type] = 2 --and aa.visibility = 1

--
--
--

set @col_an_str_group = '#'
set @row_an_str_group = '#'
set @col_an_str = '#'
set @row_an_str = '#'

-- #analitics_ap (nn, code, type, row_col, orders, itog, visibility)
select  -- формирование строк с АП и селект-листа
	@row_an_str_group = @row_an_str_group +
	case
		when aa.row_col = 0
		then QUOTENAME(aa.code) + '#'
		else ''
	end,
	@col_an_str_group = @col_an_str_group +
	case
		when aa.row_col = 1
		then QUOTENAME(aa.code) + '#'
		else ''
	end
from #analitics_ap as aa
where aa.visibility = 1
order by aa.nn

select  -- формирование строк с АП и селект-листа
	@row_an_str = @row_an_str +
	case
		when aa.row_col = 0
		then QUOTENAME(aa.code) + '#'
		else ''
	end,
	@col_an_str = @col_an_str +
	case
		when aa.row_col = 1
		then QUOTENAME(aa.code) + '#'
		else ''
	end,
	@cSqlSelect = @cSqlSelect +
		case when aa.[type] = 0 then 'res#.' else '' end +
		QUOTENAME(aa.code) +
		case when aa.[type] = 0 then '' else '#.str_val as ' + QUOTENAME(aa.code) end + ',',

	@cSqlGroupBy = @cSqlGroupBy + 
		case when aa.[type] = 0 then 'res.' else '' end +
		QUOTENAME(aa.code) +
		case when aa.[type] = 0 then '' else '.str_val ' end + ',',

	@cSqlWhere = @cSqlWhere +
		case when aa.[type] = 0 then 'res#.' + QUOTENAME(aa.code) + '=' else '' end +
		case when aa.[type] = 0 then 'res$.' + QUOTENAME(aa.code) else '' end +
		case when aa.[type] = 0 then '' else QUOTENAME(aa.code+'#')+'.str_val =' end + 
		case when aa.[type] = 0 then '' else QUOTENAME(aa.code+'$')+'.str_val' end + ' and ' 
from #analitics_ap as aa
where code not in ('itog', 'formula')
order by aa.nn

set @cSqlGroupBy = case when len(@cSqlGroupBy)>0 then left(@cSqlGroupBy,len(@cSqlGroupBy)-1) else '' end
set @cSqlWhere = case when len(@cSqlWhere)>3 then left(@cSqlWhere,len(@cSqlWhere)-3) else '' end

--print '@cSqlJoins: ' + @cSqlJoins
--print '-----------------'
--print '@cSqlJoinsAtr: ' + @cSqlJoinsAtr
--print '-----------------'
--print '@cSqlSelect: ' + @cSqlSelect
--print '-----------------'
--print '@cSqlWhere: ' + isnull(@cSqlWhere,'')

if @alt_summ = 1 begin -- если выбрана опция вывода данных за месяц(а не нарастающим итогом)
    set @cSqlSelect = replace(@cSqlSelect,'#','') + case when len(@cSqlGroupBy)>0 then '(sum(res.summa)-@@@) as summa' else '(res.summa - @@@) ' end--left(@cSqlSelect,len(@cSqlSelect)-1)
end
else begin
    set @cSqlSelect = replace(@cSqlSelect,'#','') + case when len(@cSqlGroupBy)>0 then 'sum(res.summa) as summa' else 'res.summa ' end--left(@cSqlSelect,len(@cSqlSelect)-1)
end
------------------------------------------------------
-- формирование таблицы #itog_params
exec DropTempTable '#itog_params'
create table #itog_params (nn int identity(1,1), IsItrow tinyint, ListLeft varchar(254), ListLeftDouble varchar(1000), [Name] varchar(50), RightPart varchar(254), OrderInList tinyint, itog tinyint, formula tinyint)
declare @nn int,
		@cListLeft varchar(500),
		@cListLeftDouble varchar(1500),
		@cRightPart varchar(500),
		@cItName varchar(254),
		@nItType tinyint,
		@nItOrders tinyint,
		@nItRowCol tinyint,
        @strRepl0 varchar(4000),
        @strRepl1 varchar(4000),
        @itog tinyint,
        @formula tinyint
		
set @cListLeft = ''
set @cListLeftDouble = ''
set @cRightPart = ''
set @cItName = ''
select @nn = max(nn) from #analitics_ap

-- select * from #analitics_ap
while @nn > 0 begin
	set @cListLeft = ''
	set @cListLeftDouble = ''
	set @cRightPart = ''
    set @cItName = ''
	if exists(select * from #analitics_ap where itog > 0 and nn = @nn) begin -- если текущий АП с пометкой Итог
		select @nItType = [type], @nItOrders = orders, @nItRowCol = row_col, @itog = itog from #analitics_ap where nn = @nn -- собираем его данные
		if exists(select * from #analitics_ap where orders > @nItOrders and row_col = @nItRowCol) begin -- если текущий АП не последний в списке
			if @nItType = 3 begin
                if isnull((select min(nn) from #analitics_ap where nn > @nn and row_col = @nItRowCol /* and visibility = 1*/ and code not in ('itog', 'formula')),-1) <> -1 begin
				    select @cItName = QUOTENAME(rtrim(code)), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap where nn = (select min(nn) from #analitics_ap where nn > @nn and row_col = @nItRowCol and code not in ('itog', 'formula') /*visibility = 1*/) 
				    select @cRightPart = @cRightPart + '''''' + ','
				    from #analitics_ap
				    where [type] < 3
					    and row_col = @nItRowCol
					    and orders > @nItOrders
					    and /*visibility = 1*/ code not in ('itog', 'formula')
				    order by nn

   			    set @cRightPart = case when len(@cRightPart)>0 then left(@cRightPart,len(@cRightPart)-1) else '' end

				    insert into #itog_params (IsItrow, ListLeft, ListLeftDouble, [Name], RightPart, OrderInList, itog, formula)
				    select case @nItRowCol when 1 then 0 else 1 end, '', '', @cItName, @cRightPart, @nItOrders, @itog, 0 where @cItName is not null and @cItName <> 'ERR'
                end
			end
			else begin
				select @cListLeft = @cListLeft + rtrim(code) + ',',
					   @cListLeftDouble = @cListLeftDouble + rtrim(code) + '=' + rtrim(code) + ','
				from #analitics_ap
				where [type] < 3
					and row_col = @nItRowCol
					and orders <= @nItOrders
					and /*visibility = 1*/ code not in ('itog', 'formula')
				order by nn

				set @cListLeft = case when len(@cListLeft)>0 then left(@cListLeft,len(@cListLeft)-1) else '' end
				set @cListLeftDouble = case when len(@cListLeftDouble)>0 then left(@cListLeftDouble,len(@cListLeftDouble)-1) else '' end

				--select @cItName = rtrim(code), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap where nn = @nn + 1
				select @cItName = QUOTENAME(rtrim(code)), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap where nn = (select min(nn) from #analitics_ap where nn > @nn and row_col = @nItRowCol and /*visibility = 1*/ code not in ('itog', 'formula')) 
				select @cRightPart = @cRightPart + '''''' + ','
				from #analitics_ap
				where [type] < 3
					and row_col = @nItRowCol
					and orders > @nItOrders
					and /*visibility = 1*/ code not in ('itog', 'formula')
				order by nn
				set @cRightPart = case when len(@cRightPart)>0 then left(@cRightPart,len(@cRightPart)-1) else '' end

				insert into #itog_params (IsItrow, ListLeft, ListLeftDouble, [Name], RightPart, OrderInList, itog, formula)
				select case @nItRowCol when 1 then 0 else 1 end, @cListLeft, @cListLeftDouble, @cItName, @cRightPart, @nItOrders, @itog,0 where @cItName is not null and len(@cItName) > 0
			end
		end
	end
	set @nn = @nn - 1
end


--
--костыль!
create table #analitics_ap1(nn int, code varchar(50), type tinyint, row_col tinyint, orders tinyint, itog tinyint, visibility tinyint, formula tinyint)
if COL_LENGTH('tempdb..#analitics_ap','formula') is null begin
set @strExcec = '
    insert into #analitics_ap1(nn, code, [type], row_col, orders, itog, visibility, formula)
    select nn, code, [type], row_col, orders, itog, visibility, 0 from #analitics_ap'
execute(@strExcec)
end
else begin
set @strExcec = '
    insert into #analitics_ap1(nn, code, [type], row_col, orders, itog, visibility, formula)
    select nn, code, [type], row_col, orders, itog, visibility, formula from #analitics_ap'
execute(@strExcec)
end

set @cListLeft = ''
set @cListLeftDouble = ''
set @cRightPart = ''
set @cItName = ''

select @nn = max(nn) from #analitics_ap1

while @nn > 0 begin
    set @cListLeft = ''
    set @cListLeftDouble = ''
    set @cRightPart = ''
    set @cItName = ''
    if exists(select * from #analitics_ap1 where formula > 0 and nn = @nn) begin -- если текущий АП с пометкой Итог
        select @nItType = [type], @nItOrders = orders, @nItRowCol = row_col, @itog = itog,@formula = formula from #analitics_ap1 where nn = @nn -- собираем его данные
/*
        print '----'
        print '@nItType = ' + cast(@nItType as varchar) 
        print '@nItOrders = ' + cast(@nItOrders as varchar) 
        print '@nItRowCol = ' + cast(@nItRowCol as varchar) 
        print '@itog = ' + cast(@itog as varchar) 
        print '@formula = ' + cast(@formula as varchar) 
        print '----'
*/
        if exists(select * from #analitics_ap1 where orders > @nItOrders and row_col = @nItRowCol) begin -- если текущий АП не последний в списке
	        if @nItType = 4 begin
                print 'глобальная итоговая строчка'
                if isnull((select min(nn) from #analitics_ap1 where nn > @nn and row_col = @nItRowCol and /*visibility = 1*/ code not in ('itog', 'formula')),-1) <> -1 begin
		            select @cItName = QUOTENAME(rtrim(code)), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap1 where nn = (select min(nn) from #analitics_ap1 where nn > @nn and row_col = @nItRowCol and /*visibility = 1*/ code not in ('itog', 'formula')) 
		            select @cRightPart = @cRightPart + '''''' + ','
		            from #analitics_ap1
		            where [type] < 3
			            and row_col = @nItRowCol
			            and orders > @nItOrders
			            and /*visibility = 1*/ code not in ('itog', 'formula')
		            order by nn
		            set @cRightPart = case when len(@cRightPart)>0 then left(@cRightPart,len(@cRightPart)-1) else '' end

		            insert into #itog_params (IsItrow, ListLeft, ListLeftDouble, [Name], RightPart, OrderInList, itog, formula)
		            select case @nItRowCol when 1 then 0 else 1 end, '', '', @cItName, @cRightPart, @nItOrders, 0, @formula where @cItName is not null and @cItName <> 'ERR'
                end
	        end
            else begin
                --print 'очередная итоговая строчка'
	            select @cListLeft = @cListLeft + rtrim(code) + ',',
		               @cListLeftDouble = @cListLeftDouble + rtrim(code) + '=' + rtrim(code) + ','
	            from #analitics_ap1
	            where [type] < 3
		            and row_col = @nItRowCol
		            and orders <= @nItOrders
		            and /*visibility = 1*/ code not in ('itog', 'formula')
	            order by nn
	            set @cListLeft = case when len(@cListLeft)>0 then left(@cListLeft,len(@cListLeft)-1) else '' end
	            set @cListLeftDouble = case when len(@cListLeftDouble)>0 then left(@cListLeftDouble,len(@cListLeftDouble)-1) else '' end
                --print '@cListLeft = ' + @cListLeft
	            --select @cItName = rtrim(code), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap1 where nn = @nn + 1
	            select @cItName = QUOTENAME(rtrim(code)), @nItOrders = orders, @nItRowCol = row_col from #analitics_ap1 where nn = (select min(nn) from #analitics_ap1 where nn > @nn and row_col = @nItRowCol and /*visibility = 1*/ code not in ('itog', 'formula')) 
                
	            select @cRightPart = @cRightPart + '''''' + ','
	            from #analitics_ap1
	            where [type] < 3
		            and row_col = @nItRowCol
		            and orders > @nItOrders
		            and /*visibility = 1*/ code not in ('itog', 'formula')
	            order by nn
	            set @cRightPart = case when len(@cRightPart)>0 then left(@cRightPart,len(@cRightPart)-1) else '' end

	            insert into #itog_params (IsItrow, ListLeft, ListLeftDouble, [Name], RightPart, OrderInList, itog, formula)
	            select case @nItRowCol when 1 then 0 else 1 end, @cListLeft, @cListLeftDouble, @cItName, @cRightPart, @nItOrders, 0, @formula where @cItName is not null and len(@cItName) > 0
	        end
        end
    end
    set @nn = @nn - 1
end

--select * from #itog_params
--return
---------------------------------------------------------------------------------------------------------
if @alt_summ = 1 begin -- если выбрана опция вывода данных за месяц(а не нарастающим итогом)
    set @strExcec = 'select min(res.nn) as nn, '+replace(@cSqlSelect,'#','')+' from #restab as res ' + replace(@cSqlJoins,'$','') + replace(@cSqlJoinsAtr,'$','') + case when len(@cSqlGroupBy)>0 then 'group by '+@cSqlGroupBy else '' END
    
    set @strRepl0 = 'isnull((
    select sum(res0.summa)
    from #restab as res0
    '+replace(@cSqlJoins,'$','0')+'
    '+replace(@cSqlJoinsAtr,'$','0')+'
    where '+replace(replace(replace(@cSqlWhere,'res$.[PERIOD]','(&&&)'),'$',''),'#','0')+'
),0.0)'
    set @strRepl1 = '
    select MAX(res1.PERIOD)
    from #restab as res1
    '+replace(@cSqlJoins,'$','1')+'
    '+replace(@cSqlJoinsAtr,'$','1')+'
    where '+replace(replace(replace(@cSqlWhere,'=res$.[PERIOD]','<res$.[PERIOD]'),'$',''),'#','1')+'
'
    set @strExcec = replace(@strExcec,'@@@',replace(@strRepl0,'&&&',@strRepl1))
end
else begin
    set @strExcec = 'select min(res.nn) as nn, '+replace(@cSqlSelect,'#','')+' from #restab as res ' + replace(@cSqlJoins,'$','') + replace(@cSqlJoinsAtr,'$','') + case when len(@cSqlGroupBy)>0 then 'group by '+@cSqlGroupBy else '' end --- для временной было INSERT INTO dbo.drop_me_in_february_please
end

--print @strExcec
--execute(@strExcec)
--return
--select * from #restab
select @res_set_num = count(*) from #restab
if (len(left(@col_an_str,len(@col_an_str)-1))= 0 and len(left(@col_an_str,len(@row_an_str)-1))= 0) or @res_set_num = 0 BEGIN -- в случае когда обе строчки пустые или результирующая таблица пуста, т.е. ап не заданы
	-- предупреждаем, что выдаём весь набор
	set @j = (@res_set_num / 65534) + case when (@res_set_num % 65534) > 0 then 1 else 0 end
	select 0 as res, null as col_num, null as col_set, null as col_lists, null as row_num, null as row_set, null as row_lists, @j as [count], @j as lists
	-- и выдаём его
	set @i = 1
	while @i !> @j begin
		set @strWhere = ' res.nn between ' + cast((((@i-1) * 65534)+1) as varchar(30)) + ' and ' + cast((@i * 65534) as varchar(30))
		set @strExcec = 'select 
			res.form as форма,
			res.tab as таблица,
			res.col as колонка,
			(select formula from dbo.report_formula where link_col = (select link_code_col from #report_tables where link_table = res.link_table) and link_row = cast(res.link_row as int)) as боковик,
			res.budg as код_бюджета,
			res.bud_type as бюджет,
			res.dep as код_организации,
			res.name_dep as организация,
			substring(res.period,9,30) as период,
			res.summa as сумма
		from #restab as res
		where 0 = (select val_type from #report_tables where link_table = res.link_table) and '+@strWhere+'
		union
		select 
			res.form as форма,
			res.tab as таблица,
			res.col as колонка,
			res.link_row as боковик,
			res.budg as код_бюджета,
			res.bud_type as бюджет,
			res.dep as код_организации,
			res.name_dep as организация,
			substring(res.period,9,30) as период,
			res.summa as сумма
		from #restab as res
		where 1 = (select val_type from #report_tables where link_table = res.link_table) and '+@strWhere+'' 
		--print @strExcec + @strWhere
      execute(@strExcec)
      SELECT @strExcec
		set @i = @i + 1
	end
end
---------------------------------------------------------------------------------------------------------
else begin -- иначе запускаем процедуру генерации сводной таблицы
    if @to_cube > 0 begin
        if @res_set_num >0 BEGIN
            exec RT_SAVE_DATA_TO_CUBE @strExcec, @nLink_Up
        end    
    end
    else begin
        set @strExcec = replace(@strExcec,'min(res.nn) as nn,','')
    
       exec RT_PIVOT_TABLE @col_an_str, @row_an_str, @strExcec, @hg, @bWeb, 0, @col_an_str_group, @row_an_str_group/*0 - новая выборка; 1 - старая выборкаии*/ --, @cProgressTable
    end
end

exec DropTempTable '#report_forms'
exec DropTempTable '#report_tables'
exec DropTempTable '#report_coloumns'
exec DropTempTable '#report_rows'
exec DropTempTable '#report_formula'
exec DropTempTable '#report_string'
exec DropTempTable '#report_summa'
exec DropTempTable '#report_dinamics'
exec DropTempTable '#organizationen_link'
exec DropTempTable '#report_static_table'
exec DropTempTable '#report_dynamic_table'
exec DropTempTable '#analitics_period_links'
exec DropTempTable '#analitics_filters_col'
exec DropTempTable '#analitics_filters_col_ext'
exec DropTempTable '#analitics_filters_col_ext1'
exec DropTempTable '#restab'
exec DropTempTable '#sf'
exec DropTempTable '#itog_params'
exec DropTempTable '#analitics_period'
exec DropTempTable '#tree_link'
---------------------------------------------------------------------------------------------------------------------------------------------------------
if isnull(@cProgressTable,'')<>'' begin
set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Передача данных на клиент'', percents = 100'
execute(@strProgressExec)
end

GO
grant execute on [dbo].[RT_REPORT_ANALITICS] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO
SET LOCK_TIMEOUT 30000
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_585]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_585]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_585]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

--перенос формы из архивной базы
EXEC dbo.[RN_MOVE_FORM_FROM_ARH] @iLINK_SAVED_FORM

declare @iReturn int, @vcVersion varchar(100), @subjectCode varchar(100), @subjectName varchar(254), @dBEGIN_DATE datetime, @cDate varchar(10),
	 @vcFILE_NAME_ARH varchar(100), @iLINK_TABLE int, @iLINK_FORM int, @vcExec varchar(8000), @NameOrg varchar(254), @NameBudg varchar(254), @LinkOrg int, @ExportCodeForm varchar(10), @strKS varchar(8000), @KS INT, @cDateSign varchar(8),
    @ID VARCHAR(100), @cDateCreate VARCHAR(30)
    
SET @cDateCreate = LEFT(CONVERT(VARCHAR(30), GETDATE(), 126),19)    
    
SET @ID = replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '')

DECLARE @tabXML TABLE ([TXT]	  VARCHAR(8000),
							  [ORDERS] INT IDENTITY(1,1))

DECLARE @tabXML1 TABLE ([TXT]	  VARCHAR(8000),
							  [ORDERS] INT IDENTITY(1,1))

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

select @subjectCode = RTRIM(subject_Code), @subjectName = RTRIM(Subject_Name) from dbo.I_REPORT_OPTIONS_EXPORT

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL
BEGIN
   SELECT @vcVersion = [VERSION]
   FROM #tabExportOutput 
END

SELECT  @iLINK_FORM = RSF.Link_Form, @LinkOrg = Link_Organization, @dBEGIN_DATE = [BEGIN_DATE], @NameOrg = isnull(LEFT(RTRIM(dbo.GetDepName(Link_Organization, begin_date)),250),''), @NameBudg = isnull(LEFT(isnull(RTRIM(B.Name),''),250),'')
FROM dbo.[REPORT_SAVED_FORMS] RSF left join kl_budg_type B on RSF.Link_Type_Svod = B.Link
	left join dictionary_department D on D.Link = RSF.Link_Organization
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

set @cDate = convert(varchar(10), @dBEGIN_DATE+1, 4)
SET @cDateSign =convert(varchar(8),  isnull((SELECT MAX(rs.[date]) FROM dbo.[REPORT_SIGN] rs WHERE rs.[lsf] = @iLINK_SAVED_FORM), GETDATE()), 4)

set @KS = 0
set @strKS = ''
SET @ExportCodeForm = '585'

SELECT @vcFILE_NAME =  @ID + '.xml',
	   @vcFILE_NAME_ARH = @ID + '.zip'

-- Заполнение шапки пакета.
EXEC dbo.[ВЕРСИЯ] @vcVersion OUTPUT, 0
INSERT @tabXML([TXT]) VALUES ('<?xml version="1.0" encoding="windows-1251"?>')
INSERT @tabXML([TXT]) VALUES ('<PacketED SoftWareProduct="Свод-КС" SoftWareProductVersion="' + REPLACE(@vcVersion,'Версия ','') + '" FormatVersion="2012.04">')
INSERT @tabXML([TXT]) VALUES ('	<From Name="' + LEFT(dbo.[RA_XML_MASK](@subjectName),250) + '" CodeReg="'+LEFT(dbo.[RA_XML_MASK](@subjectCode),2)+'"/>')
INSERT @tabXML([TXT]) VALUES ('	<To Name="Минфин России" Code="092"/>')
INSERT @tabXML([TXT]) VALUES ('	<Inf Name="Отчет об осуществлении расходов бюджета субъекта Российской Федерации, источником софинансирования которых являются субсидии из федерального бюджета бюджетам субъектов Российской Федерации на обеспечение жилыми помещениями детей-сирот, детей, оставшихся без попечения родителей, а также детей, находящихся под опекой (попечительством), не имеющих закрепленного жилого помещения, а также о достижении значений показателей результативности предоставления субсидий" Code="' + @ExportCodeForm + '"/>')
INSERT @tabXML([TXT]) VALUES ('	<DateRegl>'+@cDate+'</DateRegl>')
INSERT @tabXML([TXT]) VALUES ('	<Period>Квартальная</Period>')
INSERT @tabXML([TXT]) VALUES ('	<EI>тыс.руб.</EI>')

INSERT @tabXML([TXT]) VALUES ('	<ED01>') -- первый раздел

set @strKS = @strKS + @cDate -- вычисление контрольного числа

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 1

CREATE TABLE #table1 ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),
								         		      [COL1] varchar(254),[COL2] varchar(254),[COL3] NUMERIC(20,2),[COL4] NUMERIC(20,2), ITOG int)

SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 

print @vcExec
insert #table1 execute(@vcExec)

INSERT @tabXML([TXT])
SELECT '    <Str01 KodStr="' + RTRIM(COL2) + '" SumQuarter="' + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3,20,2))) END  + '" SumGen="' + CASE WHEN COL4 = 0 then '' ELSE RTRIM(LTRIM(STR(COL4,20,2))) END  + '" />
' 
from #table1
where del = 0 AND COL2 <> ''
order by orders

select @strKS = @strKS + RTRIM(COL2) + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3,20,2))) END + CASE WHEN COL4 = 0 then '' ELSE RTRIM(LTRIM(STR(COL4,20,2))) END
from #table1
where del = 0 AND COL2 <> ''
order by orders

INSERT @tabXML([TXT]) VALUES ('	</ED01>') -- конец первого раздела
INSERT @tabXML([TXT]) VALUES ('	<ED02>') -- второй раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 2

CREATE TABLE #table2 ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),
								         		      [COL1] varchar(254),[COL2] varchar(254),[COL3] NUMERIC(20,2),[COL4] NUMERIC(20,2), ITOG int)

SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 

print @vcExec
insert #table2 execute(@vcExec)

INSERT @tabXML([TXT])
SELECT '    <Str02 KodStr="' + RTRIM(COL2) + '" PeopleQuarter="' + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3))) END + '" PeopleGen="' + CASE WHEN COL4 = 0 then '' ELSE RTRIM(LTRIM(STR(COL4))) END + '" /> 
'
from #table2
where del = 0 AND COL2 <> ''
order by orders

select @strKS = @strKS + RTRIM(COL2) + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3))) END + CASE WHEN COL3 = 4 then '' ELSE RTRIM(LTRIM(STR(COL4))) END
from #table2
where del = 0 AND COL2 <> ''
order by orders

INSERT @tabXML([TXT]) VALUES ('	</ED02>') -- конец первого раздела
INSERT @tabXML([TXT]) VALUES ('	<ED03>') -- второй раздел

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 3

CREATE TABLE #table3 ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),
								         		      [COL1] varchar(254),[COL2] varchar(254),[COL3] NUMERIC(20,2),[COL4] NUMERIC(20,2), ITOG int)

SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 

print @vcExec
insert #table3 execute(@vcExec)

INSERT @tabXML([TXT])
SELECT '    <Str03 KodStr="' + RTRIM(COL2) + '" SoglPeople="' + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3))) END + '" Effect="' + CASE WHEN COL4 = 0 then '' ELSE RTRIM(LTRIM(STR(COL4,20,2))) END + '" /> 
'
from #table3
where del = 0 AND COL2 <> ''
order by orders

select @strKS = @strKS + RTRIM(COL2) + CASE WHEN COL3 = 0 then '' ELSE RTRIM(LTRIM(STR(COL3))) END + CASE WHEN COL4 = 0 then '' ELSE RTRIM(LTRIM(STR(COL4,20,2))) END
from #table3
where del = 0 AND COL2 <> ''
order by orders

INSERT @tabXML([TXT]) VALUES ('	</ED03>') -- конец первого раздела
INSERT @tabXML([TXT]) VALUES ('	<ED04>') -- второй раздел


SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 4
      
CREATE TABLE #table4 ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] VARCHAR(50),
								         		      [COL1] varchar(254),[COL2] varchar(8000),[COL3] VARCHAR(50), ITOG int)

SELECT @vcExec = 'EXEC dbo.[RI_PROC_T' + LTRIM(STR(@iLINK_TABLE)) + '] @DEL_FCOL=1, @bDeleteEmptyRows = 1, @varKSLSF=' + LTRIM(STR(@iLINK_SAVED_FORM)) 

print @vcExec
insert #table4 execute(@vcExec)


INSERT @tabXML([TXT])
SELECT '		<Str04_01 NumStr="01" ChiefPost="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(CHIEF_POST,'')),250)) 
         + '" ChiefFio="' + RTRIM(dbo.[RA_XML_MASK](LEFT(ISNULL(CHIEF,''),250))) 
         + '" GlBuxFio="' + RTRIM(dbo.[RA_XML_MASK](LEFT(ISNULL(GLBUH,''),250))) 
         + '" ExecutorPost="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(POST,'')),250)) 
         + '" ExecutorFio="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(FIO,'')),250)) 
         + '" ExecutorPhone="' + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(PHONES,'')),15)) 
         + '" Comment=" ' + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '08'),''),1000)))
         + '" OrgName="' +  dbo.[RA_XML_MASK](RTRIM(isnull((SELECT COL2 FROM #table4 WHERE CODE = '01'),'')))         
         + '" BudName="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '04'),''),250)))
         + '" OKPO="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '02'),''),8)))
         + '" Glava="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '03'),''),3)))
         + '" OKATO="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '05'),''),11)))
         + '" SoglNum="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '07'),''),50)))
         + '" SoglDate="' +  dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '06'),''),10)))
         + '" DtSigning="' + @cDateSign + '" /> '
FROM dbo.[PrintDoc_GetDepData2](@LinkOrg) P full join dbo.[RA_GET_USER_INFO](NULL) U on 1 = 1

select @strKS = @strKS + '01' 
         + RTRIM(dbo.[RA_XML_MASK](LEFT(ISNULL(CHIEF,''),250))) 
         + RTRIM(dbo.[RA_XML_MASK](LEFT(ISNULL(GLBUH,''),250))) 
         + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(POST,'')),250)) 
         + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(FIO,'')),250)) 
         + dbo.[RA_XML_MASK](LEFT(RTRIM(isnull(PHONES,'')),15)) 
         + dbo.[RA_XML_MASK](RTRIM(isnull((SELECT COL2 FROM #table4 WHERE CODE = '01'),'')))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '02'),''),8)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '03'),''),3)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '04'),''),250)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '05'),''),11)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '06'),''),50)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '07'),''),10)))
         + dbo.[RA_XML_MASK](RTRIM(LEFT(isnull((SELECT COL2 FROM #table4 WHERE CODE = '08'),''),1000)))
FROM dbo.[PrintDoc_GetDepData2](@LinkOrg) P full join dbo.[RA_GET_USER_INFO](NULL) U on 1 = 1
 

set @KS = dbo.[RA_GET_CRC](@strKS, @KS)
set @strKS = LTRIM(RTRIM(STR(@KS)))
set @KS = dbo.[RA_GET_CRC](@strKS, 0)

INSERT @tabXML([TXT]) VALUES ('		<Str04_02 NumStr="02" KsOtch="' + LTRIM(RTRIM(STR(@KS))) + '" />')

INSERT @tabXML([TXT]) VALUES ('	</ED04>') -- конец шестого раздела
INSERT @tabXML([TXT]) VALUES ('</PacketED>')

INSERT @tabXML1(TXT)
VALUES('<?xml version="1.0" encoding="windows-1251"?>')
INSERT @tabXML1(TXT)
VALUES('<Package MF_FormType="784D5E6589394354AC41A7A45D118A19">')
INSERT @tabXML1(TXT)
VALUES('<Properties MF_PackageType="27E97A84479941A8988EF84CFCF8C276" MF_PackageSubType="1" LibVersion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '" InDateReg="1899-12-30T00:00:00" OutDateReg="1899-12-30T00:00:00">')
INSERT @tabXML1(TXT)
VALUES('<PropertyList>')
INSERT @tabXML1(TXT)
VALUES('<Property Name="CodeReg" Value="'+LEFT(dbo.[RA_XML_MASK](@subjectCode),2)+'"/>')
INSERT @tabXML1(TXT)
VALUES('<Property Name="DateRegl" Value="'+@cDate+'"/>')
INSERT @tabXML1(TXT)
VALUES('<Property Name="CodeFrm" Value="585"/>')
INSERT @tabXML1(TXT)
VALUES('</PropertyList>')
INSERT @tabXML1(TXT)
VALUES('</Properties>')
INSERT @tabXML1(TXT)
VALUES('<MF_Body>')
INSERT @tabXML1(TXT)
VALUES('<MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('<MF_ID>' + @ID + '</MF_ID>')
INSERT @tabXML1(TXT)
VALUES('<MF_BODY>')
INSERT @tabXML1(TXT)
VALUES('<!--Отчет по форме 585-->')
INSERT @tabXML1(TXT)
VALUES('<Document MF_FormType="9FB9832A5AE6438B9426AA23B0DF12B3">')
INSERT @tabXML1(TXT)
VALUES('<Properties MF_DocumentType="78E7362C01CF4C659A31E2AEE1DB92DF " MF_DocumentSubType="1" LibVersion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '">')
INSERT @tabXML1(TXT)
VALUES('</Properties>')
INSERT @tabXML1(TXT)
VALUES(' <MF_Body MF_FormatData=".xml" MF_StoreFormat="2">')
INSERT @tabXML1(TXT)
VALUES('<MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('<MF_ID>' + replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '') + '</MF_ID>')
INSERT @tabXML1(TXT)
VALUES('<MF_BODY>#DEL13#')

INSERT @tabXML1(TXT)
SELECT dbo.RO_STR_ASCII_16(TXT)  + '#DEL13#' 
FROM @tabXML



INSERT @tabXML1(TXT)
VALUES('</MF_BODY>')
INSERT @tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('</MF_Body>')
INSERT @tabXML1(TXT)
VALUES('</Document>')
INSERT @tabXML1(TXT)
VALUES('<!-- Пояснительная записка к отчету по форме 585-->')
INSERT @tabXML1(TXT)
VALUES('<Document MF_FormType="9FB9832A5AE6438B9426AA23B0DF12B3">')
INSERT @tabXML1(TXT)
VALUES('<Properties MF_DocumentType="84E5CD1C64704162A436A67A1C408E2A" MF_DocumentSubType="1" LibVer-sion="1" FormatVersion="1" DateCreate="' + @cDateCreate + '">')
INSERT @tabXML1(TXT)
VALUES('</Properties>')
INSERT @tabXML1(TXT)
VALUES(' <MF_Body MF_FormatData=".doc" MF_StoreFormat="2">')
INSERT @tabXML1(TXT)
VALUES('  <MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('   <MF_ID>' + replace(replace(replace(convert(varchar(100), newid()), '-', ''), '{',  '' ), '}', '') + '</MF_ID>')
INSERT @tabXML1(TXT)
VALUES('   <MF_BODY></MF_BODY>')
INSERT @tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('</MF_Body>')
INSERT @tabXML1(TXT)
VALUES('</Document>')
INSERT @tabXML1(TXT)
VALUES('</MF_BODY>')
INSERT @tabXML1(TXT)
VALUES('</MF_SignaturePart>')
INSERT @tabXML1(TXT)
VALUES('</MF_Body>')
INSERT @tabXML1(TXT)
VALUES('</Package>')



INSERT #FileExportReport([TXT],
                         [NameFile],
                         [ORDERS],
                         [NameFileArh])
SELECT [TXT],
	    @vcFILE_NAME,
	    [ORDERS],
       @vcFILE_NAME_ARH
FROM @tabXML1
ORDER BY [ORDERS]

drop table #table1
drop table #table2
drop table #table3
drop table #table4

GO
GRANT ALL ON dbo.[RO_EXPORT_FORM_585] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
		  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_DEL_DOCUMENT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_DEL_DOCUMENT]

GO




CREATE   PROCEDURE [dbo].DP_DEL_DOCUMENT 
  @Link    INT,
  @Mode  INT= 0
AS

DECLARE @ErrMessage  VARCHAR(255),
        @UserRef     INT,
        @DelLinks    CURSOR,
        @CurLink      INT

SELECT @UserRef = USER_REF FROM WHO_IS_WHO WHERE SID = SUSER_SID()

IF @Mode = 0
       -- режим удаления права на документ
       EXEC DP_DEL_REC_ACCESS @Link,@UserRef
ELSE
BEGIN
       -- режим удаления документа из БД
       IF 0 < (SELECT COUNT(*) FROM DOCUMENTS_REF WHERE REF_UP = @Link)
       BEGIN
              SELECT @ErrMessage = 'Невозможно удалить документ, потому что на него ссылаются другие документы'
              RAISERROR (@ErrMessage,11,1)
              RETURN
       END
       ELSE
       BEGIN	
              ------- Запись в журнал событий --------------------
              DECLARE @Auth      VARCHAR(30),
                      @DocRegNum VARCHAR(15),
                      @DocName   VARCHAR(100),
                      @CurInfStr VARCHAR(254)
			
              SELECT @Auth = dbo.sd_GetEmplName(@UserRef)
              SELECT @DocName = NAME FROM DOCUMENTS WHERE LINK = @Link

              -- Формируем информационную строку
              SET @CurInfStr = 'Пользователь ' + LTRIM(RTRIM(@Auth)) +' удалил документ "'+  LTRIM(RTRIM(@DocName)) 
               EXECUTE  WF_GENERATEEVENT 'Удаление документа',@CurInfStr, NULL, 'DOCUMENTS'
              ---------------------------------------------------------------------
	
              DELETE FROM DOCUMENTS WHERE LINK = @Link
       END
       
       IF NOT (dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
		OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
			IF NOT EXISTS (SELECT * FROM dbo.DOCUMENTS WHERE LINK = @Link)	
				AND EXISTS (SELECT * FROM dbo.EOS_JURNAL WHERE INOUT = 0 AND TYPE_M = 1 AND LINK_DOC = @Link)
			EXEC dbo.EOS_EXPORT_REPORT @Link
       
END





GO


GRANT EXECUTE ON dbo.[DP_DEL_DOCUMENT] 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_get_name_spr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ro_get_name_spr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[ro_get_name_spr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [ro_get_name_spr]
GO

/*
	(для автозаполняемых справочников, а также для подитогов)

	для поля Where поля, которые относятся к обновляемой таблице нужно начинать с T.
	поля, относящиеся к справочнику нужно начинать с SPR.
*/
CREATE PROCEDURE dbo.[ro_get_name_spr] 
	@varKSiLT int, -- линк таблицы
	@varKScRule varchar(1000),  -- правило откуда брать наименование из каких спрвочников, которые подключены к колонкам таблицы
	@varKScNameTable varchar(100), -- где делаем update поля Name для данного поля Code
	@varKScNameCode varchar(100) = 'CODE', -- наименования поля, содержащего Код
	@varKScNameName varchar(100) = 'Name', -- наименование поля, содержащего Наименование
	@varKSCWhere varchar(1000) = '', -- поле Where, чтобы не все обновлялось для постоянных таблиц
   @varKSiLSF     int  = NULL             -- ид отчета
as
PRINT 'ro_get_name_spr'
	declare @rule_one varchar(250), @rule_count tinyint, @i int, @val varchar(250), @col_one varchar(250),@code_one varchar(250), @dict varchar(100), @RunStr varchar(8000), @nol_one varchar(50),
		@lenName int, @dict_where varchar(1000), @link_org int, @link_budg INT, @vcDate VARCHAR(10)
	if left(@varKScNameTable, 1) = '#'
		set @lenName = COL_LENGTH('tempdb..'+ @varKScNameTable,@varKScNameName)
	else
		set @lenName = COL_LENGTH(@varKScNameTable,@varKScNameName)
	set @rule_count = dbo.RN_GETWORDCOUNT(@varKScRule, '#')
	set @i = 1
	while @i <= @rule_count
	begin
		set @rule_one = dbo.RN_GETWORDNUM(@varKScRule, @i, '#')
		set @i = @i + 1
		set @col_one = dbo.RN_GETWORDNUM(@rule_one, 1, '=')
		set @code_one = dbo.RN_GETWORDNUM(@rule_one, 2, '=')
		set @nol_one = dbo.RN_GETWORDNUM(@rule_one, 3, '=')

		if charindex('COL', @col_one) <> 0 or charindex('ITOG', @col_one) = 1
      begin
  		 select @dict = dictionary, @dict_where = isnull(dictionary_where, '') from report_coloumns where Link_Table  = @varKSiLT and orders = convert(int, replace(replace(@col_one,'COL',''),'ITOG',''))
         select @link_org = link_organization, @link_budg = link_type_svod, @vcDate = convert(varchar(10), BEGIN_date, 112)  
         from dbo.report_saved_forms where link_saved_form = @varKSiLSF
         
         IF COL_LENGTH(@dict, 'begin_date') IS NOT NULL
         set @dict_where = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@dict_where, '%link_org%', ltrim(str(isnull(@link_org,0)))), '%link_budg%', ltrim(str(isnull(@link_budg,0)))), '(link', '(SPR.link'), 'begin_date', 'begin_date'), 'end_date', 'end_date'), '%date%', '''' + @vcDate + '''')
         ELSE
         set @dict_where = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@dict_where, '%link_org%', ltrim(str(isnull(@link_org,0)))), '%link_budg%', ltrim(str(isnull(@link_budg,0)))), '(link', '(SPR.link'), 'begin_date', '%date%'), 'end_date', '%date%'), '%date%', '''' + @vcDate + '''')   

      end
		ELSE
            begin 
			   select @dict = @col_one
               set @dict_where = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@dict_where, '%link_org%', ltrim(str(isnull(@link_org,0)))), '%link_budg%', ltrim(str(isnull(@link_budg,0)))), '(link', '(SPR.link'), 'begin_date', '%date%'), 'end_date', '%date%'), '%date%', '''' + @vcDate + '''')            
            END 
--select @dict , @dict_where
		if charindex('ITOG', @col_one) = 1
      BEGIN 
			set @RunStr = 'update ' + rtrim(@varKScNameTable) + ' set ' + rtrim(@varKScNameName) + ' = ''Итог по '' + SPR.Code from ' + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' + case when isnull(@varKSCWhere,'') <> '' then ' and (' + isnull(@varKSCWhere, '') + ')' else '' END
      END          
		ELSE BEGIN
         SET @RunStr = ''
         IF @varKScNameTable LIKE '%report_kbk%' AND COL_LENGTH(@dict, 'begin_date') IS NOT NULL AND @varKScNameName = 'NAME'
         BEGIN                                 
            set @RunStr = 'UPDATE dbo.[REPORT_KBK_HIST] '
                        + ' SET  NAME =  left(SPR.Name, 250)'
                        + ' from '  + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR'
                        + ' where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) 
                                 + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' 
                                 + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' 
                                 + case when isnull(@varKSCWhere,'') <> '' 
                                          then ' and (' + isnull(@varKSCWhere, '') + ')' else '' end 
                                + case when @dict_where <> '' then ' and (' + @dict_where + ')' else '' END
                        + ' and T.link = [REPORT_KBK_HIST].link_up and SPR.begin_date = [REPORT_KBK_HIST].[DATE]'                        
                        + ' INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])'
                        + ' select T.link, SPR.begin_date, max(left(SPR.Name, 250)), '''''
                        + ' from '  + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR'
                        + ' where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) 
                                 + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' 
                                 + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' 
                                 + case when isnull(@varKSCWhere,'') <> '' 
                                          then ' and (' + isnull(@varKSCWhere, '') + ')' else '' end 
                                + case when @dict_where <> '' then ' and (' + @dict_where + ')' else '' END
                        + ' and not exists(select * from  dbo.[REPORT_KBK_HIST] H where H.link_up =  T.link and H.date = SPR.begin_date)'
                        + ' group by T.link, SPR.begin_date'
         END                                   

         IF @varKScNameTable LIKE '%report_kbk%' AND COL_LENGTH(@dict, 'begin_date') IS NOT NULL AND @varKScNameName = 'LONG_NAME'
         BEGIN                                 
            set @RunStr = 'UPDATE dbo.[REPORT_KBK_HIST] '
                        + ' SET  LONG_NAME =  SPR.Name'
                        + ' from '  + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR'
                        + ' where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) 
                                 + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' 
                                 + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' 
                                 + case when isnull(@varKSCWhere,'') <> '' 
                                          then ' and (' + isnull(@varKSCWhere, '') + ')' else '' end 
                                + case when @dict_where <> '' then ' and (' + @dict_where + ')' else '' END
                        + ' and T.link = [REPORT_KBK_HIST].link_up and SPR.begin_date = [REPORT_KBK_HIST].[DATE]'                        
                        + ' INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])'
                        + ' select T.link, SPR.begin_date, '''', max(SPR.Name) '
                        + ' from '  + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR'
                        + ' where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) 
                                 + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' 
                                 + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' 
                                 + case when isnull(@varKSCWhere,'') <> '' 
                                          then ' and (' + isnull(@varKSCWhere, '') + ')' else '' end 
                                + case when @dict_where <> '' then ' and (' + @dict_where + ')' else '' END
                        + ' and not exists(select * from  dbo.[REPORT_KBK_HIST] H where H.link_up =  T.link and H.date = SPR.begin_date)'
                        + ' group by T.link, SPR.begin_date'
         END                                   

			set @RunStr = @RunStr + ' update ' + rtrim(@varKScNameTable) 
                        + ' set ' + rtrim(@varKScNameName) +  ' = LEFT(SPR.Name,' + LTRIM(STR(isnull(@lenName,250))) + ')'
                        + ' from '  + rtrim(@varKScNameTable) + ' T,' + rtrim(@dict) + ' SPR'
                        + ' where SPR.Code = ' + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) 
                                 + ' and isnull(T.' + @varKScNameName + ','''') = '''' and ' 
                                 + REPLACE(@code_one,@varKScNameCode,'T.' + @varKScNameCode) + ' <> ''' + @nol_one + '''' 
                                 + case when isnull(@varKSCWhere,'') <> '' 
                                          then ' and (' + isnull(@varKSCWhere, '') + ')' else '' end 
                                + case when @dict_where <> '' then ' and (' + @dict_where + ')' else '' END
      END    
--print @RunStr
      execute(@RunStr)
	end

/*
		--найдем форму
		declare @val varchar(250)
		set @val=''
		set @code=rtrim(@code)

		if @code_form in ('0503117G','0503117M') and substring(@code,1,17)='79000000000000000'
			begin
				set @val='Результат исполнения бюджета (дефицит / профицит)'
				return @val
			end

		if @code_form in ('0503117G','0503117M') and substring(@code,1,17)='96000000000000000'
			begin
				set @val='Расходы - всего'
				return @val
			end

		if @code_form='0503117G' and substring(@code,3,15)='000000000000000'
			begin
				select @val=name from RN_VIEW_KBK_PODRAZ_G where code=substring(@code,1,4)
				return @val
			end
		if @code_form='0503117G' and substring(@code,5,13)='0000000000000'
			begin
				select @val=name from RN_VIEW_KBK_PODRAZ_G where code=substring(@code,1,4)	
				return @val
			end
		if @code_form='0503117G' and substring(@code,8,10)='0000000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_G where code=substring(@code,5,7)
				return @val
			end

		if @code_form='0503117G' and substring(@code,10,8)='00000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_G where code=substring(@code,5,7)
				return @val
			end
		if @code_form='0503117G' and substring(@code,12,6)='000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_G where code=substring(@code,5,7)
				return @val
			end
		if @code_form='0503117G' and substring(@code,15,3)='000'
			begin
				select @val=name from RN_VIEW_KBK_VR_G  where code=substring(@code,12,3)
				return @val
			end

		if @code_form='0503117M' and substring(@code,3,15)='000000000000000'
			begin
				select @val=name from RN_VIEW_KBK_PODRAZ_M where code=substring(@code,1,4)
				return @val
			end
		if @code_form='0503117M' and substring(@code,5,13)='0000000000000'
			begin
				select @val=name from RN_VIEW_KBK_PODRAZ_M where code=substring(@code,1,4)	
				return @val
			end
		if @code_form='0503117M' and substring(@code,8,10)='0000000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_M where code=substring(@code,5,7)
				return @val
			end
		if @code_form='0503117M' and substring(@code,10,8)='00000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_M where code=substring(@code,5,7)
				return @val
			end
		if @code_form='0503117M' and substring(@code,12,6)='000000'
			begin
				select @val=name from RN_VIEW_KBK_CST_M where code=substring(@code,5,7)
				return @val
			end
		if @code_form='0503117M' and substring(@code,15,3)='000'
			begin
				select @val=name from RN_VIEW_KBK_VR_M  where code=substring(@code,12,3)
				return @val
			end
*/


GO
GRANT ALL ON dbo.[ro_get_name_spr] 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].[RI_REPORT_FORMULA_CALCULATE_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RI_REPORT_FORMULA_CALCULATE_ITOG]
GO


/*
	Расчет формул для формирования отчета
	20060817 доступ к колонке
*/
CREATE                   PROCEDURE dbo.RI_REPORT_FORMULA_CALCULATE_ITOG 
	@dBegin datetime = '20050101', @dEnd datetime = '20051231', @LSF int = NULL,@cTables varchar(1000) = '',
      @cProgressTable     varchar(254)  = '',@isWeb int=0   
    -- входные параметры
AS

DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int,
	@varKSEventStr	varchar (200),
	@varKSEventStr2	varchar (200),
	@varKSLink_Task	int,
	@varKSLink_last_event int,
	@Statistics int,
	@time_begin datetime,
	@Reads		int
	
set @time_begin = getdate()
select @Statistics = Val_Int from dbo.report_options where razdel = 'statistics' and code = 'mode'

if @LSF is NULL
	return -1
if not exists(select * from report_saved_forms where Link_Saved_Form = @LSF)
	return -2
if dbo.RO_ACCESS_SAVED_FORM(@LSF, @isWeb) & 2 = 0
	return -1
--перенос формы из архивной базы
exec dbo.RN_MOVE_FORM_FROM_ARH @LSF


declare @linkRow int, @linkCol int, @Formula varchar(2000), @CodeForm char(10)
declare @tmp int, @i int, @subStr varchar(700), @Str varchar(1000),@cWord varchar(20),@liTable int

--Для формы 14 досчет по таблицам не нужен
declare @link_form int
select @Link_Form = Link_Form from dbo.report_saved_forms where Link_Saved_Form = @LSF

SELECT @CodeForm = CODE FROM REPORT_FORMS WHERE LINK_FORM=@Link_Form

--удалим старые итоги
IF @CodeForm like '050307[45]%' 
	set @cTables=''


EXEC dbo.RO_report_MODIFY @LSF

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)
	IF @liTable<0 
		set @cTables=''
    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)
IF @cTables=''
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	(CHARINDEX('ИТОГ', Formula) > 0 or CHARINDEX('ГР', Formula) > 0) and 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
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	(CHARINDEX('ИТОГ', Formula) > 0 or CHARINDEX('ГР', Formula) > 0) and 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

set @Reads  = isnull((select count(*) from #F), 0)

--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


-- расчет динамических таблиц
declare @codeRow varchar(250), @LinkTable int, @OrderCol int, @itog varchar(1000), @SQLScript varchar(2000)
declare @t_Formul table (S varchar(8000))

IF @cTables=''
BEGIN
        declare Totals cursor local static
        for select RDT.Link_Table, RDT.Code_Row, RDT.Order_Col, RDT.Formula
        	from report_dinamic_totals RDT
        		left join report_tables RT on RDT.link_Table = RT.link_Table
        		left join report_saved_forms RSF on RT.Link_Form = RSF.Link_Form
        	where RSF.Link_Saved_Form = @LSF
        	order by RDT.link_total
END
ELSE
BEGIN
        declare Totals cursor local static
        for select RDT.Link_Table, RDT.Code_Row, RDT.Order_Col, RDT.Formula
        	from report_dinamic_totals RDT
        		left join report_tables RT on RDT.link_Table = RT.link_Table
        		left join report_saved_forms RSF on RT.Link_Form = RSF.Link_Form
        	where RSF.Link_Saved_Form = @LSF and 
                exists(select * from #iTables IT where RT.link_Table=IT.Link_table)                
        	order by RDT.link_total

END
open Totals


fetch next from Totals
into @linkTable, @codeRow, @OrderCol, @Formula

while @@fetch_status = 0
begin
	if @codeRow is NULL or LEN(RTRIM(@codeRow)) = 0
	begin
		if @orderCol <> 0 -- сумма колонок
		begin
			insert @t_Formul(S)
				select 'declare @P numeric(20,2) set @P = ' + RTRIM(REPLACE(REPLACE(@Formula, 'S(', 'dbo.ro_sum_total(' + STR(@LSF) + ', ' + STR(@LinkTable) + ', ' + STR(@OrderCol) + ', '), ')', ', ''' + RTRIM(Code_Row) + ''')')) + ' ' + 
							'update report_dinamics set Float_Val = @P where Link_SF = ' + STR(@LSF) + ' and Code_Row = ''' + RTRIM(Code_Row) + ''' and Link_Col = (select top 1 Link_Col from report_coloumns where Link_Table = ' + STR(@LinkTable) + ' and orders = ' + STR(@orderCol) + ' and dbo.RO_AccessColByLink(Link_Col) > 0)'
				from dbo.I_REPORT_DINAMIC_ROWS
				where Link_SF = @LSF and Link_Table = @LinkTable
			while exists(select * from @t_Formul where S is not NULL)
			begin
				select top 1 @SQLScript = S from @t_Formul
				execute(@SQLScript)
				delete @t_Formul where S = @SQLScript
			end
		end
	end
	else begin
		if @orderCol = 0
		begin -- расчет итогов для всех столбцов по строкам, которые не являются итогами
			set @itog = ''
			select @itog = @itog + case when CHARINDEX('*', Code_Row) > 0 then ' or code_row like ''' + RTRIM(REPLACE(Code_Row, '*', '%')) + '''' else ' or code_row = ''' + Code_Row + '''' end from report_dinamic_totals where link_Table = @LinkTable and Code_Row is not null
			set @itog = RIGHT(@itog, LEN(@itog) - 4)
			if CHARINDEX('*', @codeRow) > 0
			begin
				set @SQLScript = 'declare @LSF int set @LSF = ' + STR(@LSF) + ' ' + @Formula
				execute(@SQLScript)
			end
			else begin
				set @SQLScript = 'declare @t table (LC int, val numeric (20,2))
					insert @t(LC, val)
						select Link_Col, sum(float_val)
						from report_dinamics
						where Link_SF = ' + STR(@LSF) + ' and not (' + @itog + ') and Link_Col in (select Link_Col from report_coloumns where Link_Table = ' + STR(@LinkTable) + ')
						group by Link_Col
		
					update report_dinamics
					set Float_Val = val
					from 	@t
					where Link_SF = ' + STR(@LSF) + ' and code_row = ''' +  RTRIM(@codeRow) + ''' and Link_Col = LC and dbo.RO_AccessColByLink(Link_Col) > 0'
			end
			execute(@SQLScript)
		end
		else begin -- расчет по формуле
			set @SQLScript = 'declare @P numeric(20,2) set @P = ' + REPLACE(@Formula, 'S(', 'dbo.ro_sum_total(' + STR(@LSF) + ', ' + STR(@LinkTable) + ', ' + STR(@OrderCol) + ', ') + 
						'update report_dinamics set Float_Val = @P where Link_SF = ' + STR(@LSF) + ' and Code_Row = ''' + @CodeRow + ''' and Link_Col = (select top 1 Link_Col from report_coloumns where Link_Table = ' + STR(@LinkTable) + ' and orders = ' + STR(@orderCol) + ' and dbo.RO_AccessColByLink(Link_Col) > 0)'
			execute(@SQLScript)
		end
	end
	fetch next from Totals
	into @linkTable, @codeRow, @OrderCol, @Formula
end
close Totals
deallocate Totals

-- расчет из КС (формулы досчета)
EXEC dbo.RN_CALCULATE_DOSCHET @LSF,@cTables,@cProgressTable,@isWeb
--exec dbo.RO_CALCULATE_DOSCHET @LSF,@cTables,@cProgressTable

SET @varKSEventStr2 = 'Расчет итогов сохраненной формы'

select @varKSLink_Task = link_task from user_info
select @varKSEventStr = 'Форма: ' + rtrim(RF.code) + '; Организация: ' + RTRIM(LEFT(dbo.GetDepName(RSF.Link_Organization,RSF.begin_date),80)) + ';Бюджет: ' + isnull(RTRIM(B.Name),'-') + '; Период: ' + 
	(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 
	left join kl_budg_type B on B.Link = RSF.Link_Type_Svod
where link_saved_form = @LSF
	
exec dbo.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

drop table #itables

--if @Statistics = 1
--begin
--	insert dbo.REPORT_STATISTICS (Operation, CodeForm, Reads, Duration) 
--	select Operation = 2, 
--			CodeForm = @CodeForm, 
--			Reads = isnull(@Reads, 0) + isnull((select count(*) from dbo.report_dinamics_all where link_sf = @LSF), 0) + isnull((select count(*) from dbo.report_summa_all where link_saved_form = @LSF), 0) + isnull((select count(*) from dbo.report_control_rules where link_form = @Link_Form and IsOutside = 0), 0),
--			Duration = getdate() - @time_begin
--end

GO
GRANT ALL ON dbo.[RI_REPORT_FORMULA_CALCULATE_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

select * from report_saved_forms
DECLARE @tabRULES TABLE  ([LINK_RULE]  INT, 
                        [ORDER_RULE] INT)

insert into @tabRULES exec dbo.I_CONTROL_RULES_LIST 2814, 0
*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_GET_ATRIBUT_VALUES]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_GET_ATRIBUT_VALUES]
GO

/*******************************************************************************
	Кейсистемс (Keysystems), 2006
   проверка сводного отчета
*******************************************************************************/
CREATE       procedure dbo.RN_GET_ATRIBUT_VALUES
	@LSF int=null,  -- линк сохраненного отчета
    @LF int=null,
    @type int=0, -- тип возвращаемой таблицы. 0-горизонтальная, 1 - вертикальная
    @tmp_table varchar(100)='',
    @tmp_table2  varchar(100)=''
AS

delete REPORT_ATRIBUT_VALUES where link_saved_form=0
declare @atributs varchar(1000),@li int,@atr varchar(50),@cstr varchar(8000),@cstr1 varchar(8000),@len varchar(10)
--получим список доступных атрибутов отчета.

IF @LSF is not null and @LSF<>0
    select @LF = Link_Form from report_saved_forms (nolock) where Link_Saved_Form = @LSF

select @atributs=atributs from report_forms where link_form=@LF 
declare @REPORTS_ATR_CST int,@CST_NAME varchar(1000)
declare @REPORTS_ATR_KBK_63 int,@REPORTS_ATR_KBK_63_NAME varchar(1000)
declare @REPORTS_ATR_RZPR int,@RZPR_NAME varchar(2000)
declare @REPORTS_ATR_VR int,@VR_NAME varchar(2000)


set @REPORTS_ATR_CST=0
set @REPORTS_ATR_KBK_63=0
IF @type=1
    begin
        set @cstr=''
        set @li=1
        set @cstr=''
        set @cstr1=''
        WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
				if @atr='REPORTS_ATR_CST'
					set @REPORTS_ATR_CST=1
				if @atr='REPORTS_ATR_KBK_63'
					set @REPORTS_ATR_KBK_63=1

				if @atr='REPORTS_ATR_RZPR'
					set @REPORTS_ATR_RZPR=1

				if @atr='REPORTS_ATR_VR'
					set @REPORTS_ATR_VR=1
               	
				set @cstr=@cstr + case when @li>1 then ' union ' else '' end +'select '''+@atr+''' code_atr,dbo.get_val('''+@atr+''',''NAME'',0) atr_name,convert(varchar(250),isnull((select str_val from REPORT_ATRIBUT_VALUES where link_saved_form='+LTRIM(str(isnull(@LSF,0)))+' and code_atr='''+@atr+'''),dbo.get_val('''+@atr+''',''DEFAULT_VALUE'',0))) str_val'+ case when @li=1 and @tmp_table<>'' then ' into '+@tmp_table else '' end
                set @li=@li+1
            end
--        IF @tmp_table<>''
--            set @cstr=@cstr+' into '+@tmp_table 
        IF RTRIM(@atributs)<>''
			begin
			print @cstr
			IF @REPORTS_ATR_CST=1
				begin
					select @CST_NAME=NAME FROM RN_VIEW_KBK_CST_M where code=(select top 1 str_val from REPORT_ATRIBUT_VALUES where link_saved_form=@LSF and code_atr='REPORTS_ATR_CST')
					if @CST_NAME is not null
						set @cstr=@cstr + ' union  select ''REPORTS_ATR_CST_NAME'' code_atr,'''' atr_name,'''+@CST_NAME+''''
				end
--select  @REPORTS_ATR_KBK_63
			IF @REPORTS_ATR_KBK_63=1
				begin
					select @REPORTS_ATR_KBK_63_NAME=NAME FROM rn_view_kbk_63 where code=(select top 1 str_val from REPORT_ATRIBUT_VALUES where link_saved_form=@LSF and code_atr='REPORTS_ATR_KBK_63')
					if @REPORTS_ATR_KBK_63_NAME is not null
						set @cstr=@cstr + ' union  select ''REPORTS_ATR_KBK_63_N'' code_atr,'''' atr_name,'''+@REPORTS_ATR_KBK_63_NAME+''''
				end

			IF @REPORTS_ATR_RZPR=1
				begin
					select @RZPR_NAME=NAME FROM dbo.R_SPR_RZPR_2011 where code=(select top 1 str_val from REPORT_ATRIBUT_VALUES where link_saved_form=@LSF and code_atr='REPORTS_ATR_RZPR')
					if @RZPR_NAME is not null
						set @cstr=@cstr + ' union  select ''REPORTS_ATR_RZPR_N'' code_atr,'''' atr_name,'''+@RZPR_NAME+''''
				end

			IF @REPORTS_ATR_VR=1
				begin
					select @VR_NAME=NAME FROM dbo.R_SPR_VR_2011 where code=(select top 1 str_val from REPORT_ATRIBUT_VALUES where link_saved_form=@LSF and code_atr='REPORTS_ATR_VR')
					if @RZPR_NAME is not null
						set @cstr=@cstr + ' union  select ''REPORTS_ATR_VR_N'' code_atr,'''' atr_name,'''+@VR_NAME+''''
				END
            
            execute(@cstr)
			END
        ELSE
            RETURN 0 
        
    end
else
    begin   
        set @cstr=''
        set @li=1
        set @cstr='CREATE TABLE #tmp_atr ('
        set @cstr1='select '
        WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
				set @len=ISNULL(dbo.get_val(@atr,'MAXWIDTH',0),'50')

                set @cstr=@cstr+case when @li>1 then ',' else '' end +@atr+' varchar('+ISNULL(dbo.get_val(@atr,'MAXWIDTH',0),'50')+')'
                set @cstr1=@cstr1+case when @li>1 then ',' else '' end+'left(isnull((select top 1 str_val from REPORT_ATRIBUT_VALUES where link_saved_form='+LTRIM(str(isnull(@LSF,0)))+' and code_atr='''+@atr+'''),dbo.get_val('''+@atr+''',''DEFAULT_VALUE'',0)),'+@len+')'
                set @li=@li+1
            end
        set @cstr=@cstr+') 
            insert #tmp_atr '
        IF RTRIM(@atributs)<>''
            if isnull(@tmp_table2, '') <> ''
               execute(@cstr+@cstr1+' select * into ' + @tmp_table2 + ' from #tmp_atr')
            else
               execute(@cstr+@cstr1+' select * from #tmp_atr')
        ELSE
            RETURN 0 
    end
GO
GRANT ALL ON dbo.[RN_GET_ATRIBUT_VALUES] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_EXPORT_ZS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_EXPORT_ZS]
GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE FB_EXPORT_ZS
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''


AS
  DECLARE @iDepLink	int,
	  @iLongFio	int

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
select top 1 @iLongFio = isnull(FIO,0) from dbo.DOCUMENTS_REC_CASH_OPTIONS  


-- Таблица 2
-- найдем текущего пользователя
Declare @cur_user varchar(50), @cur_user_dol varchar(50)
Select @cur_user = case @iLongFio when 1 then EP.FIO else EP.NAME_EMPL end,
	   @cur_user_dol = ep.post_name
	FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN WHO_IS_WHO UD ON UD.SID = SUSER_SID()
	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EP ON UD.USER_REF = EP.LINK
	WHERE DD1.LINK = @iDepLink

SELECT  	
		[LINK] 		= RC.LINK,
		[LINK_UP] 	= RC.LINK,
		[NUM_ZVK] 	= RC.Number,
		[DATE_ZVK] 	= RC.DATE,
		[VID_PL] 	    = case 
						WHEN RC.KIND = 'почтой'     THEN '1'
						WHEN RC.KIND = 'телеграфом' THEN '2'
						WHEN RC.KIND = 'электронно' THEN '3'
						WHEN RC.KIND = 'срочно'     THEN '4'
						ELSE '0' 
						END,
		[SUM_ZVK] 	= RC.SUMMA,
		[INN_PAY]  	= DP.INN,
		[KPP_PAY]  	= DP.KPP,
		[KOD_BP_PAY] 	= DP.BUDG,
		[NAME_BP_PAY] = DP.FULL_NAME,
		[NAME_PAY]    = dbo.FuncPrintReceptionCashData(RC.ACC_LINK),
		[NUM_LS_PAY]   = RC.ACC_CODE,
		[KOD_TOFK_PAY] = (Select CODE From DICTIONARY_TREASURY Where link = da.ref_link_k),
		[INN_OK_PAY]  = (Select INN From DICTIONARY_TREASURY Where link = da.ref_link_k),
		[NM_OK_PAY] = (Select convert(varchar(120), NAME) From DICTIONARY_TREASURY Where LINK =  da.ref_link_k),
		[RS_PAY]	 = (Select CODE From Dictionary_K_accounts Where LINK = da.K_ACC_LINK),

-- select * from DICTIONARY_TREASURY
-- select * from Dictionary_K_accounts


	  	[BIK_PAY] = (Select TOP 1 BANK_CODE From Dictionary_K_accounts Where code in (Select CODE From Dictionary_K_accounts Where LINK = da.K_ACC_LINK)),
		[BANK_PAY] = (Select TOP 1 convert(varchar(50), BANK_NAME) From Dictionary_K_accounts Where code in (Select CODE From Dictionary_K_accounts Where LINK = da.K_ACC_LINK)),
		[FILIAL_PAY] = 	(Select TOP 1 convert(varchar(50), FILIAL_NAME) From Dictionary_K_accounts Where code in (Select CODE From Dictionary_K_accounts Where LINK = da.K_ACC_LINK)),
		[KS_PAY] = (Select KS From Dictionary_Bank where link = (Select bank_link From Dictionary_K_accounts Where LINK = da.K_ACC_LINK)),
		[INN_RCP] = '',
		[KPP_RCP] = '',
		[NAME_RCP] = '',
		[INN_OK_RCP] = '',
		[NM_OK_RCP] = '',
		[RS_RCP] = '',
		[LS_RCP] = '',
		[BIK_RCP] = '',
		[BANK_RCP] = '',
		[FILIAL_RCP] = '',
		[KS_RCP] = '',
		[TIME_PAY] = RC.SROK,
		[ORDER_PAY] = RC.PLAT_ORDER,
		[PURPOSE] = RC.REASON,
		[PRINT_KPP] = '',
		[CHECK_SER] = RC.Chek_ser,
		[CHECK_NOM] = RC.Chek_no,
		[CHECK_DATE] = RC.Chek_date,
		[DOL_DOV]  = ep.post_name,
		[NAME_DOV] = case @iLongFio when 1 then rtrim(EP.FIO) else EP.NAME_EMPL end,
		NAME_DOC	 = RC.ED_DOC,
		NOM_DOC		 = RC.ED_NUM,
		ORG_DOC		 = RC.ED_WHOM,
		DATE_DOC	 = RC.ED_DATE,
		[NAME_RUK] 	= (SELECT case @iLongFio when 1 then rtrim(FM) + ' ' + rtrim(IM) + ' ' + rtrim(OT) else SHORT_NAME end FROM dbo.GetOtvFaceData(@iDepLink, 'Руководитель')),
		[NAME_BUH] 	= (SELECT case @iLongFio when 1 then rtrim(FM) + ' ' + rtrim(IM) + ' ' + rtrim(OT) else SHORT_NAME end FROM dbo.GetOtvFaceData(@iDepLink, 'Главный бухгалтер')),
		[COMM]		=  RC.UKAZ,
		[DOL_ISP] 	= @cur_user_dol,
		[NAME_ISP] 	= @cur_user
	FROM documents_RECEPTION_CASH RC
	left join dbo.departments dp on dp.link = rc.dep_link
   	left join dbo.dictionary_accounts da on da.link = rc.acc_link
	left join dbo.ku_empl_placing ep on ep.link = rc.emp_link 
	left join dbo.ku_person pers on pers.link = ep.pers_link 
	where RC.LINK in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())


--select * from ku_person where fm = 'Кукарева'
--select * from ku_empl_placing where pers_link=17485
-- Блок BOST
--if @iTableNum = 5

	select 	
		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), RCT.EKR_CODE),
		KKIVNF		= '',
		KKIVF		= '',
		KDOH		= '',
		ADD_KLASS 	= convert (varchar(20), RCT.D_CL_CODE),
		KOD_FIN 	= convert (varchar(1), RCT.FS_CODE),
		SUM_STR		= RCT.SUMMA,
		LINK		= RCT.LINK,
		LINK_UP		= RCT.LINK_UP

	from dbo.RECEPTION_CASH_table_view RCT
	left join dbo.documents_RECEPTION_CASH RC on RC.LINK = RCT.LINK_UP
	left join dbo.BI_DICTION_VKR VKR on VKR.LINK_KBK = RCT.KBK
	where RCT.LINK_UP in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())

--select * from RECEPTION_CASH_table_view



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant all on dbo.[FB_EXPORT_ZS] to public
GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_U_USP_CALC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_U_USP_CALC]
GO

CREATE   PROCEDURE dbo.SA_U_USP_CALC (@LINK_DOC INT)
AS

DECLARE
	@REF_PAY INT, --Начисление по исп. листу
	@REF_EMPL INT, --Сотрудник
	@Date1 DATETIME, --Начало периода
	@Date2 DATETIME, --Конец периода
	@REF_DOC INT, --Исполниьельный лист
	@PAYMENT TINYINT, -- способ расчета (1 - %, 2 - сумма)
	@SUMMA NUMERIC(18,2), --сумма или % удержания по исп листу
	@DATE DATETIME, --Дата документа с расчетом,
	@WAY TINYINT, --способ перечисления денег
	@INO TINYINT, --флаг международного перевода
	@SUM_ENUM NUMERIC(18,2),-- сумма за перечисление денег
	@PERCENT NUMERIC(18,2), --процент за перечисление денег
	@SUMMA_NEED NUMERIC(18,2), --сумма необходимая,
	@PERC_SFIN TINYINT,
	@NO_NDFL TINYINT,
	@BY_EKR TINYINT

--Сведения о расчете
SELECT
	@REF_PAY = SD.LINK_PAY,
	@REF_DOC = SD.REF_DOC,
	@Date1 = dbo.DateBeginOfMonth(S.DATE_CALC),
	@Date2 = dbo.DateEndOfMonth(S.DATE_CALC),
	@DATE = S.DATE_CALC
FROM 
	DBO.SDOC S INNER JOIN DBO.SDOC_TISP SD ON S.LINK = SD.LINK_UP
WHERE
	S.LINK = @LINK_DOC
	
--Сведения об исполнительном листе
SELECT 
	@REF_EMPL = SD.LINK_EMPL,
	@PAYMENT = ISNULL(SD.PAYMENT,1),
	@SUMMA = ISNULL(SD.SUMMA,0),
	@WAY = ISNULL(WAY,1),
	@INO = INO,
	@SUM_ENUM = ISNULL(SUM_ENUM,0),
	@PERCENT = ISNULL([PERC],0),
	@SUMMA_NEED = ISNULL(SUMMA_NEED,0),
	@PERC_SFIN = ISNULL(PERC_SFIN,0),
	@NO_NDFL = ISNULL(NO_NDFL,0),
	@BY_EKR = ISNULL(BY_EKR,0)
FROM
	DBO.SDOC_WRIT SD
WHERE
	SD.LINK_UP = @REF_DOC
	
--
DELETE FROM DBO.DED_WRIT_TABLE WHERE LINK_UP = @LINK_DOC
--
DECLARE @SUM_PAY NUMERIC(18,2), @SUM_IL NUMERIC(18,2)

DECLARE @LinkEKR211 int
SET @LinkEKR211 = ISNULL((SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211'),0)
--
INSERT INTO DBO.DED_WRIT_TABLE (LINK_UP, ORDERS, LINK_PAY, SUMMA, LINK_SFIN, LINK_EKR)
SELECT
	@LINK_DOC,
	1, 	
	CJ.LINK_PAYS,
	SUM(CJ.SUMMA),
	CJ.LINK_VKR,
	case when isnull(@BY_EKR,0) = 0 then @LinkEKR211 else ISNULL(CJ.LINK_EKR,P.LINK_EKR) end
FROM 
	dbo.CALCULATE_JURNAL CJ 
	INNER JOIN dbo.group_tax(@REF_PAY) T ON CJ.LINK_PAYS=T.TAX_LINK
	INNER JOIN DBO.PAYS P ON CJ.LINK_PAYS = P.LINK
WHERE
	P.[OBJECT] = 1
	AND
	CJ.LINK_EMPL = @REF_EMPL
	AND
	CJ.PERIOD_BEGIN >= @Date1 AND CJ.PERIOD_END <= @Date2
GROUP BY  
	CJ.LINK_PAYS, CJ.LINK_VKR , case when isnull(@BY_EKR,0) = 0 then @LinkEKR211 else ISNULL(CJ.LINK_EKR,P.LINK_EKR) end
UNION ALL
SELECT
	@LINK_DOC,
	1, 	
	CJ.LINK_PAYS,
	SUM(CJ.SUMMA),
	CJ.LINK_VKR,
	case when isnull(@BY_EKR,0) = 0 then @LinkEKR211 else ISNULL(CJ.LINK_EKR,P.LINK_EKR) end
FROM 
	dbo.CALCULATE_JURNAL CJ 
	INNER JOIN DBO.PAYS P ON CJ.LINK_PAYS = P.LINK
WHERE
	P.[OBJECT] = 2
	AND
	@NO_NDFL = 0
	AND
	P.WAY_CALC IN (4,5,6)
	AND
	CJ.LINK_EMPL = @REF_EMPL
	AND
	CJ.PERIOD_BEGIN >= @Date1 AND CJ.PERIOD_END <= @Date2
GROUP BY  
	CJ.LINK_PAYS, CJ.LINK_VKR , case when isnull(@BY_EKR,0) = 0 then @LinkEKR211 else ISNULL(CJ.LINK_EKR,P.LINK_EKR) end

--Нумерация
declare @num int
select @num = 0
update dbo.DED_WRIT_TABLE
Set 
	@num = @num + 1,
	orders = @num
where
	LINK_UP = @LINK_DOC

--Базовая сумма

DECLARE @DOC_SFIN INT
SET @DOC_SFIN = (SELECT TOP 1 B.LINK_VKR FROM DBO.SDOC_TISP A INNER JOIN DBO.SDOC_WRIT B ON A.REF_DOC = B.LINK_UP WHERE A.LINK_UP = @LINK_DOC)
SET @DOC_SFIN = CASE WHEN @DOC_SFIN = 0 THEN NULL ELSE @DOC_SFIN END

----
DELETE FROM DBO.DED_WRIT_TABLE1 WHERE LINK_UP = @LINK_DOC
INSERT INTO DBO.DED_WRIT_TABLE1 (LINK_UP, ORDERS, LINK_SFIN, LINK_EKR, SUMMA_BASE, SUMMA_N, SUMMA_U, SUMMA, SUMMA_PER)
SELECT
	@LINK_DOC, 
	0,
	link_sfin = ISNULL(ISNULL(@DOC_SFIN,T.LINK_SFIN),S.LINK_KBK),
	link_ekr = ISNULL(T.LINK_EKR,@LinkEKR211), 
	SUMMA_BASE = ISNULL(SUM(CASE WHEN P.OBJECT =1 THEN T.SUMMA ELSE -T.SUMMA END),0),
	SUMMA_N = 0, 
	SUMMA_U = 0,
	SUMMA = 0, 
	SUMMA_PER = 0
FROM
	DBO.SDOC_TISP A INNER JOIN DBO.SDOC_WRIT B ON A.REF_DOC = B.LINK_UP
	LEFT JOIN DBO.DED_WRIT_TABLE T ON T.LINK_UP = A.LINK_UP 
	LEFT JOIN DBO.PAYS P ON P.LINK = T.LINK_PAY
	LEFT JOIN dbo.EMPL_STAFF1(default) S on B.LINK_EMPL = S.EMPL_LINK
WHERE 
	A.LINK_UP = @LINK_DOC
GROUP BY 
	T.LINK_EKR, ISNULL(ISNULL(@DOC_SFIN,T.LINK_SFIN),S.LINK_KBK)
ORDER BY
	ISNULL(ISNULL(@DOC_SFIN,T.LINK_SFIN),S.LINK_KBK), T.LINK_EKR
	
--Нумерация
select @num = 0
update dbo.DED_WRIT_TABLE1
Set 
	@num = @num + 1,
	orders = @num
where
	LINK_UP = @LINK_DOC		
	
---Вычислить коэффициенты пропорциональности	
Create table #koef (orders TINYINT, summa numeric(18,2), summa1 numeric(20,8),summa2 numeric(20,8), summa3 numeric(20,8))
IF ISNULL( (SELECT COUNT(*) FROM DBO.DED_WRIT_TABLE1 WHERE LINK_UP = @LINK_DOC), 0) > 1
BEGIN
	INSERT INTO #koef (orders, summa, summa1, summa2, summa3)
	SELECT ORDERS, SUMMA_BASE, 0, 0, 0
	FROM DBO.DED_WRIT_TABLE1 
	WHERE LINK_UP = @LINK_DOC

	update #koef
	set summa1 = summa / (select case when abs(min(summa)) <> 0 then abs(min(summa)) else 1 end from #koef a )
	WHERE summa > 0

	update #koef
	set summa2 = summa1 + (select case when min(summa1) < 0 then abs(min(summa1)) else 0 end from #koef a)

	update #koef
	set summa3 = summa2 / (select (case when sum(summa2) <> 0 then sum(summa2) else 1 end) from #koef a )
END
ELSE
	INSERT INTO #koef (orders, summa, summa1, summa2, summa3) 
	SELECT ORDERS, SUMMA_BASE, 0, 0, 1
	FROM DBO.DED_WRIT_TABLE1 
	WHERE LINK_UP = @LINK_DOC

--Общая базовая сумма
SET @SUM_PAY = (SELECT ISNULL(SUM(SUMMA_BASE),0) FROM DBO.DED_WRIT_TABLE1 WHERE LINK_UP = @LINK_DOC)
SET @SUM_PAY = CASE WHEN @SUM_PAY < 0 THEN 0 ELSE @SUM_PAY END

--Сумма по исполнительному листу
SET @SUM_IL = @SUMMA * CASE WHEN @PAYMENT = 1 THEN @SUM_PAY / 100 ELSE 1 END
SET @SUM_IL = CASE WHEN @SUM_IL > @SUM_PAY THEN @SUM_PAY ELSE @SUM_IL END

--Сколько уже было удержано по этому исп. листу до этого месяца
DECLARE @SUM_TOT NUMERIC(18,2)
SET @SUM_TOT = ISNULL((
	SELECT SUM(SUMMA_RAS) 
	FROM 
		DBO.SDOC S INNER JOIN DBO.SDOC_TISP SD ON S.LINK = SD.LINK_UP
	WHERE 
		SD.REF_DOC = @REF_DOC
		AND
		S.FLAG_JC = 1
		AND
		S.[DATE] < @Date1
	),0)
-- Проверка, чтобы не перебрать
IF @SUMMA_NEED > 0 AND (@SUM_IL + @SUM_TOT) > @SUMMA_NEED
	SET @SUM_IL = CASE WHEN @SUM_TOT < @SUMMA_NEED THEN @SUMMA_NEED - @SUM_TOT ELSE 0 END

-- Сколько в этом месяце удержали	
Select LINK_EKR, CJ.LINK_VKR, SUMMA = SUM(CJ.SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_TISP 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(@REF_DOC,0) > 0
	AND SA.REF_DOC = @REF_DOC
	AND PERIOD_BEGIN BETWEEN @Date1 AND @Date2
	AND LINK_PAYS = @REF_PAY
GROUP BY
	LINK_EKR, CJ.LINK_VKR

-- разобъем по источникам и сопоставить старые
UPDATE T
SET 
	SUMMA_N = @SUM_IL * B.summa3,
	SUMMA_U = ISNULL(SO.SUMMA,0)
FROM 
	dbo.DED_WRIT_TABLE1 T
	INNER JOIN #koef B ON T.ORDERS = B.ORDERS
	LEFT JOIN #SUM_OLD SO ON T.LINK_SFIN = SO.LINK_VKR and T.LINK_EKR = SO.LINK_EKR
WHERE 
	T.LINK_UP = @LINK_DOC
	
-- добавить старые, которых теперь нет
insert into dbo.DED_WRIT_TABLE1 
	(LINK_UP, ORDERS, LINK_SFIN, LINK_EKR, SUMMA_BASE, SUMMA_N, SUMMA_U, SUMMA, SUMMA_PER)
Select 
	@LINK_DOC, 0, LINK_VKR, LINK_EKR, 0, 0, ISNULL(SO.SUMMA,0), 0, 0
from 
	#SUM_OLD SO
where 
	NOT EXISTS (Select * from dbo.DED_WRIT_TABLE1 T where T.LINK_UP = @LINK_DOC
		AND T.LINK_SFIN = SO.LINK_VKR and T.LINK_EKR = SO.LINK_EKR)	
		
--Нумерация
select @num = 0
update dbo.DED_WRIT_TABLE1
Set 
	@num = @num + 1,
	orders = @num
where
	LINK_UP = @LINK_DOC	
	
---- сравнить
UPDATE dbo.DED_WRIT_TABLE1
SET SUMMA = ISNULL(SUMMA_N,0) - ISNULL(SUMMA_U,0)
WHERE LINK_UP = @LINK_DOC	
		

---- Считаем сколько нужно взять за перевод денег
IF @WAY = 1 AND @SUM_PAY > 0
	IF @PERC_SFIN = 1 
	BEGIN

		SELECT LINK_SFIN, SUMMA = SUM(SUMMA)
		INTO #SUM_SFIN
		FROM dbo.DED_WRIT_TABLE1
		WHERE LINK_UP = @LINK_DOC
		GROUP BY LINK_SFIN

		UPDATE A
			SET SUMMA_PER = DBO.SA_POST_TARIF(SF.SUMMA, @INO) * A.SUMMA / SF.SUMMA
		FROM 
			dbo.DED_WRIT_TABLE1 A INNER JOIN #SUM_SFIN SF ON SF.LINK_SFIN = A.LINK_SFIN
		WHERE 
			A.LINK_UP = @LINK_DOC AND SF.SUMMA <> 0
	END
	ELSE
		BEGIN

			SELECT SUMMA = SUM(SUMMA)
			INTO #SUM_SFIN2
			FROM dbo.DED_WRIT_TABLE1
			WHERE LINK_UP = @LINK_DOC

			UPDATE A
				SET SUMMA_PER = DBO.SA_POST_TARIF(SF.SUMMA, @INO) * A.SUMMA / SF.SUMMA
			FROM 
				dbo.DED_WRIT_TABLE1 A INNER JOIN #SUM_SFIN2 SF ON 1=1
			WHERE 
				A.LINK_UP = @LINK_DOC AND SF.SUMMA <> 0	
		END

--Для банка	
IF @WAY = 3
BEGIN

	SELECT SUMMA = SUM(SUMMA)
	INTO #SUM_SFIN3
	FROM dbo.DED_WRIT_TABLE1
	WHERE LINK_UP = @LINK_DOC

	UPDATE A
	SET SUMMA_PER = A.SUMMA * @PERCENT / 100 + @SUM_ENUM * A.SUMMA / SF.SUMMA
	FROM dbo.DED_WRIT_TABLE1 A INNER JOIN #SUM_SFIN3 SF ON 1=1
	WHERE LINK_UP = @LINK_DOC AND @WAY = 3 AND SF.SUMMA <> 0

END

SET @SUM_ENUM = (SELECT SUM(SUMMA_PER) FROM dbo.DED_WRIT_TABLE1 WHERE LINK_UP = @LINK_DOC)

-- Обновить результаты
UPDATE DBO.SDOC_TISP
SET 
	SUMMA_BASE = ISNULL(@SUM_PAY,0), 
	SUMMA_UD = ISNULL(@SUM_TOT,0), 
	SUM_ENUM = ISNULL(@SUM_ENUM,0), 
	SUMMA_RAS = ISNULL(@SUM_IL,0), 
	SUMMA_TOTAL = ISNULL(@SUM_ENUM,0) + ISNULL(@SUM_IL,0)
WHERE 
	LINK_UP = @LINK_DOC

SELECT SUMMA_BASE, SUM_ENUM, SUMMA_RAS, SUMMA_TOTAL, SUMMA_UD
FROM DBO.SDOC_TISP WHERE LINK_UP = @LINK_DOC
GO


GRANT EXECUTE ON dbo.[SA_U_USP_CALC] TO PUBLIC
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_360]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_360]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_360]
	@iLINK_SAVED_FORM INT,	                  -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1  -- Формат: 1-внутренний, 2-минфиновский
AS

SET NOCOUNT ON

DECLARE @i INT
IF OBJECT_ID('tempdb..#tabExportOutput') IS NULL
BEGIN
	return 
END
   
   DECLARE @vcVersion VARCHAR(250),
            @vcFileNameArh VARCHAR(250)

	EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
									   @vcFILE_NAME OUTPUT,
									   @iMODE                          

	if @iMODE = 2
	begin
	   UPDATE #FileExportReport
	   SET [NAMEFILE] = LEFT(NAMEFILE, CHARINDEX('.', NAMEFILE)) + 'doc'
      
       IF (SELECT TOP 1 CODE FROM REPORT_FORMS WHERE LINK_FORM = (SELECT LINK_FORM FROM REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @iLINK_SAVED_FORM))
        IN ('0503760G','0503760M')
	   UPDATE #FileExportReport
	   SET [NameFileArh] = SUBSTRING(NameFileArh, 2, 100)

       IF (SELECT TOP 1 CODE FROM REPORT_FORMS WHERE LINK_FORM = (SELECT LINK_FORM FROM REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @iLINK_SAVED_FORM))
        IN ('579')
        BEGIN 
           	SELECT @vcVersion = [VERSION] FROM #tabExportOutput
            SELECT             @vcFILE_NAME = RTRIM([B].[EXPORTCODE]) + 
                        RIGHT('0'+LTRIM(STR(MONTH([A].[BEGIN_DATE]+1))),2)+ 
                        'Q' + RTRIM(@vcVersion) + '.TXT',
                     @vcFileNameArh = '5' + RIGHT('000' + ISNULL(RTRIM(LTRIM((SELECT IST_ZATO FROM dbo.RA_VIEW_OPTIONS_57X))),''),3) +
						            RIGHT('0'+LTRIM(STR(MONTH([A].[BEGIN_DATE]+1))),2)+ RTRIM(@vcVersion) + '.arj'
               FROM dbo.[REPORT_SAVED_FORMS] [A]
               JOIN dbo.[REPORT_FORMS]       [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
               WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM      

            DELETE  #FileExportReport
            WHERE TXT NOT LIKE '%|%'
               
	         UPDATE #FileExportReport
	         SET [NameFileArh] = @vcFileNameArh,
                 [NameFile] = @vcFILE_NAME,
                 TXT = SUBSTRING(TXT, CHARINDEX('|', [TXT]) + 1, LEN([TXT]) - CHARINDEX('|', [TXT])-1) + '#DEL13#' 

            IF NOT EXISTS(SELECT * FROM #FileExportReport)
            BEGIN
               INSERT #FileExportReport ([TXT],
                                          [NameFile],
                                          [NameFileArh])
               SELECT '',
                        @vcFILE_NAME,
                        @vcFileNameArh
               
            END 
               
        END
	end

GO
GRANT ALL ON dbo.RA_EXPORT_FORM_360 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_SAVE_SUMMA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_SAVE_SUMMA]
GO





/*
© Кейсистемс (Keysystems), 2005
*/
--сохранение сумм

CREATE     
PROCEDURE dbo.RN_SAVE_SUMMA
	@LSF	int	= null,
    @Link_table int = null,
    @tmp_table varchar(100)=null,
    @del_tmp int=1 --удалить временный файл    
AS

--на входе временная табличка
/*
link_col int
link_row int
code_row varchar(50)
str_val varchar(1000)
summa numeric(18,4)
del bit
*/
IF @LSF is null or @link_table is null or @tmp_table is null
    RETURN -1


 declare @execStr varchar(1000)

  IF OBJECT_ID('tempdb..#TMP_TABLE') IS NULL
  BEGIN
     create table #TMP_TABLE (link_col int,link_row int,code_row varchar(50),str_val varchar(8000),summa numeric(20,4),del bit)
     set @ExecStr = 'insert #TMP_TABLE 
       (link_col,link_row,code_row,str_val,summa,del)
       select link_col,link_row,code_row,isnull(str_val,''''),summa,del from ' + @tmp_table  +case when @del_tmp=1 then  ' drop table ' + @tmp_table else '' end
     print @ExecStr
     execute(@ExecStr) 
   
   Create index #IX_TMP_TABLE_CODE_ROW on #TMP_TABLE (del,link_col,code_row)
   Create index #IX_TMP_TABLE_LINK_ROW on #TMP_TABLE (del,link_col,link_row)
  END

IF EXISTS(select * from #TMP_TABLE)
BEGIN 
   exec dbo.RO_REPORT_MODIFY @LSF
END    

create table #link_col (link_col int)
insert #link_col
select link_col from report_coloumns where link_table=@link_table

declare @type_table int
select  @type_table=val_type from report_tables where link_table=@link_table

declare @count int
declare @nameLock varchar(100)
set @nameLock='RN_SAVE_SUMMA#'+LTRIM(RTRIM(STR(@Link_table)))
set @count=0
while EXISTS(select * from JURNAL where tableName=@nameLock and  link_pk=@LSF) and @count<10
    begin
        WAITFOR DELAY '00:00:01'
        set @count=@count+1
    end

exec X_LOCK_RECORD @nameLock,@LSF,'' 


SET NOCOUNT               ON
--SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          10000  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.


--проверим, не архивный ли отчет сохраняем.
IF exists(select * from report_saved_forms where link_saved_form=@LSF and is_arhiv=1)
	begin
	   --архивный, надо перенести данные в оперативную таблицу
		exec rn_move_form_from_arh @LSF
	end

--print @type_table

IF @type_table=1
    begin
    --динамическая таблица
        --удаление данных
        DELETE REPORT_DINAMICS
        FROM REPORT_DINAMICS A
        WHERE Link_SF=@LSF AND 
              EXISTS(SELECT * FROM  #TMP_TABLE B WHERE B.del=1 AND B.link_col=0 and B.code_row=RTRIM(A.code_row))
			  and link_col in (select link_col from #link_col)
        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        DELETE REPORT_DINAMICS
        FROM REPORT_DINAMICS A
        WHERE Link_SF=@LSF AND 
              EXISTS(SELECT * FROM  #TMP_TABLE B WHERE B.del=1 and B.link_col>0 AND B.link_col=A.link_col and B.code_row=rtrim(A.code_row))


        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        UPDATE REPORT_DINAMICS
         SET float_val=B.summa,
             str_val=B.str_val
        FROM REPORT_DINAMICS A INNER JOIN #TMP_TABLE B ON B.del=0 AND B.link_col=A.link_col and B.code_row=rtrim(A.code_row)
        WHERE A.Link_SF=@LSF 

        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 


        INSERT REPORT_DINAMICS (link_sf,link_col,Code_row,Float_val,Str_val)
        SELECT @lsf link_sf,link_col,Code_row,max(summa),max(Str_val)
        FROM #TMP_TABLE B
        WHERE B.del=0 AND rtrim(B.code_row)<>'' and 
              not EXISTS(SELECT * FROM REPORT_DINAMICS C WHERE B.link_col=C.link_col and rtrim(B.code_row)=C.code_row and C.link_sf=@LSF)
			  and (summa<>0	or str_val<>'')
	    GROUP BY B.link_col,B.Code_row	

        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

    end

IF @type_table=0
    begin
    --статическая таблица
        --удаление данных
        DELETE REPORT_SUMMA
        FROM REPORT_SUMMA A
        WHERE Link_Saved_Form=@LSF AND 
              EXISTS(SELECT * FROM  #TMP_TABLE B WHERE B.del=1 AND B.link_col=0 and B.link_row=A.link_row)
        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        DELETE REPORT_SUMMA
        FROM REPORT_SUMMA A
        WHERE Link_Saved_Form=@LSF AND 
              EXISTS(SELECT * FROM  #TMP_TABLE B WHERE B.del=1 and B.link_col>0 AND B.link_col=A.link_col and B.link_row=A.link_row )

        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        UPDATE REPORT_SUMMA
         SET summa=B.summa
        FROM REPORT_SUMMA A INNER JOIN #TMP_TABLE B ON B.del=0 AND B.link_col=A.link_col and B.link_row=A.link_row
        WHERE A.Link_Saved_Form=@LSF 



        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        UPDATE REPORT_STRING
         SET str_val=B.str_val
        FROM REPORT_STRING A INNER JOIN #TMP_TABLE B ON B.del=0 AND B.link_col=A.link_col and B.link_row=A.link_row
        WHERE A.Link_Saved_Form=@LSF 


        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        INSERT REPORT_SUMMA (link_saved_form,link_col,link_row,summa)
        SELECT @lsf Link_Saved_Form,link_col,link_row,max(summa)
        FROM #TMP_TABLE B
        WHERE B.del=0 AND
              not EXISTS(SELECT * FROM REPORT_SUMMA C WHERE B.link_col=C.link_col and B.link_row=C.link_row and C.Link_Saved_Form=@LSF) 
			  and summa<>0
	    GROUP BY B.link_col,B.link_row	


        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 

        INSERT REPORT_STRING (link_saved_form,link_col,link_row,str_val)
        SELECT @lsf Link_Saved_Form,link_col,link_row,max(str_val)
        FROM #TMP_TABLE B
        WHERE B.del=0 AND
              not EXISTS(SELECT * FROM REPORT_STRING C WHERE B.link_col=C.link_col and B.link_row=C.link_row and C.Link_Saved_Form=@LSF)
			  and str_val<>''
	    GROUP BY B.link_col,B.link_row	

        IF @@ERROR>0
            begin 
               ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
               COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
               exec X_UNLOCK_RECORD @nameLock,@LSF
               RETURN  
            end 
        
    end

/*
-- Группировка по строкам
SELECT code_row, summa = SUM(summa),del
INTO #TMP_TABLE_G
FROM #TMP_TABLE
GROUP BY code_row, del

-- Подготовка данных для системного журнала
DECLARE @varKSTASK Varchar(30), @varKSDB_Object VARCHAR(128), @varKSintOBJECT INT, @varKSEventText varchar(254)

SET @varKSTASK = (SELECT ltrim(rtrim(CODE_TASK)) FROM dbo.USER_TASK_INFO)
IF @type_table=0
	SET @varKSDB_Object = 'REPORT_SUMMA'
ELSE
	SET @varKSDB_Object = 'REPORT_DINAMICS'

SELECT @varKSintOBJECT = LINK FROM dbo.S_OBJECTS WHERE CODE = 'REPORT_SVOD'

SELECT @varKSEventText = 'Удаление строки из отчета: ' + LTRIM(RTRIM(RF.CODE))
FROM REPORT_FORMS RF, REPORT_SAVED_FORMS RSF WHERE RSF.LINK_Saved_Form = @LSF AND RF.LINK_FORM = RSF.LINK_FORM


-- Отметка в системном журнале об удалении ненулевых строк
INSERT INTO SYS_EVENTS (SID,HOSTNAME,APPNAME,EVENT_DATE,EVENT,TASK,DB_OBJECT,OBJECT,TEXT,LINK_OBJ)
SELECT	[SID] = SUSER_SID(),
	[HOSTNAME] = HOST_NAME(),
	[APPNAME] = APP_NAME(),
	[EVENT_DATE] = GETDATE(),
	[EVENT] = 'Сохранение документа',
	[TASK] = @varKSTASK,
	[DB_OBJECT] = @varKSDB_Object,
	[OBJECT] = @varKSintOBJECT,
	[TEXT] = LEFT(ISNULL(@varKSEventText, 'Удаление строки из неизвестного отчета ') + ', код строки: ' + ltrim(rtrim(b.code_row)),254),
	[LINK_OBJ] = @LSF
FROM #TMP_TABLE_G B
WHERE B.del=1 -- and b.summa <> 0
*/
IF @@ERROR>0
    begin 
       ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
       COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
       RETURN  
    end 

COMMIT TRANSACTION -- Фиксация транзакции.

exec X_UNLOCK_RECORD @nameLock,@LSF

GO
GRANT ALL ON dbo.[RN_SAVE_SUMMA] 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].[RO_WEB_EDIT_0503360]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_EDIT_0503360]
GO




/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB для формы 0503360
*/


CREATE       PROCEDURE dbo.RO_WEB_EDIT_0503360
	@varKSnLink	bigint,
	@varKSnTree	int = 0, -- если форма новая, то линк дерева сводов, иначе - линк дерева кбк
	@varKSisHeader int =0
AS

declare @iLF int
DECLARE @DATE	datetime,
	@PType	tinyint,
	@PNom	tinyint,
	@DATE1 datetime,
	@DATE2 datetime, 
	@Periodic tinyint,
	@LSF	int,
	@Mode	int,
	@LinkOrg int,
	@LinkBudg int,
	@varKSnLinkOld BIGINT,
   @atributs VARCHAR(1000)
set @varKSnLinkOld = @varKSnLink
set @LinkOrg = dbo.RO_SVOD_ORG(@varKSnTree)
set @LinkBudg = dbo.RO_SVOD_BUDG(@varKSnTree)
set @Mode = convert(int, @varKSnLink/4294967296)
set @varKSnLink = @varKSnLink - @Mode * 4294967296
set @Mode = abs(@Mode)

/* Список возвращаемых таблиц */
if @varKSnLink > 0
begin
select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink)
	if  @varKSnTree = 1 -- реквизиты
	begin
			SELECT	[alias] = 'REP_HEAD', 
				[order] = convert(smallint,1),
				[tab_name] = 'Реквизиты',
				[link_table] = convert(varchar(50), 'REPORT_SVOD'),--convert(int,0),
				[table_type] = convert(smallint,2)
			UNION
         SELECT	[alias] = 'REP_ATR', 
	         [order] = convert(smallint, 2),
	         [tab_name] = 'Атрибуты',
	         [link_table] = convert(varchar(50), '-98'),
	         [table_type] = convert(smallint, 0)
             WHERE @atributs<>'' 
         UNION         
			SELECT	[alias] = 'REP_NASTR', 
				[order] = convert(smallint, 99),
				[tab_name] = 'Настройки печати',
				[link_table] = convert(varchar(50), '0'),
				[table_type] = convert(smallint, -1)
			ORDER BY [order]
	end

	if  @varKSnTree = 2 -- таблица с текстом
	begin
		SELECT	[alias] = 'REP_TABLE', 
			[order] = orders + 1,
			[tab_name] = name,
			[link_table] = convert(varchar(50), 'REPORT_TEXT'),
			[table_type] = convert(smallint,2)
		FROM REPORT_TABLES
		WHERE (@varKSnLink>0 and Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink))
			OR (@varKSnLink<0 and Link_Form = abs(@varKSnLink))
		UNION
		SELECT	[alias] = 'REP_NASTR', 
			[order] = convert(smallint, 99),
			[tab_name] = 'Настройки печати',
			[link_table] = convert(varchar(50), '0'),
			[table_type] = convert(smallint, -1)
		ORDER BY [order]
	end
end
else begin -- новая форма
	SELECT	[alias] = 'REP_HEAD', 
		[order] = convert(smallint,1),
		[tab_name] = 'Реквизиты',
		[link_table] = convert(varchar(50), 'REPORT_SVOD'),
		[table_type] = convert(smallint,2)
	UNION
	SELECT	[alias] = 'REP_NASTR', 
		[order] = convert(smallint, 99),
		[tab_name] = 'Настройки печати',
		[link_table] = convert(varchar(50), '0'),
		[table_type] = convert(smallint, -1)
	ORDER by [order]
end


/* Данные об отчете */
if @varKSnLink > 0
begin
	declare @Shifr varchar(10), @orders tinyint
	select @Shifr = Shifr from dbo.REPORT_FORM14_RAZD_NAME where Link = @varKSnTree
	if  @varKSnTree = 1 -- реквизиты
   BEGIN
      CREATE TABLE #REP_HEAD_temp ("checked" Int,"UPD" Int,"del" Int,"date" DateTime,"date_prov" DateTime,"link" Int,"period" VarChar(17),"name" VarChar(200),"code" Char(20),"Start_Date" Char(10),"link_saved_form" Int,"Link_form" Int,"Version" SmallInt,"begin_date" DateTime,"period_type" TinyInt,"period_type_web" Int,"period_number" TinyInt,"period_year" Int,"link_organization" Int,"dep_name" VarChar(254),"dep_code" Char(10),"isUpload" TinyInt,"isSvod" TinyInt,"isChangeAnalit" Bit,"IsRO" TinyInt,"Note" VarChar(4000),"Link_Type_Svod" Int,"Type_Svod" VarChar(250),"IsUsedRazdel" Int,"IsUsedCelSt" Int,"IsUsedRashod" Int,"LinkRazdel" Int,"LinkCelSt" Int,"LinkRashod" Int,"CodeRazdel" VarChar(1),"NameRazdel" VarChar(1),"CodeCelSt" VarChar(1),"NameCelSt" VarChar(1),"CodeRashod" VarChar(1),"NameRashod" VarChar(1),"Print_Object_Method" VarChar(200),"Query_Add_Module" VarChar(200),"Query_Before" VarChar(200),"Query_RepMaker" VarChar(200),"Query_Report" VarChar(200),"Query_Report_Path" VarChar(200),"Decript_Proc" VarChar(30),"IsRemoteAccess" TinyInt,"RULES" TinyInt,"isCalcItog" Int,"IsRO_MASK" Int,"CountSave" Int,"Object" Char(30),[IS_AUTOFILL] TINYINT,"IsCopy" BIT,"End_Date" Char(10), Query_Report_New varchar(250), Print_Object_Method_New varchar(250))
      CREATE TABLE #note (link INT, note_all TEXT)

      INSERT #REP_HEAD_temp
		exec I_REPORT_USER_SAVED_FORM @varKSnLink,null,null,1 -- редактирование
      

      INSERT #note (link, note_all)
      EXEC dbo.RO_SAVED_FORM_NOTES @varKSnLink

	   select T.*, Note_All from #REP_HEAD_temp T, #note N          
      
      drop table #REP_HEAD_temp
      DROP TABLE #note
      
      --атрибуты
       IF @atributs<>''
       begin
           exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,0
       end

   END
	
	if  @varKSnTree = 2 -- текст
	begin
		-- все значения в поле text
		create table #dest (link int, value text)
		create table #sour (link int identity(1,1), link_up int, value varchar(8000))

		insert #dest
		values(@varKSnLink, '')

		insert #sour (link_up, value) 
		select @varKSnLink, str_val from report_dinamics_all where link_sf=     @varKSnLink order by code_row

		exec varchar2text
			@cTableSour ='#sour',
			@cValueSour ='value',
			@cKeySour ='link',
			@cKeyUpSour ='link_up',
			
			@cTableDest ='#dest',
			@cValueDest ='value',
			@cKeyDest ='link'

		select link, value from  #dest
		drop table #dest
		drop table #sour
	end	
end
else
begin -- новый отчет
	exec I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg,1
end

/* Настройки печати */
DECLARE	@iLOrg	int,
	@DocDate	datetime
EXEC @iLOrg = getowndeplink 
IF @varKSnLink>0
	select @iLOrg = link_organization, @DocDate = begin_date from report_saved_forms where link_saved_form = @varKSnLink
ELSE
	select @DocDate = getdate()

select *, convert(char(10), @DocDate + 1, 104) as Doc_Date from dbo.PrintDoc_GetDepData2 (@iLOrg)


GO
GRANT ALL ON dbo.[RO_WEB_EDIT_0503360] 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_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] (20),
	@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
AS
DECLARE @varKSERROR	tinyint,
	@varKStrancount	int, 
	@varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF @CODE IS NULL OR @CODE = '' OR @NAME IS NULL OR @NAME = ''
BEGIN
	ROLLBACK
	RETURN 5
END

--IF EXISTS (SELECT * FROM dbo.SAL_SFIN WHERE LINK <> @LINK AND CODE = @CODE) 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)
		VALUES (@CODE,@NAME,@LINK_KBK,@SOURCE,@USER_ACC,@LINK_DOP_KL,@LINK_KAU,@COMMENT,@ENVD)

	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
	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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_127_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_127_ITOG]
GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать форм 127 (для параметра "все атрибуты в один отчет)
	Печать с подитогами
*/


CREATE       PROCEDURE dbo.RO_PRINT_127_ITOG
	@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
select @iLF = Link_Form, @iYear = YEAR(begin_date) from report_saved_forms where Link_Saved_Form = @LSF

if isnull(@WEB_excel, 0) <> 1
	select '' col1 

-- таблица доходы
exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1

------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
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 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 float, Col15 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, Col15)
exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1

IF @varKSiRashEKR = 1 
BEGIN
   UPDATE #rash
   SET COL7 = 0,
        COL8 = 0
   WHERE RIGHT(RTRIM(CODE),3) <> '000'  
END    

IF @varKSiRashEKR = 2 
BEGIN
   UPDATE #rash
   SET COL7 = 0,
        COL8 = 0
   WHERE RIGHT(RTRIM(CODE),2) <> '00'  
END    

IF @varKSiNoItogRash = 1
BEGIN
   DELETE #rash
   WHERE RIGHT(RTRIM(CODE),3) IN ('200', '210', '220', '230', '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, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(Col15,14) + '000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,14) + '000000', left(Col15,14) + '000000'
end

if @varKSiParam & 4 = 4 -- подитоги по подразделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(col15,7) + '0000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col15,7) + '0000000000000'
end

if @varKSiParam & 8 = 8 -- подитоги по разделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(col15,5) + '000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col15,5) + '000000000000000',left(col3,2) + '00'
end

if @varKSiParam & 16 = 16 -- подитоги по администратору
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(col15,3) + '00000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col15,3) + '00000000000000000'
end

if @varKSiParam & 32 = 32 -- обнуляем подпрограмму в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(Col15,12) + '00000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,12) + '00000000', left(Col15,12) + '00000000'
end

if @varKSiParam & 64 = 64 -- обнуляем программу в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), left(Col15,10) + '0000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col15,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, Col15)
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, Col15 
from #rash_itog

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#RN_VIEW_KBK_ADM_M=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#R_SPR_ADM_2011=LEFT(CODE,3)=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 ALL ON dbo.[RO_PRINT_127_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PF_REPORT2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PF_REPORT2]

GO
CREATE PROCEDURE [dbo].[SA_PF_REPORT2]
--Вычисление суммы уплаты долга в текущем году за прошлый год	
	@YEAR  varchar (4), /* Год */
	@KVART varchar (4),	 /* Квартал */
	@PACHKA varchar (4) /* Номер пачка */

AS 
BEGIN

	DECLARE @DATE1 DATETIME,	/* Начало периода */
			@DATE2 DATETIME	/* Конец периода */

	-- Выборка линка организации 
	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT
	-- Дата начала периода
	set @DATE1 = (@YEAR + '0101')
	-- Дата окончания , по указанному кварталу 
	SET @DATE2 = (@YEAR + ''+(CASE WHEN @KVART = '1' THEN '0331'
								   WHEN @KVART = '2' THEN '0630' 
								   WHEN @KVART = '3' THEN '0930'
								   ELSE	'1231'
								END)+'')

	--Пачки, из которых брать сведения о перечисленных суммах		
	CREATE TABLE #PACHKI (LINK INT)
	if exists (select link from DBO.SZV4_PACHKA where link = @PACHKA and LINK_DEP = @LINK_DEP)
	begin
		INSERT INTO #PACHKI(LINK)
		VALUES(@PACHKA)
	end
	WHILE EXISTS(
				SELECT P.LINK_SELF
				FROM 
					DBO.SZV4_PACHKA P 
					INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF and P.LINK_DEP = @LINK_DEP
				WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
					AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
					AND P2.YEAR_BEGIN = YEAR(@DATE2) AND P2.MONTH_END < MONTH(@DATE2)
				)
	BEGIN			

		INSERT INTO #PACHKI(LINK)
		SELECT P.LINK_SELF
		FROM 
			DBO.SZV4_PACHKA P 
			INNER JOIN DBO.SZV4_PACHKA P2 ON P2.LINK = P.LINK_SELF and P.LINK_DEP = @LINK_DEP
		WHERE EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK)
			AND NOT EXISTS (SELECT * FROM #PACHKI P1 WHERE P1.LINK = P.LINK_SELF)
			AND P2.YEAR_BEGIN = YEAR(@DATE2) AND P2.MONTH_END < MONTH(@DATE2)
	END
	
	DELETE FROM #PACHKI WHERE LINK = @PACHKA

	--Сведения о перечисленных суммах
	CREATE TABLE #PERECHISL (LINK INT, SUM_STR NUMERIC(18,2), SUM_NAK NUMERIC(18,2))
	
	INSERT INTO #PERECHISL (LINK, SUM_STR, SUM_NAK)
	SELECT link_pers, SUM(SUM_UPLATA_DOLGA_STR), SUM(SUM_UPLATA_DOLGA_NAK)
	FROM
		#PACHKI P INNER JOIN dbo.SZV4_SVEDENIA S ON P.LINK = S.LINK_UP
	GROUP BY
		link_pers
	HAVING
		SUM(SUM_UPLATA_DOLGA_STR) > 0
		OR 	SUM(SUM_UPLATA_DOLGA_NAK) > 0	
	
	--Список физ лиц, по которым есть сведения о начисленных, либо перечисленных суммах
	CREATE TABLE #PERS(LINK INT)
	
	INSERT INTO #PERS (LINK)
	SELECT DISTINCT LINK FROM #PERECHISL

	SELECT
		P.LINK, 
		FIO = LEFT(RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.', 100),
		BIRTH = BIRTHDATE,
		INSUR_NUM,
		AGE_TYPE = CASE WHEN YEAR(P.BIRTHDATE) <= 1966 THEN 1 ELSE 2 END,
		SUM_STR_P = PS.SUM_STR,
		SUM_NAK_P = PS.SUM_NAK
	FROM
		#PERS F
		INNER JOIN dbo.PERSON P ON P.LINK = F.LINK
		LEFT JOIN #PERECHISL PS ON PS.LINK = F.LINK
	ORDER BY
		FIO 	
	
	DROP TABLE #PACHKI
	DROP TABLE #PERECHISL
	DROP TABLE #PERS

END



GO


GRANT EXECUTE ON dbo.[SA_PF_REPORT2] TO PUBLIC

GO

GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_CREDIT_CARD_DOLG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_CREDIT_CARD_DOLG]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
c Кейсистемс (Keysystems), 2005
*/

create  procedure dbo.BB_CREDIT_CARD_DOLG
	@cBufId 	char(100),
	@dDateB 	datetime,
	@dDateE 	datetime,
	@iAcc207 	tinyint,
	@iTypeRep 	tinyint = 1,
	@iDepLink 	int = 0,
	@cVal1 		char(1), 
	@nOtborLink1 	int,
	@cVal2 		char(1), 
	@nOtborLink2 	int
	

as
declare @iOwnDep	int,
		@dDateRest  datetime
	
declare @tRest table(DEP int,
		      		 ACC_LINK int,
					 GRUP	int,
					 [TYPE]	tinyint,
					 SUMMA numeric(28,2))


set @iOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

if @cBufId is null or @cBufId = ''
begin
	set @cBufId = 'BB_DOLG'
	exec dbo.BufferClear @cBufId
	
	insert into BUFFER (link, id)
	select C.link, @cBufId 
	from BB_P_CREDIT C
	where C.DEP_LINK = @iOwnDep and 
			C.DATE_BEG <= @dDateE and C.DATE_END >= @dDateB and
	      (@iDepLink <> 0 and C.KDEP_LINK = @iDepLink or 
			(@iDepLink = 0 and (len(@cVal1) = 0  or len(@cVal1) <> 0 
			and EXISTS (select * from dbo.OBJECT_VAR_DEPARTMENT OVD where OVD.RECORD = C.KDEP_LINK AND OVD.LINK_UP = @nOtborLink1)))) 

			/*inner join dbo.OBJECT_VAR_CREDIT_TYPE OVC on OVC.RECORD = CH.TYPE AND OVC.LINK_UP = @nOtborLink2*/ 
	
end
IF @dDateB IS NULL
	select @dDateB = MIN(DATE)
	from G_PROV 
	where OBJECT in (select link from S_OBJECTS WHERE CODE = 'BB_P_CREDIT') and 
		(@cBufId is null or @cBufId = '' or link in (select * from dbo.BufferGetTableByID(@cBufId))) and
		DEP = @iOwnDep
IF @dDateE IS NULL
	select @dDateE = MAX(dbo.BB_CREDIT_DATE_END(LINK, default, default))
	from G_PROV 
	where OBJECT in (select link from S_OBJECTS WHERE CODE = 'BB_P_CREDIT') and
		(@cBufId is null or @cBufId = '' or link in (select * from dbo.BufferGetTableByID(@cBufId))) and
		DEP = @iOwnDep

exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_P'
exec dbo.BufferClear 'SGU_K_KL_N'

insert into BUFFER (link, id)
select link, 'CREDIT_ACC' from s_accounts where code like '%301.%'

insert into BUFFER (link, id)
select link, 'CREDIT_PER' from s_accounts where code like '%210.02%' or code like '%201.07%' or code like '%201.11%' or code like '%401.30%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL' from s_accounts where code like '%304.05%' or code like '%201.07%' or code like '%201.11%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL_N' from s_accounts where code like '%401.[1-2]0%'

insert into BUFFER (link, id)
select O.LINK, 'OSNOV' 
from dbo.BD_OSNOV O
inner join dbo.G_PROV G on G.LINK = O.DOC_LINK and G.LINK in (select * from dbo.BufferGetTableByID(@cBufId))

insert into BUFFER (link, id)
select link, 'SGU_D' from dbo.KOSGU where CODE like '8%'

insert into BUFFER (link, id)
select link, 'SGU_K' from dbo.KOSGU where CODE like '7%'

insert into BUFFER (link, id)
select link, 'SGU_K_P' from dbo.KOSGU where CODE like '23%'

insert into BUFFER (link, id)
select link, 'SGU_K_PL_N' from dbo.KOSGU where CODE like '171'



-- Раздел 1
declare @tTempRasdel1 table(OBJECT		varchar(254),
					    LINK	int,
						DOC_NUM		char(25),
					    DOC_DATE	datetime,
					    OPER_NAME	varchar(254),
					    OPER_DATE	datetime,
					    SUM_PER		numeric(28,2),
					    SUM_PL		numeric(28,2),
					    SUM_PR 		numeric(28,2),
						DEP			int,
		      			DOC_LINK	int,
		      			ACC_LINK	int)

declare @tRasdel1 table(TYPE		int,
		      			ACC_LINK	int,
					DOC_NAME	varchar(254),
					DOC_NUM		char(25),
					DOC_DATE	datetime,
					OPER_NAME	varchar(254),
					OPER_DATE	datetime,
					SUM_PER		numeric(28,2),
					SUM_PL		numeric(28,2),
					SUM_PR 		numeric(28,2),
					SORT		tinyint,
					P_LINK		int,
					DOC_LINK	int,
					GRUP		INT)



insert into @tTempRasdel1
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV,S.SUMMA, 0, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1), KT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PER', 'CREDIT_ACC',
			 null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA,  0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1), DT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV,  0, 0, S.SUMMA, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1), DT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL_N',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0, 0, S.SUMMA, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1), KT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S



-- Раздел 2
declare @tTempRasdel2 table(OBJECT	varchar(254),
			    LINK	int,
			    DOC_NUM	char(25),
			    DOC_DATE	datetime,
			    OPER_NAME	varchar(254),
			    OPER_DATE	datetime,
			    SUM_PER	numeric(28,2),
			    SUM_PL	numeric(28,2),
			    SUM_PR 	numeric(28,2),
				DEP			int,
		      	DOC_LINK	int,
		      	ACC_LINK	int)

declare @tRasdel2 table(TYPE		int,
		      			ACC_LINK	int,
			DOC_NAME	varchar(254),
			DOC_NUM		char(25),
			DOC_DATE	datetime,
			OPER_NAME	varchar(254),
			OPER_DATE	datetime,
			SUM_PER		numeric(28,2),
			SUM_PL		numeric(28,2),
			SUM_PR 		numeric(28,2),
			SORT		tinyint,
			P_LINK		int,
			DOC_LINK	int,
			GRUP		INT)

insert into @tTempRasdel2
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, S.SUMMA, 0, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1), KT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1), DT_ACCOUNT
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null) S


if @iAcc207 = 0
begin
	insert into @tRest
	select C.KDEP_LINK, NULL, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 0, sum(dbo.BB_CREDIT_REST(C.LINK, @dDateB,0))
	from dbo.BB_P_CREDIT C 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end
	
	insert into @tRest
	select C.KDEP_LINK, NULL, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 2, sum(dbo.BB_CREDIT_REST(C.LINK, @dDateE,0))
	from dbo.BB_P_CREDIT C 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end
	
	insert into @tRest
	select  C.KDEP_LINK, NULL, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 1,
			sum(dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'PROC','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_NECELEV','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_CREDIT','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_PROC',''))
	from dbo.BB_P_CREDIT C
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK,  case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end

	insert into @tRest
	select C.KDEP_LINK, NULL, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 3,
			sum(dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'PROC','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_NECELEV','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_CREDIT','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_PROC',''))
	from dbo.BB_P_CREDIT C
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK,  case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end

end
else
begin
	insert into @tRest
	select R.DEP, R.ACCOUNT, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end,
				case KBK.TYPE when 1 then 1 else 0 end, 
				sum(R.K_SUMMA - R.D_SUMMA) 
		from dbo.aRestTableByDateAccounts(@dDateB,'CREDIT_ACC') R
		inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
		inner join dbo.BD_OSNOV O on R.AP1 = O.LINK  
		inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
		where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
		group by R.DEP, R.ACCOUNT, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end, KBK.TYPE
set @dDateE = @dDateE + 1
	insert into @tRest
	select R.DEP, R.ACCOUNT, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end,
				2 + case KBK.TYPE when 1 then 1 else 0 end , 
				sum(R.K_SUMMA - R.D_SUMMA) 
		from dbo.aRestTableByDateAccounts(@dDateE,'CREDIT_ACC') R
		inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
		left join dbo.BD_OSNOV O on R.AP1 = O.LINK  
		inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
		where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
		group by R.DEP, R.ACCOUNT, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end, KBK.TYPE
end


insert into @tRasdel1
select  C.TYPE,
		S.ACC_LINK,
		DOC_NAME	= dbo.JurnalProvGetDocKind (S.LINK, S.OBJECT),
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		S.OPER_NAME,
		S.OPER_DATE,
		S.SUM_PER,
		S.SUM_PL,
		S.SUM_PR,
		SORT		= 2,
		C.KDEP_LINK,
		C.LINK,
		GPUP = case @iTypeRep when 1 then isnull(C.KDEP_LINK, S.DEP)
								when 2 then isnull(C.TYPE, '')
								when 3 then O.DOC_LINK else '' end
from @tTempRasdel1 S
left join dbo.BD_OSNOV O on S.DOC_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK and C.LINK in (select * from dbo.BufferGetTableByID(@cBufId))


insert into @tRasdel2
select  C.TYPE,
		S.ACC_LINK,
		DOC_NAME	= dbo.JurnalProvGetDocKind (S.LINK, S.OBJECT),
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		S.OPER_NAME,
		S.OPER_DATE,
		S.SUM_PER,
		S.SUM_PL,
		S.SUM_PR,
		SORT		= 2,
		C.KDEP_LINK,
		C.LINK,
		GPUP = case @iTypeRep when 1 then isnull(C.KDEP_LINK, S.DEP)
								when 2 then isnull(C.TYPE, '')
								when 3 then O.DOC_LINK else '' end
from @tTempRasdel2 S
left join dbo.BD_OSNOV O on S.DOC_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK and C.LINK in (select * from dbo.BufferGetTableByID(@cBufId))


--declare @tDocTable table(DOC_LINK	int, POL_LINK	int, TYPE int)
declare @tDocTable table( ACC_LINK int,DEP int, GRUP int)



insert into @tDocTable
select ACC_LINK, P_LINK, GRUP from @tRasdel2 union
select ACC_LINK, P_LINK, GRUP from @tRasdel1 union
select ACC_LINK, DEP, GRUP from @tRest
 


select 	--DOC_LINK = DT.DOC_LINK,
		DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		SUM_REST_B = isnull(RB.SUMMA,0),
		SUM_REST_E = isnull(RE.SUMMA,0),
		OPER_NAME = isnull(R.OPER_NAME,''),
		R.OPER_DATE,
		SUM_PER = isnull(R.SUM_PER,0),
		SUM_PL = isnull(R.SUM_PL,0),
		SUM_PR = isnull(R.SUM_PR,0),
		P_LINK = D.LINK, 
		P_CODE = D.CODE, 
		P_NAME = D.[NAME], 
		--DT.TYPE, 
		DATE_B = C.DATE_BEG,
		DATE_E = C.DATE_END,
		ACC_CODE = SA.CODE,
		TYPE_CODE = coalesce(CT.CODE,C.TYPE_CODE), 
		[TYPE_NAME] = coalesce(CT.[NAME], rtrim(C.[TYPE_NAME]) + ' (договор №' + rtrim(ltrim(C.NUMBER)) + ')'),
		DT.GRUP  
from @tDocTable DT
inner join dbo.DEPARTMENTS D   on D.LINK = DT.DEP
left join dbo.BB_P_CREDIT C ON @iTypeRep = 3 and  C.LINK  = DT.GRUP
left join dbo.CREDIT_TYPES CT ON @iTypeRep = 2 and CT.LINK  = DT.GRUP
left join @tRasdel1 R on (DT.GRUP = R.GRUP or DT.GRUP is null and R.GRUP is null) and R.P_LINK = DT.DEP
left join @tRest RB on RB.GRUP = DT.GRUP and RB.[TYPE] = 0
left join @tRest RE on RE.GRUP = DT.GRUP and RE.[TYPE] = 2
left join S_ACCOUNTS SA on SA.LINK = DT.ACC_LINK
order by DT.GRUP, P_LINK, DOC_NAME, R.DOC_DATE, SUM_PL, SORT


select 	--DOC_LINK = DT.DOC_LINK,
		DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		SUM_REST_B = isnull(RB.SUMMA,0),
		SUM_REST_E = isnull(RE.SUMMA,0),
		OPER_NAME = isnull(R.OPER_NAME ,''),
		R.OPER_DATE,
		SUM_PER = isnull(R.SUM_PER,0),
		SUM_PL = isnull(R.SUM_PL,0),
		SUM_PR = isnull(R.SUM_PR,0),
		P_LINK = D.LINK, 
		P_CODE = D.CODE, 
		P_NAME = D.[NAME], 
		--DT.TYPE, 
		ACC_CODE = SA.CODE,
		TYPE_CODE = isnull(CT.CODE,''), 
		[TYPE_NAME] = coalesce(CT.[NAME], rtrim(C.[TYPE_NAME]) + ' (договор №' + rtrim(ltrim(C.NUMBER)) + ')'),
		DT.GRUP    
from @tDocTable DT
inner join dbo.DEPARTMENTS D   on D.LINK = DT.DEP
left join dbo.BB_P_CREDIT C ON @iTypeRep = 3 and  C.LINK  = DT.GRUP
left join dbo.CREDIT_TYPES CT ON @iTypeRep = 2 and CT.LINK  = DT.GRUP
left join @tRasdel2 R on (DT.GRUP = R.GRUP or DT.GRUP is null and R.GRUP is null) and R.P_LINK = DT.DEP
left join @tRest RB on RB.GRUP = DT.GRUP and RB.[TYPE] = 1
left join @tRest RE on RE.GRUP = DT.GRUP and RE.[TYPE] = 3
left join S_ACCOUNTS SA on SA.LINK = DT.ACC_LINK
order by  DT.GRUP, P_LINK, DOC_NAME, R.DOC_DATE, SUM_PL, SORT


exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_KL_N'

return 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant all on dbo.BB_CREDIT_CARD_DOLG to public
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_SAVE_AKT_MZ_FROM_NEEDS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_SAVE_AKT_MZ_FROM_NEEDS]
GO

--- ФОРМИРОВАНИЕ АКТА СПИСАНИЯ МЗ ИЗ ВЕДОМОСТИ ВЫДАЧИ МЗ --- 
CREATE PROCEDURE dbo.BK_SAVE_AKT_MZ_FROM_NEEDS
	@parm_intLINK_MAIN	INT,
	@parm_intLINK_REF	INT	OUTPUT
AS
BEGIN
	DECLARE
		@intOBJ_REF	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		@strDOC_NUMBER	VARCHAR (30),
		@strMAIN_NUMBER	VARCHAR (30),
		@dDOC_DATE	DATETIME,
		@dDATE_REST	DATETIME,
		@intERROR	INT,

		@intNOMEN		INT,
		@intLINK_ROW	INT,
		@intORDERS		INT,
		@PRICE			NUMERIC (18,4), 
		@PRICE_FACT		NUMERIC (18,4), 
		@QTY_REST		NUMERIC (28,4),
		@SUM_REST		NUMERIC (28,4),
		@QTY_OUT		NUMERIC (28,4),
		@SUM_OUT		NUMERIC (28,4),

		@intACCOUNT	INT,
		
		-- ---
		@strOBJ_REF_CODE	VARCHAR (30),
		@strDOC_REF_CODE	VARCHAR (30),
		@strCOMMENT	VARCHAR (254),
		@intEMPL	INT,
		@intSUB		INT,
		@lnTAX_RATE	NUMERIC (4,2),
		@intTYPE_NUMBER		INT -- 0 - номер док-та генерируется, 1 - номер равен номеру СЧФК

	SELECT @strOBJ_REF_CODE	= 'BA_DOC_MZ_NEEDS_LINK_AKT',	-- Ссылка на созданный документ (межд. связь)
		@strDOC_REF_CODE = 'BA_DOCUMENTS_MZ_CHARGE',		-- Код документа, который требуется сформировать
		@intTYPE_NUMBER = 0

	EXEC @intOBJ_REF = dbo.X_GET_OBJ_LINK @strOBJ_REF_CODE 

	/* -- РЕКВИЗИТЫ ИЗ ВЕДОМОСТИ -- */
	SELECT 	@intDEP_LINK	=	G.DEP_LINK,
		@dDOC_DATE	=	G.[DATE],
		@strMAIN_NUMBER = 	G.NUMBER,
		@intACC_LINK	=	G.ACC_LINK,
		@intEMPL		=	G.LINK_MOL,
		@intSUB	=	G.LINK_SUB
	FROM dbo.BA_DOCUMENTS_MZ_NEEDS G 
	WHERE G.LINK = @parm_intLINK_MAIN

	SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE)

	--- ФОРМИРОВАНИЕ ДОКУМЕНТА --- 
	--- Создание ---
	IF @intTYPE_NUMBER = 1
		SET @strDOC_NUMBER = @strMAIN_NUMBER
	ELSE
		EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER @strDOC_REF_CODE, @strDOC_NUMBER output, @intDEP_LINK
	
	SET @parm_intLINK_REF = (SELECT LINK FROM dbo.XK_GetTable_Doc_FOREIGN (@parm_intLINK_MAIN)
					WHERE DOC_CODE = @strDOC_REF_CODE)

	SELECT @strCOMMENT = 'Автосформировано из ведомости выдачи МЗ № ' + RTRIM (@strMAIN_NUMBER) + 
		' от ' + CONVERT (VARCHAR (10), @dDOC_DATE, 104)

	EXEC @intERROR = dbo.X_SAVE_BA_DOCUMENTS_MZ_CHARGE @parm_intLINK_REF OUTPUT, @strDOC_NUMBER,
		@dDOC_DATE, DEFAULT, DEFAULT, @strCOMMENT, @intDEP_LINK, @intACC_LINK, DEFAULT, 
		@intSUB, @intEMPL, @strCOMMENT

	IF @intERROR <> 0
		RETURN @intERROR
	
	IF @parm_intLINK_REF IS NULL
	BEGIN
		RAISERROR ('Документ не сформирован!', 11, 1)
		RETURN 1
	END

	EXEC dbo.X_UPDATE_G_PROV_REF
		@parm_intLINK_MAIN,
		@intOBJ_REF,
		@parm_intLINK_REF

	--- !!! СОХРАНЕНИЕ КОМИССИИ !!! ---
	EXEC @intERROR = dbo.BK_FILL_COMISSION_IN_DOC @parm_intLINK_REF
	IF @intERROR <> 0
		RETURN @intERROR
		
	--- !!!СОХРАНЯЕМ ТАБЛИЧНУЮ ЧАСТЬ!!! --- 
	-- Табличная часть Ведомости на выдачу --
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT
				R.ACCOUNT,
	
				T.INV_LINK,
				ISNULL (T.GIVE, 0),
				ISNULL (R.PRICE, 0),
				ISNULL (R.D_QUANTITY, 0),
				ISNULL (R.D_SUMMA, 0)
		FROM dbo.BA_VIEW_MZ_NEEDS_INV T
		LEFT JOIN dbo.ARestGroupedTableByDate (@dDATE_REST, DEFAULT, 56) R
				ON (R.NOMEN = T.INV_LINK
					AND R.DEP_LINK = @intDEP_LINK
					AND ISNULL (R.EMP, 0) = ISNULL (T.EMPL_LINK, 0))
		WHERE T.LINK_DOC = @parm_intLINK_MAIN 
			AND T.INV_TYPE = 'BV_NOMENCLATURE'
		ORDER BY INV_CODE

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @intACCOUNT,
			@intNOMEN, @QTY_OUT, @PRICE_FACT, @QTY_REST, @SUM_REST

	SET @intORDERS = 0
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @intLINK_ROW = NULL
		SET @intORDERS = @intORDERS + 1
	
		SET @PRICE = CASE
							WHEN @PRICE_FACT = 0 THEN 
								CASE WHEN @QTY_REST <> 0 THEN @SUM_REST / @QTY_REST ELSE 0 END
							ELSE
								@PRICE_FACT 
					END

		SET @SUM_OUT = ISNULL (@PRICE, 0) * @QTY_OUT

		EXEC @intERROR = dbo.BK_SAVE_MZ_CHARGE_TABLE
			@intLINK_ROW OUTPUT,
			@parm_intLINK_REF,
			@intORDERS,

			@intACCOUNT,
			@intNOMEN,
			@QTY_REST,
			@QTY_OUT,
			@SUM_OUT,
			@PRICE,
			@PRICE_FACT

		IF @intERROR <> 0
			RETURN @intERROR

		FETCH NEXT FROM #DATA_CURSOR
			INTO @intACCOUNT,
				@intNOMEN, @QTY_OUT, @PRICE_FACT, @QTY_REST, @SUM_REST

	END

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	RETURN 0
END
GO


GRANT EXECUTE ON dbo.[BK_SAVE_AKT_MZ_FROM_NEEDS] TO PUBLIC
GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SAVE_DOC_LINKS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SAVE_DOC_LINKS]

GO





/*
© Кейсистемс (Keysystems), 2005
*/








CREATE PROCEDURE [dbo].DP_SAVE_DOC_LINKS 
  @varKSparLINK    INT, 	
  @varKSparLinkRef INT   
AS

DECLARE @varKSERROR       TINYINT,
        @varKStrancount   INT,		
        @varKSSQLError    INT,
        @varKSCardLinkObj INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON

BEGIN TRAN
COMMIT TRAN

SELECT @varKSCardLinkObj = LINK FROM S_OBJECTS WHERE CODE = 'WF_CARD_LINK' 

IF (@varKSparLINK IS NULL) OR (@varKSparLINK = 0) OR (@varKSparLinkRef IS NULL) OR (@varKSparLinkRef = 0)
BEGIN
     ROLLBACK
     RETURN 5
END


SET @varKSparLINK = (SELECT @varKSparLINK FROM dbo.DOCUMENTS WITH (UPDLOCK) WHERE LINK = @varKSparLINK)
SET @varKSparLinkRef = (SELECT @varKSparLinkRef FROM dbo.DOCUMENTS WITH (UPDLOCK) WHERE LINK = @varKSparLinkRef)

IF (@varKSparLINK IS NULL) OR (@varKSparLinkRef IS NULL)
BEGIN
     ROLLBACK
     RETURN 2
END

INSERT INTO DOCUMENTS_REF (REF_UP,REF_DOWN,OBJECT)
VALUES (@varKSparLINK,@varKSparLinkRef,@varKSCardLinkObj)

SELECT @varKSSQLError = @@ERROR
IF @varKSSQLError <> 0
BEGIN
     ROLLBACK
     RETURN 7
END

IF (@varKSparLINK <> @varKSparLinkRef)
   INSERT INTO DOCUMENTS_REF (REF_UP,REF_DOWN,OBJECT)
   VALUES (@varKSparLinkRef,@varKSparLINK,@varKSCardLinkObj)

SELECT @varKSSQLError = @@ERROR
IF @varKSSQLError <> 0
BEGIN
     ROLLBACK
     RETURN 7
END

   IF NOT (dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
	OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
		exec EOS_EXPORT_REPORT @varKSparLinkRef

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0








GO


GRANT EXECUTE ON dbo.[DP_SAVE_DOC_LINKS] TO PUBLIC

GO

GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_UVED_817_69N_CREATE_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_UVED_817_69N_CREATE_TABLE]
GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE dbo.BB_UVED_817_69N_CREATE_TABLE @iDocLink int, @iDel tinyint

as
Declare	@iError		int,
		@nSumma		numeric(20,2),
		@iCount		int,
		@dDocDate	datetime,
		@dDateB		datetime,
		@dDateBY	datetime,
		@dDateE		datetime,
		@iDepLink	int,
		@iAccLink	int,
		@iPDepLink	int,
		@iPunkt1	tinyint,
		@iLink206	int,
		@iLink205	int,
		@cPBudgEl	char(2),
		@cPAdmCode	char(3),
		@iSGUP		int,
		@iNastrKBK int
		
set @iNastrKBK = isnull(dbo.XK_GET_NASTR_INT('BB_UVED_817_69N_NASTR_KBK'),1)
declare @tTemp table(KBK	int, 
					EKR		int, 
					DCL		int, 
					SUMMA_R	numeric(20,2), 
					SUMMA_N	numeric(20,2), 
					SUMMA_P	numeric(20,2), 
					SUMMA_POL1	numeric(20,2), 
					SUMMA_POL	numeric(20,2), 
					KBK_P	numeric(20,2))
	
select	@dDocDate = DATE,
		@iDepLink = DEP,
		@iAccLink = ACC
from dbo.G_PROV where LINK = @iDocLink

select @dDateB = DATE_B, @dDateE = DATE_E from dbo.BB_UVED_817_69N_NASTR
select @iSGUP = LINK from dbo.KOSGU where CODE = '151'		

select @iPDepLink = GPD.DEPARTMENT, @cPBudgEl = PBUDG.CODE_EL, @cPAdmCode = PVED.CODE
from dbo.G_PROV_DEPARTMENT GPD WITH (NOLOCK) 
left join dbo.DEPARTMENTS PD WITH (NOLOCK) on PD.LINK = GPD.DEPARTMENT 
left join dbo.KL_ADMIN_BS PVED WITH (NOLOCK) on PVED.LINK = PD.VED_LINK
left join dbo.KL_BUDG_TYPE PBUDG WITH (NOLOCK) on PVED.LINK_bUDG = PBUDG.LINK
where	DOC_LINK = @iDocLink and 
		OBJECT = (select LINK from dbo.S_OBJECTS where CODE = 'BB_UVED_817_69N_PDEP_LINK')
if @dDateE is null 
	set @dDateE = @dDocDate
	
if @dDateB is null 
	set @dDateB = dbo.DateBeginOfYear(@dDateE)

set @dDateBY = dbo.DateBeginOfYear(@dDateB)

select @iPunkt1 = CONVERT(int, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=@iDocLink and gpv.object=(select link from s_objects where code='BB_UVED_817_69N_P1')))

if @iDel = 1
	delete from dbo.UVED_817_TABLE where LINK_UP = @iDocLink

EXEC dbo.[BufferClear] '30251'
EXEC dbo.[BufferClear] '503'
EXEC dbo.[BufferClear] '20651'
EXEC dbo.[BufferClear] '20551'
EXEC dbo.[BufferClear] '40110'


INSERT dbo.BUFFER(LINK, [ID])
SELECT [LINK], '30251' 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '302' AND cAnalit = '51'

INSERT dbo.BUFFER(LINK, [ID])
SELECT [LINK], '20651' 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '206' AND cAnalit = '51'

INSERT dbo.BUFFER(LINK, [ID])
SELECT [LINK], '20551' 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '205' AND cAnalit = '51'

INSERT dbo.BUFFER(LINK, [ID])
SELECT [LINK], '40110' 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '401' AND cAnalit = '10'

INSERT dbo.BUFFER(LINK, [ID])
SELECT [LINK], '503' 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '503' AND (cAnalit = '04' or cAnalit = '14' or cAnalit = '03' or cAnalit = '13')

SELECT @iLink206 = LINK 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '206' AND cAnalit = '51'

SELECT @iLink205 = LINK 
FROM dbo.S_ACCOUNTS 
WHERE ZABALANS = 0  AND cSource = '1'  AND cSinth = '205' AND cAnalit = '51'

insert into @tTemp
select S.KBK, S.EKR, S.DCL, 
		SUMMA_R = case @iPunkt1 when 1 then S.SUMMA_R - isnull(R.SUMMA_R,0) else 0 end,
		SUMMA_N = case @iPunkt1 when 2 then S.SUMMA_N - isnull(R.SUMMA_N,0) else 0 end, 
		SUMMA_P = case @iPunkt1 when 3 then S.SUMMA_P - isnull(R.SUMMA_P,0) else 0 end,
		SUMMA_POL1 = case @iPunkt1 when 1 then S.SUMMA_POL1 - isnull(R.SUMMA_POL1,0) else 0 end,
		SUMMA_POL = case @iPunkt1 when 4 then S.SUMMA_POL - isnull(R.SUMMA_POL,0) else 0 end,
		case @iNastrKBK when 1 then KBK_P.LINK else S.KBK_P end
from (select KBK = KT_VKR, EKR = KT_EKR, DCL = KT_AP2, SUMMA_R = 0, SUMMA_N = sum(ISNULL(SUMMA, 0)), SUMMA_P = 0, SUMMA_POL1 = 0 , SUMMA_POL = 0, KBK_P = NULL 
			FROM dbo.AProvByBufferConditionsShort(@dDateB, @dDateE, null, '503') 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 2 and
					(DT_DEP_ACC = @iAccLink or KT_DEP_ACC = @iAccLink) AND
					(DT_DEP = @iPDepLink OR KT_DEP = @iPDepLink)
			GROUP BY KT_VKR, KT_EKR, KT_AP2 union 
	select KBK = KT_VKR, EKR = KT_EKR, DCL = KT_AP2, 0, 0, SUMMA_P = sum(ISNULL(SUMMA, 0)), 0,0, KBK_P = DT_VKR
			FROM dbo.AProvByBufferConditionsShort(@dDateB, @dDateE, null, '30251') 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 3 and
					(DT_DEP = @iPDepLink OR KT_DEP = @iPDepLink)
			GROUP BY KT_VKR, KT_EKR, KT_AP2, DT_VKR union 
	select KBK = DT_VKR, EKR = KT_EKR, DCL = KT_AP2, 0, 0, SUMMA_P = sum(ISNULL(SUMMA, 0)), 0,0, KBK_P = KT_VKR
			FROM dbo.AProvByBufferConditionsShort(@dDateB, @dDateE, '40110', '20551') 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 3 and
					(DT_DEP = @iPDepLink OR KT_DEP = @iPDepLink)
			GROUP BY KT_VKR, KT_EKR, KT_AP2, DT_VKR union 
	select KBK = DT_VKR, EKR = KT_EKR, DCL = KT_AP2, 0, 0,  0,0, SUMMA_P = sum(ISNULL(SUMMA, 0)),KBK_P = KT_VKR
			FROM dbo.AProvByBufferConditionsShort(@dDateB, @dDateE, '20651', '20551') 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 4 and
					(DT_DEP = @iPDepLink OR KT_DEP = @iPDepLink)
			GROUP BY KT_VKR, KT_EKR, KT_AP2, DT_VKR union 
	select KBK = DT_VKR, EKR = KT_EKR, DCL = KT_AP2, SUMMA_R = sum(ISNULL(SUMMA, 0)), 0, 0, 0,0, KBK_P = KT_VKR
			FROM dbo.AProvByBufferConditionsShort(@dDateB, @dDateE, '20551', '20551') 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 1 and
					(DT_DEP = @iPDepLink OR KT_DEP = @iPDepLink)
			GROUP BY KT_VKR, KT_EKR, KT_AP2, DT_VKR union 
	select KBK, SGU.LINK, DCL = AP2, 0, 0, 0, sum(ISNULL(D_SUMMA - K_SUMMA, 0)), 0, NULL
			FROM dbo.ARestTableByDate(@dDateBY, @iLink205) 
			inner join dbo.KOSGU SGU on SGU.CODE = '251' 
			WHERE DEP_LINK = @iDepLink AND @iPunkt1 = 1 and
					DEP = @iPDepLink
			GROUP BY KBK, SGU.LINK, AP2) S
left join dbo.KL_KBK KBK on KBK.LINK = S.KBK 
left join (select isnull(KBKP1.LINK,KBKP.LINK) as LINK, KBKL.LINK_KBK from dbo.KL_KBK_LINKED KBKL 
			inner join dbo.KL_KBK KBKP on KBKP.LINK = KBKL.LINK and (substring(replace(KBKP.CODE,'.',''),12,2) = @cPBudgEl OR substring(replace(KBKP.CODE,'.',''),12,2) = '00') and (left(KBKP.CODE,3) = @cPAdmCode or left(KBKP.CODE,3) = '000')  
			left join dbo.KL_KBK KBKP1 on substring(replace(KBKP.CODE,'.',''),12,2) = '00' and left(KBKP.CODE,3) = '000' and @cPAdmCode + substring(replace(KBKP.CODE,'.',''),4,8) + @cPBudgEl + right(replace(KBKP.CODE,'.',''),4) = replace(KBKP1.CODE,'.','') union
			select isnull(KBKP1.LINK,KBKP.LINK), KBKL.LINK from dbo.KL_KBK_LINKED KBKL 
			inner join dbo.KL_KBK KBKP on KBKP.LINK = KBKL.LINK_KBK and (substring(replace(KBKP.CODE,'.',''),12,2) = @cPBudgEl or substring(replace(KBKP.CODE,'.',''),12,2) = '00') and (left(KBKP.CODE,3) = @cPAdmCode or left(KBKP.CODE,3) = '000')
			left join dbo.KL_KBK KBKP1 on substring(replace(KBKP.CODE,'.',''),12,2) = '00' and left(KBKP.CODE,3) = '000' and @cPAdmCode + substring(replace(KBKP.CODE,'.',''),4,8) + @cPBudgEl + right(replace(KBKP.CODE,'.',''),4) = replace(KBKP1.CODE,'.','')) KBK_P ON KBK_P.LINK_KBK = KBK.LINK
left join (select LINK_KBK, LINK_SGU, LINK_DCL, 
					SUMMA_R = sum(SUMMA_PER) , 
					SUMMA_N = sum(SUMMA_UTV) , 
					SUMMA_P = sum(SUMMA_RASH), 
					SUMMA_POL1 = sum(SUMMA_POL1), 
					SUMMA_POL = sum(SUMMA_POL),
					KBK_P =  LINK_KBKP
			from dbo.UVED_817_TABLE T
			INNER JOIN dbo.BB_UVED_817_69N D on D.LINK = T.LINK_UP and 
											D.DATE_PROV is not null and D.DATE_PROV between @dDateB and @dDocDate and
											D.DEP_LINK = @iDepLink AND 
											D.ACC_LINK = @iAccLink AND
											D.PDEP_LINK = @iPDepLink
			GROUP BY LINK_KBK, LINK_SGU, LINK_DCL,LINK_KBKP) R on S.KBK = R.LINK_KBK and 
														S.EKR = R.LINK_SGU and 
														(S.DCL = R.LINK_DCL OR S.DCL is null and R.LINK_DCL is null)and 
														(case @iNastrKBK when 1 then KBK_P.LINK else S.KBK_P end = R.KBK_P OR case @iNastrKBK when 1 then KBK_P.LINK else S.KBK_P end is null and R.KBK_P is null)


select @nSumma = isnull(sum(case @iPunkt1 when 1 then SUMMA_R
											when 2 then SUMMA_N
											when 3 then SUMMA_P
											when 4 then SUMMA_POL end),0) from @tTemp
											
insert into UVED_817_TABLE(LINK_UP, LINK_KBK, LINK_SGU, LINK_DCL, LINK_KBKP, LINK_SGUP, SUMMA_PER, SUMMA_UTV, SUMMA_RASH, SUMMA_POL1, SUMMA_POL)
select @iDocLink, KBK, EKR, DCL, KBK_P, @iSGUP, SUMMA_R, SUMMA_N, SUMMA_P, SUMMA_POL1, SUMMA_POL from @tTemp where SUMMA_N <> 0 or SUMMA_P <> 0 or SUMMA_POL <> 0 or SUMMA_POL1 <> 0 or SUMMA_R <> 0
set @iCount = @@rowcount

EXEC dbo.[BufferClear] '30251'
EXEC dbo.[BufferClear] '503'
EXEC dbo.[BufferClear] '20651'
EXEC dbo.[BufferClear] '20551'
EXEC dbo.[BufferClear] '40110'

select COUNT_STR = @iCount, SUMMA = @nSumma



GO
grant all on BB_UVED_817_69N_CREATE_TABLE to public
GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE1]

GO



/*
© Кейсистемс (Keysystems), 2005
*/



CREATE     PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_MROT_TABLE1
	@varKSLINK_MINROT	INT,
	@varKSLINK_DICTION	INT,
	@varKSPREDEL	NUMERIC(15,2),
	@varKSSumma	NUMERIC(15,2)
AS
DECLARE @varKSObject int
SELECT @varKSObject = LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'

IF @varKSLINK_MINROT IS NULL OR @varKSLINK_MINROT = 0
BEGIN
	RETURN 5
END

IF @varKSLINK_DICTION IS NULL OR @varKSLINK_DICTION = 0
BEGIN
	RETURN 5
END

IF EXISTS (SELECT * FROM  MINROT_DICTION where link_minrot = @varKSLINK_MINROT and link_diction = @varKSLINK_DICTION and [object] = @varKSObject)
begin 
	RETURN 8 
end	

INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
VALUES(@varKSLINK_MINROT,@varKSLINK_DICTION,@varKSObject,@varKSPREDEL,@varKSSumma)








GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE1] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_ADV61]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_ADV61]

GO

CREATE PROCEDURE dbo.SZV4_PRINT_ADV61(@Link int) 
AS

DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
	@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9), @Month int, @Year int, @date datetime

SELECT 
	@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
	@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP,
	@Month = month_end, @year = year_begin
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
WHERE P.link = @link

Set @date = dbo.ConvertDMY2Date(1,@Month,@Year)
Set @date = dbo.DateEndOfMonth(@date)

DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT4')
Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)


Select 	
	[YEAR] = year_begin,
	SZV = MAX(S.forma),
	[NGROUP] = S.pachka,
	[PERS_CNT] = COUNT(S.orders),
	[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
			+ SUM(case when S.forma = 1 then 1 else 0 end),
	[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
	[AVIA] = (CASE WHEN sum(COALESCE(S.sum_dop,0)) > 0 then 'АВИА' else NULL end),
	[TERUSL] = ST.TER_USL,
	ST.ter_koef,
	[OPT1] = (case when type = 1 then 1 else 0 end),
	[OPT2] = (case when type = 2 then 1 else 0 end),
	[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
	[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
	[DOHOD] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
	[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str+S.SUM_UPLATA_DOLGA_STR)),@ROUND_LEN,@ROUND_TYPE),
	[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
	[DOP] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop+S.SUM_UPLATA_DOLGA_NAK)),@ROUND_LEN,@ROUND_TYPE),
	@varKSNOM_PF AS PFNUMBER, 
	@varKSname AS DEP_NAME,
	@varKSOKPO AS OKPO,
	@varKSINN AS INN,
	@varKSKPP AS KPP,
	DATE_CRT = @date,
	DATE_DOC = date
from 
	dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
	LEFT JOIN dbo.SZV4_STAZH ST ON (S.link = ST.link_up and S.forma = 2)
where
	P.link = @Link
	and P.proverka = 1
group by
	s.pachka, year_begin, type, vid_kor, TER_USL, ST.ter_koef, [date]
order by
	S.pachka



GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_ADV61] TO PUBLIC

GO

GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FB_REPORT_RBS_DETAILS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_REPORT_RBS_DETAILS]
GO


CREATE            PROCEDURE FB_REPORT_RBS_DETAILS
	@varKSiFyear	int,
	@varKSdDateB	datetime,
	@varKSdDateE	datetime,
	@varKSiDocType	tinyint,
	@iDetKBK		tinyint,
	@varKScVal1 		char(1), 
	@varKSnOtborLink1 	int,
	@varKScVal2 		char(1), 
	@varKSnOtborLink2 	int,
	@varKScVal3 		char(1), 
	@varKSnOtborLink3 	int,
	@varKScVal4		char(1), 
	@varKSnOtborLink4 	int


AS
DECLARE	@varKSintFinPeriod	tinyint, 
	@varKSFinObjCode 	char(100),
	@varKSintSummaType 	tinyint,
	@cCROSS_TABLE 		char(100),
	@intCOUNTER		INT,
	@cSQL_STR		VARCHAR (1000),
	@cCOUNTER		VARCHAR (10),
	@intMAX_REC		INT,
	@intCOUNT_COLROW	INT,
	@varKScIF		char(1),
	@varKSintDopEkr 	tinyint,
	@varKSiPeriod 		int,
	@varKScPerTiile 	varchar	(200),
	@varKSintTypePer	int

	
--set @varKSiPeriod = month(@varKSdDateE)
--select @varKScIF = '1' --(case @varKSiIFType when 2 then '2' else '1' end) 

SELECT @varKSintDopEkr = FIN_DOP_EKR FROM WORKMODE
set @varKSiPeriod = month(@varKSdDateE)

SET @intMAX_REC = 10
DECLARE @varKSInTable TABLE( 
	VKR 	 int,
	EKR 	 int, 
	DOP_CL 	 int,
	DEP  	 int, 
	LINK_DOC int,
	P1	 [numeric](28,2),
	P2	 [numeric](28,2),
	P3	 [numeric](28,2),
	P4	 [numeric](28,2),
	P5	 [numeric](28,2),
	P6	 [numeric](28,2),
	P7	 [numeric](28,2),
	P8	 [numeric](28,2),
	P9	 [numeric](28,2),
	P10	 [numeric](28,2),
	P11	 [numeric](28,2),
	P12	 [numeric](28,2),
	SUMMA 	 [numeric](28,2),
	DOP		INT, 
	ORD		int)

SELECT @varKSFinObjCode = (CASE @varKSiDocType 	WHEN 1 	THEN  'FINANS_LIMIT'
						WHEN 2 	THEN  'FINANS_ASSIGN' END)


IF @varKSFinObjCode = 'FINANS_ASSIGN'
BEGIN
	SELECT @varKSintFinPeriod = max(FIN_SMETA_PER), @varKSintTypePer = 0 FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_ASSIGN_OPTIONS
	set @varKScIF = null
END
IF @varKSFinObjCode = 'FINANS_LIMIT'
BEGIN
	SELECT	@varKSintFinPeriod = max(FIN_LIM_PER), 
		@varKSintTypePer = max(FIN_LIM_type)FROM WorkMode
	SELECT @varKSintSummaType = ISNULL(UM,1) FROM FINANS_LIMIT_OPTIONS
	set @varKScIF = '1'
	set @iDetKBK = 0
END


-- Выбираем организации из фильтра
DECLARE @varKStDEP  TABLE (LINK [INT])	
IF LEN (@varKScVal1) > 0
	INSERT INTO @varKStDEP
	SELECT RECORD
	FROM OBJECT_VAR_DEPARTMENT
	WHERE LINK_UP = @varKSnOtborLink1
ELSE
	INSERT INTO @varKStDEP
	SELECT D.LINK
	FROM dbo.DEPARTMENTS D
	where (D.TYPE = 4 OR D.TYPE = 2 OR D.ZB = 1)

-- Выбираем КБК из фильтров по Подразделам и ЦС
DECLARE @varKStVKR  TABLE (LINK [INT])	
IF LEN (@varKScVal2) > 0 AND LEN (@varKScVal4) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK 
	INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV
	INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink4 AND OVI.RECORD = VKR.LINK_CSR

IF LEN (@varKScVal2) > 0 AND NOT LEN (@varKScVal4) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
	INNER JOIN dbo.OBJECT_VAR_DIVISION OVD ON OVD.LINK_UP = @varKSnOtborLink2 AND OVD.RECORD = VKR.LINK_DIV 

IF NOT LEN (@varKScVal2) > 0 AND LEN (@varKScVal4) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK KBK
	INNER JOIN dbo.KL_VKR VKR ON KBK.LINK = VKR.LINK_KBK
	INNER JOIN dbo.OBJECT_VAR_TARGET_ITEM OVI ON OVI.LINK_UP = @varKSnOtborLink4 AND OVI.RECORD = VKR.LINK_CSR

IF LEN (@varKScVal2) = 0 AND NOT LEN (@varKScVal4) > 0
	INSERT INTO @varKStVKR
	SELECT LINK
	FROM dbo.KL_KBK
	WHERE TYPE = 1

-- Выбираем ЕКР из фильтра
DECLARE @varKStEKR  TABLE (LINK [INT])	
IF LEN (@varKScVal3) > 0
	INSERT INTO @varKStEKR
	SELECT RECORD
	FROM dbo.OBJECT_VAR_KOSGU
	WHERE LINK_UP = @varKSnOtborLink3
ELSE
	INSERT INTO @varKStEKR
	SELECT LINK
	FROM dbo.KOSGU
	WHERE IS_EKR = 1

INSERT INTO @varKSInTable (LINK_DOC, DEP, VKR, EKR, DOP_CL, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, SUMMA, DOP, ORD)
SELECT *, 0, 0 FROM (select *,[ITOGS] = F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12 
		FROM dbo.FB_FINANS_POLUCH_DOC(@varKSiFyear, @varKSdDateB, @varKSdDateE, 0, @varKSintSummaType, @varKSFinObjCode, @varKSintFinPeriod) F
		WHERE	F.DEP in (select LINK from @varKStDEP)
			AND F.EKR in (select LINK from @varKStEKR)
			AND F.VKR in (select LINK from @varKStVKR)) FS1 
WHERE NOT (P1 = 0 and P2 = 0 and P3 = 0 and P4 = 0 and P5 = 0 and P6 = 0 and P7 = 0 and P8 = 0 and P9 = 0 and P10 = 0 and P11 = 0 and P12 = 0)
ORDER BY FS1.DEP, FS1.VKR, FS1.EKR, FS1.DOP_CL, FS1.LINK_DOC




--select * from @varKSInTable
select @varKScPerTiile = 'на ' + isnull(p.period + ' ' ,'') + convert(char(4),@varKSiFyear) + ' г.'
from (select period FROM PERIODS
where 	((ord = @varKSiPeriod and @varKSintFinPeriod = 3) OR
	(((ord = 13 and @varKSiPeriod in(1,2,3)) or 
		(ord = 14 and @varKSiPeriod in(4,5,6)) or
		(ord = 15 and @varKSiPeriod in(7,8,9)) or
		(ord = 16 and @varKSiPeriod in(10,11,12))) and @varKSintFinPeriod = 2)) and @varKSintTypePer = 1
union select '' as period where @varKSintTypePer = 0 or @varKSintFinPeriod = 1) p


if @iDetKBK = 0
	Select F.VKR, F.EKR, F.DOP_CL, F.DEP, F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12,
		/*IT.PI1, IT.PI2, IT.PI3, IT.PI4, IT.PI5, IT.PI6, IT.PI7, IT.PI8, IT.PI9, IT.PI10, IT.PI11, IT.PI12,
		SIT.PSI1, SIT.PSI2, SIT.PSI3, SIT.PSI4, SIT.PSI5, SIT.PSI6, SIT.PSI7, SIT.PSI8, SIT.PSI9, SIT.PSI10, SIT.PSI11, SIT.PSI12,
		DIT.PDI1, DIT.PDI2, DIT.PDI3, DIT.PDI4, DIT.PDI5, DIT.PDI6, DIT.PDI7, DIT.PDI8, DIT.PDI9, DIT.PDI10, DIT.PDI11, DIT.PDI12,*/
		[VKR_CODE] = VKR.CODE,
		[VKR_NAME] = VKR.NAME,
		[EKR_CODE] = EKR.CODE,
		[EKR_NAME] = (case when F.DOP_CL is null then EKR.NAME else DCL.NAME end), --EKR.NAME
		[DOP_CODE] = DCL.CODE,
		[EKR_DOP]  = rtrim(EKR.CODE) + '_' + rtrim(isnull(DCL.CODE,'')),
		--[DOP_NAME] = DCL.NAME,
		[DEP_CODE] = D.CODE,
		[DEP_NAME] = D.NAME,
		link_DOC,
		[DOC_NAME] = cast(rtrim(SO.NAME) + ' № '  + rtrim(GP.[NUMBER]) + ' от ' + ISNULL(CONVERT(VARCHAR(30),GP.[DATE],104),'')  as varchar(254)),
		--[ACC_CODE] = DA.CODE,
		ITOG = F.SUMMA, --IT.ITOGI, SIT.ITOGSI, DIT.ITOGDI,
		[um] 	= @varKSintSummaType, 
		[title]	= (case @varKSiDocType when 1 then 'ЛИМИТЫ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ' else 'БЮДЖЕТНЫЕ АССИГНОВАНИЯ' end),  
		[per_title]	= @varKScPerTiile
		From @varKSInTable F  
		INNER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
		INNER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = F.EKR
		INNER JOIN dbo.DEPARTMENTS D ON D.LINK = F.DEP
		INNER JOIN dbo.G_PROV GP ON GP.LINK = F.LINK_DOC
		INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = GP.OBJECT
		LEFT  JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		/*LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
		LEFT outer JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = F.EKR
		LEFT outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
		LEFT OUTER JOIN dbo.DEPARTMENTS D ON D.LINK = F.DEP
		LEFT outer JOIN dbo.G_PROV GP ON GP.LINK = F.LINK_DOC
		LEFT OUTER JOIN dbo.S_OBJECTS SO ON SO.LINK = GP.OBJECT*/
		
	ORDER BY d.code, VKR.CODE, EKR.CODE, DCL.CODE 
else 
begin

	INSERT INTO @varKSInTable (LINK_DOC, DEP, VKR, EKR, SUMMA, DOP, ORD)
	SELECT F1.LINK_DOC, F1.DEP, VKR, EKR, sum(SUMMA), case when exists(select * from @varKSInTable where F1.LINK_DOC = LINK_DOC and F1.VKR = VKR and F1.EKR = EKR and DOP_CL is null) then 2 else 1 end, 2
	FROM @varKSInTable F1
	WHERE exists(select * from @varKSInTable where F1.LINK_DOC = LINK_DOC and F1.VKR = VKR and F1.EKR = EKR and DOP_CL is not null) 
	GROUP BY LINK_DOC, DEP, VKR, EKR

	INSERT INTO @varKSInTable (LINK_DOC, DEP, VKR, EKR, SUMMA, DOP, ORD)
	SELECT F1.LINK_DOC, F1.DEP, F1.VKR, EKR2.LINK, sum(SUMMA), 1, 3
	FROM @varKSInTable F1 
	INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '0'
	INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,2) + '0' AND NOT EXISTS(SELECT EKR FROM @varKSInTable T1 WHERE F1.LINK_DOC = LINK_DOC and T1.VKR = F1.VKR and T1.EKR = EKR2.LINK)
	WHERE DOP = 0  
	GROUP BY F1.LINK_DOC, F1.DEP, F1.VKR, EKR2.LINK 

	INSERT INTO @varKSInTable (LINK_DOC, DEP, VKR, EKR, SUMMA, DOP, ORD)
	SELECT F1.LINK_DOC, F1.DEP, F1.VKR, EKR2.LINK, sum(SUMMA), 1, 4
	FROM @varKSInTable F1 
	INNER JOIN dbo.KOSGU EKR1 ON EKR1.LINK = F1.EKR AND NOT RIGHT(EKR1.CODE,1) = '00'
	INNER JOIN dbo.KOSGU EKR2 ON EKR2.CODE = LEFT(EKR1.CODE,1) + '00' AND NOT EXISTS(SELECT EKR FROM @varKSInTable T1 WHERE F1.LINK_DOC = LINK_DOC and T1.VKR = F1.VKR and T1.EKR = EKR2.LINK)
	WHERE DOP = 0  
	GROUP BY F1.LINK_DOC, F1.DEP, F1.VKR,EKR2.LINK 

	select D.NAME, T.* from
	(Select	F.LINK_DOC, 
			F.DEP,
			DIV = substring(rtrim(replace(VKR.CODE,'.','')),4,4),
			CSR = substring(rtrim(replace(VKR.CODE,'.','')),8,7),
			[EXP] = right(rtrim(replace(VKR.CODE,'.','')),3),
			EKR = EKR.CODE,
			DOP_CL = isnull(DCL.CODE,''),
			NAME = rtrim(case when F.DOP_CL is null then EKR.NAME else DCL.NAME end) + case F.DOP when 2 then '(Итого)' else '' end,
			SUMMA, 
			ITOG = (select sum(summa) from @varKSInTable where F.LINK_DOC = LINK_DOC and DOP = 0 ),
			ORD		
	From @varKSInTable F  
	LEFT OUTER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
	left outer JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
	left outer JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = F.DOP_CL
	--GROUP BY F.LINK_DOC, F.DEP
	union all
	Select	F.LINK_DOC, 
			F.DEP,
			DIV = substring(rtrim(replace(VKR.CODE,'.','')),4,4),
			CSR = substring(rtrim(replace(VKR.CODE,'.','')),8,7),
			[EXP] = right(rtrim(replace(VKR.CODE,'.','')),3),
			EKR = '000',
			DOP_CL = '',
			NAME = VKR.NAME,
			sum(SUMMA), 0, 5
	From @varKSInTable F  
	INNER JOIN dbo.KL_KBK VKR ON VKR.LINK = F.VKR
	WHERE DOP = 0 
	GROUP BY F.LINK_DOC, F.DEP, VKR.CODE, VKR.NAME
	union all
	Select	F.LINK_DOC, 
			F.DEP,
			DIV = DIV.CODE,
			CSR = CSR.CODE,
			[EXP] = '000',
			EKR = '000',
			DOP_CL = '',
			NAME = CSR.NAME,
			sum(SUMMA), 0, 6
	From @varKSInTable F  
	INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
	INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
	INNER JOIN dbo.KL_TARGET_ITEM CSR ON VKR.Link_CSR = CSR.link
	WHERE DOP = 0 
	GROUP BY F.LINK_DOC, F.DEP, DIV.CODE, CSR.CODE, CSR.NAME
	union all
	Select	F.LINK_DOC, 
			F.DEP,
			DIV = DIV.CODE,
			CSR = CSR1.CODE,
			[EXP] = '000',
			EKR = '000',
			DOP_CL = '',
			NAME = CSR1.NAME,
			sum(SUMMA), 0, 7
	From @varKSInTable F  
	INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
	INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
	INNER JOIN dbo.KL_TARGET_ITEM CSR ON VKR.Link_CSR = CSR.link
	INNER JOIN dbo.KL_TARGET_ITEM CSR1 ON left(CSR.CODE,3) + '0000' = CSR1.CODE
	WHERE DOP = 0 
	GROUP BY F.LINK_DOC, F.DEP, DIV.CODE, CSR1.CODE, CSR1.NAME
	union all
	Select	F.LINK_DOC, 
			F.DEP,
			DIV = DIV.CODE,
			CSR = '0000000',
			[EXP] = '000',
			EKR = '000',
			DOP_CL = '',
			NAME = DIV.NAME,
			sum(SUMMA), 0, 8
	From @varKSInTable F  
	INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
	INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
	WHERE DOP = 0 
	GROUP BY F.LINK_DOC, F.DEP, DIV.CODE, DIV.NAME
	union all
	Select	F.LINK_DOC, 
			F.DEP,
			DIV = DIV1.CODE,
			CSR = '0000000',
			[EXP] = '000',
			EKR = '000',
			DOP_CL = '',
			NAME = DIV1.NAME,
			sum(SUMMA),0, 9
	From @varKSInTable F  
	INNER JOIN dbo.KL_VKR VKR ON VKR.LINK_KBK = F.VKR
	INNER JOIN dbo.KL_DIVISION DIV ON VKR.Link_Div = DIV.link
	INNER JOIN dbo.KL_DIVISION DIV1 ON left(DIV.CODE,2) + '00' = DIV1.CODE
	WHERE DOP = 0 
	GROUP BY F.LINK_DOC, F.DEP, DIV1.CODE, DIV1.NAME) T
	inner join dbo.DEPARTMENTS D on D.LINK = T.DEP
	order by  1, 4, 5, 6, 7, 8, 12 desc



end
 

RETURN 1

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SAVE_IN_EXECUTE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SAVE_IN_EXECUTE]

GO






/*
© Кейсистемс (Keysystems), 2005
*/

-- warning: LINK и LINK_EXECUTORS указывают на EVENT_LINKS!

CREATE PROCEDURE dbo.DP_SAVE_IN_EXECUTE 
    @varKSparLINK            INT OUTPUT,
    @varKSparLINK_DOC        INT,
    @varKSparEXECU_DATE      DATETIME,
    @varKSparCOMMENT         VARCHAR(2000) = '',
    @varKSparEX_CHECKED	     BIT,
	@varKSparTASK_AUTH_COMM  VARCHAR(2000) = '',
    @varKSparLINK_EXECUTORS	INT
AS

DECLARE @varKSSQLError      TINYINT,
        @varKStrancount		  INT,
        @varKSRowCount      INT,
        @varKSEventLink     INT,
        @varKSExecutorLink  INT,
        @varKSObjEXECUTE    INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON

BEGIN TRAN
COMMIT TRAN
	

IF @varKSparLINK_DOC IS NULL OR @varKSparLINK_DOC = 0
BEGIN
  ROLLBACK
  RETURN 5
END

IF @varKSparLINK <= 0 
  SET @varKSparLINK = NULL

IF EXISTS(SELECT EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK)
  SELECT @varKSEventLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK
ELSE
  SET @varKSEventLink = NULL

IF ISNULL(@varKSparLINK_EXECUTORS,0) <= 0 
BEGIN	
  ROLLBACK
  RETURN 5
END
ELSE
  SELECT @varKSExecutorLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK_EXECUTORS

IF @varKSEventLink IS NULL 
BEGIN
     DECLARE  @varKSUserRef  INT
     SELECT @varKSUserRef = USER_REF FROM WHO_IS_WHO WHERE SID = SUSER_SID()
    
     INSERT INTO dbo.EVENT_EXECU WITH (ROWLOCK) (LINK_DOC,LINK_EXECUTORS,EXECU_DATE,COMMENT,EVENT_DATE,CHECKED,TASK_AUTH_COMMENT,EVENT_LINK_EMPL) 
     VALUES (@varKSparLINK_DOC, @varKSExecutorLink, @varKSparEXECU_DATE, @varKSparCOMMENT, GETDATE(), @varKSparEX_CHECKED, @varKSparTASK_AUTH_COMM, @varKSUserRef)
    
     SELECT @varKSSQLError = @@ERROR, @varKSEventLINK = SCOPE_IDENTITY()
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END

     SELECT @varKSObjEXECUTE = LINK FROM S_OBJECTS WHERE CODE = 'WF_EVENT_EXECUTE'
     SELECT @varKSparLINK = LINK FROM dbo.EVENT_LINKS WHERE EVENT_LINK = @varKSEventLink AND OBJECT = @varKSObjEXECUTE

END
ELSE
BEGIN
     UPDATE dbo.EVENT_EXECU WITH (ROWLOCK) 
     SET LINK_DOC = @varKSparLINK_DOC,LINK_EXECUTORS = @varKSExecutorLink, EXECU_DATE = @varKSparEXECU_DATE,COMMENT = @varKSparCOMMENT, CHECKED = @varKSparEX_CHECKED, TASK_AUTH_COMMENT = @varKSparTASK_AUTH_COMM
     WHERE LINK = @varKSEventLink
    
     SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END
    
     IF @varKSRowCount = 0
     BEGIN
          ROLLBACK
          RETURN 2
     END
END	

   DECLARE @varKSAuth      VARCHAR(30),
           @varKSRoute     VARCHAR(30),
           @varKSDocRegNum VARCHAR(15),
           @varKSDocName   VARCHAR(100),
           @varKSCurInfStr VARCHAR(254)

   SELECT @varKSAuth = dbo.sd_GetEmplName(WW.USER_REF)
   FROM WHO_IS_WHO WW
   WHERE WW.SID = SUSER_SID()
		
   SELECT @varKSDocRegNum = ER.REG_NUM, @varKSDocName = D.NAME FROM DOCUMENTS D LEFT OUTER JOIN EVENT_REG ER ON D.LINK = ER.LINK_DOC WHERE D.LINK = @varKSparLINK_DOC
   
   SET @varKSCurInfStr = 'Пользователь ' +LTRIM(RTRIM(ISNULL(@varKSAuth,''))) + case when @varKSEventLink IS NULL then ' приступил к исполнению поручения ' else ' отредактировал ход исполнения ' end +
				  ' по документу "'+ 
				  LTRIM(RTRIM(ISNULL(@varKSDocName,''))) + '"(№:'+LTRIM(RTRIM(ISNULL(@varKSDocRegNum,'')))+')'
   EXECUTE	WF_GENERATEEVENT 'Редактирование документа',@varKSCurInfStr,NULL,'DOCUMENTS'

   IF NOT ( dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
	OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
		exec EOS_EXPORT_REPORT @varKSparLINK_DOC

IF @@TRANCOUNT > @varKStrancount
   COMMIT TRAN

RETURN 0







GO


GRANT EXECUTE ON dbo.[DP_SAVE_IN_EXECUTE] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE2]

GO

CREATE      PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_MROT_TABLE2
	@varKSLINK_MINROT	INT,
	@varKSLINK_PAYS	    INT,
	@varKSPREDEL	NUMERIC(15,2)
AS
DECLARE @varKSObject int
SELECT @varKSObject = LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T2'

IF @varKSLINK_MINROT IS NULL OR @varKSLINK_MINROT = 0
	RETURN 5

IF @varKSLINK_PAYS IS NULL OR @varKSLINK_PAYS = 0
	RETURN 5

IF EXISTS (SELECT * FROM  MINROT_DICTION where link_minrot = @varKSLINK_MINROT and link_diction = @varKSLINK_PAYS and [object] = @varKSObject)
begin 
	RETURN 8 
end	

INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
VALUES(@varKSLINK_MINROT,@varKSLINK_PAYS,@varKSObject,0,@varKSPREDEL)



GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE2] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[XK_DELETE_DICTION_REC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XK_DELETE_DICTION_REC]

GO
CREATE PROCEDURE dbo.XK_DELETE_DICTION_REC
	@intDIC_LINK	INT
AS
BEGIN
	DECLARE @strtrancount	int,
		@intObj_Link	int,
		@strOBJ_CODE	VARCHAR (30),
		@strEventText	varchar(254)
	
	SET @strtrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN

	SELECT @strEventText = CONVERT (VARCHAR (254),
					RTRIM (SO.[NAME]) + ': '
					+ RTRIM (ISNULL (A1.CODE, ''))
					+ '-' + ISNULL (A1.[NAME], '')),
		@intObj_Link = SO.LINK,
		@strOBJ_CODE = SO.CODE	
	FROM dbo.DICTION A1 WITH (UPDLOCK) 
	INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = A1.OBJECT)
	WHERE A1.LINK = @intDIC_LINK

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	DELETE FROM dbo.DICTION
	WHERE LINK = @intDIC_LINK

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	IF @@TRANCOUNT > @strtrancount
		BEGIN
			EXECUTE dbo.WF_GENERATEEVENT 'Удаление из справочника',
					@strEventText,
					@intObj_Link,
					'DICTION',
					@intDIC_LINK
			COMMIT TRAN
		END
	RETURN 0
END

GO


GRANT EXECUTE ON dbo.[XK_DELETE_DICTION_REC] 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(17),
		@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(17),
		@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(17), 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(17), 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) + ''''
	--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,'.','')
				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
	
	--insert into #tProtocol values('Принято ' + ltrim(str(@@rowcount)) + ' проводок',1,0,0)
	
	OPEN #CURS_BKS 
	
	insert into #tProtocol values('Принято ' + ltrim(str(@@rowcount)) + ' проводок',1,0,0)
	insert into #tProtocol values('Сохранение принятых документов',1,0,0)
	
	FETCH FROM #CURS_BKS 
	INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_KT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
	
	SELECT @intCount_Prov_Save = 0,
		@intCount_Doc_Save = 0

	WHILE @@FETCH_STATUS = 0 
	BEGIN
		--- Выбор документа для СМЕТЫ, если нет, то создаем новый ---
		SELECT @intDOC_SMETA = (SELECT DOC_SMETA FROM @TABLE_DOCS WHERE DOC_BKS = @intDOC_BKS)
		
					
		--- Создание нового документа в смете ---
		IF @intDOC_SMETA IS NULL
		BEGIN
			insert into #tProtocol values('Прием документа "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),''),1,0,0)
			if exists(select * from dbo.DOCUMENTS_OPER G where NUMBER = isnull(@DOC_NUM,'') and DATE = @DOC_DATE and DATE_PROV = @DATE_PROV and DEP_LINK = @intDEP_LINK and KIND_CODE_BKS = @DOC_CODE) and
				not exists(select * from @TABLE_DOCS where @DATE_PROV = DATE_PROV and DATE = @DOC_DATE and @DOC_NUM = DOC_NUM and @DOC_CODE = DOC_CODE) or 
				(@DOC_CODE = 'DOCUMENTS_0401002' and exists(select P.* 
															from dbo.DOCUMENTS_PAY P 
															inner join dbo.G_PROV1 G1 on G1.LINK_UP = P.LINK  
															inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK and G2.SUMMA = @nSUMMA  
															where P.NUMBER = isnull(@DOC_NUM,'') and P.DATE_PROV = @DATE_PROV and P.DATE = @DOC_DATE and P.DEP_LINK = @intDEP_LINK))
				insert into #tProtocol values('Документ "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),'') + ' уже существует. ',1,0,1)
			else
			begin
				SELECT @intDEP_ACC = (SELECT TOP 1 LINK FROM dbo.DEPARTMENT_ACCOUNTS WHERE CODE = @DEP_ACC)
				insert into #tProtocol values('Создание документа "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),''),1,0,1)
			
				SELECT @COMMENT = 'Принят из БКС: ' + ISNULL (@COMMENT, RTRIM (ISNULL (@DOC_NAME, '')))
				EXEC @intERROR = dbo.X_SAVE_DOCUMENTS_OPER @intDOC_SMETA OUTPUT, @DOC_NUM, @DOC_DATE, @DATE_PROV,
					0, @COMMENT, DEFAULT, @DOC_TYPE, @intDEP_LINK, @intDEP_ACC
				IF @intERROR <> 0
					RETURN @intERROR
				
				SET @intCount_Doc_Save = @intCount_Doc_Save + 1

				INSERT INTO @TABLE_DOCS (DOC_BKS, DOC_SMETA, DATE, DATE_PROV, DOC_NUM, DOC_CODE)
				VALUES (@intDOC_BKS, @intDOC_SMETA, @DOC_DATE, @DATE_PROV, @DOC_NUM, @DOC_CODE) 
			end
		END	-- IF @intDOC_SMETA IS NULL
	
		IF @intDOC_SMETA IS NULL
		BEGIN
			insert into #tProtocol values('Невозможно создать документ.',1,1,1)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

		--select @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_INN_KT, @strDEP_NAME_KT,@DOC_NUM
		--- ВЫЧИСЛЕНИЕ ЗНАЧЕНИЯ РЕКВИЗИТОВ ПРОВОДКИ (АНАЛИТИКИ) ---
		--- Дебетовая часть ---
		
		set @intDCL_DT = (SELECT TOP 1 LINK
		FROM dbo.DOP_CLASSIF
		WHERE CODE = @strDCL_CODE_DT)

		IF ISNULL (@strDEP_INN_DT, '') <> '' and @intDEP_DT is null
			SELECT TOP 1 @intDEP_DT = LINK
			FROM dbo.DEPARTMENTS  
			WHERE (rtrim(INN) + case INN_DOP when '' then '' else '/' + INN_DOP end) = @strDEP_INN_DT		

		IF @intDEP_ACC_DT is null and ISNULL (@strDEP_ACC_DT, '') <> '' 
			SELECT TOP 1 @intDEP_ACC_DT = LINK
			FROM dbo.DEPARTMENT_ACCOUNTS
			WHERE CODE = @strDEP_ACC_DT
				
		if isnull(@strDCL_CODE_DT,'') <> '' and @intDCL_DT is null
			insert into #tProtocol values('В справочнике не найдена доп. классификация: ' + @strDCL_CODE_DT,1 ,1,2)

	
		--print @strDEP_INN_DT
		if isnull(@strDEP_INN_DT,'') <> '' and isnull(@strDEP_NAME_DT,'') <> '' and @intDEP_DT is null
		begin
			select @cDepNextCode = cast(ISNULL(MAX(CONVERT(bigint, CODE)),0) + 1 as varchar(10))  
			FROM  dbo.DEPARTMENTS
			where dbo.CheckIsNumeric(CODE) = 1
			insert into dbo.DEPARTMENTS (CODE, INN, [NAME], FULL_NAME, TYPE, OKATO)
			values(@cDepNextCode,@strDEP_INN_DT,@strDEP_NAME_DT,@strDEP_NAME_DT,1, ISNULL(@strDEP_OKATO_DT,''))
			insert into #tProtocol values('Организация ' + @strDEP_NAME_DT + ' с ИНН: ' + @strDEP_INN_DT + ' добалена в справочник',1 ,1,2)
		end

		if isnull(@strDEP_INN_DT,'') <> '' and @intDEP_DT is null
				insert into #tProtocol values('В справочнике не найдена организация с ИНН: ' + @strDEP_INN_DT,1 ,1,2)

		if isnull(@strDEP_ACC_DT,'') <> '' and @intDEP_ACC_DT is null
				insert into #tProtocol values('В справочнике не найден счет организации: ' + @strDEP_ACC_DT,1 ,1,2)
		
	--	select @strDEP_INN_KT,@strDEP_NAME_KT,@strDEP_NAME_KT
	
--- Кредитовая часть ---
		
		set @intDCL_KT = (SELECT TOP 1 LINK
		FROM dbo.DOP_CLASSIF
		WHERE CODE = @strDCL_CODE_KT)	 

		IF ISNULL (@strDEP_INN_KT, '') <> '' and @intDEP_KT is null
			SELECT TOP 1 @intDEP_KT = LINK
			FROM dbo.DEPARTMENTS  
			WHERE (rtrim(INN) + case INN_DOP when '' then '' else '/' + INN_DOP end) = @strDEP_INN_KT		

		IF @intDEP_ACC_KT is null and ISNULL (@strDEP_ACC_KT, '') <> '' 
			SELECT TOP 1 @intDEP_ACC_KT = LINK
			FROM dbo.DEPARTMENT_ACCOUNTS
			WHERE CODE = @strDEP_ACC_KT

		if isnull(@strDCL_CODE_KT,'') <> '' and @intDCL_KT is null
			insert into #tProtocol values('В справочнике не найдена доп. классификация: ' + @strDCL_CODE_KT,1 ,1,2)

		if isnull(@strDEP_INN_KT,'') <> '' and @intDEP_KT is null and isnull(@strDEP_NAME_KT,'') <> '' 
		begin	
			select @cDepNextCode = cast(ISNULL(MAX(CONVERT(bigint, CODE)),0) + 1 as varchar(10))  
			FROM  dbo.DEPARTMENTS
			where dbo.CheckIsNumeric(CODE) = 1
			insert into dbo.DEPARTMENTS (CODE, INN, [NAME], FULL_NAME, TYPE, OKATO)
			values(@cDepNextCode,@strDEP_INN_KT,@strDEP_NAME_KT,@strDEP_NAME_KT,1, ISNULL(@strDEP_OKATO_KT,''))
			insert into #tProtocol values('Организация ' + @strDEP_NAME_KT + ' с ИНН: ' + @strDEP_INN_KT + ' добалена в справочник',1 ,1,2)
		end		

		if isnull(@strDEP_INN_KT,'') <> '' and @intDEP_KT is null
				insert into #tProtocol values('В справочнике не найдена организация с ИНН: ' + @strDEP_INN_KT,1 ,1,2)

		if isnull(@strDEP_ACC_KT,'') <> '' and @intDEP_ACC_KT is null
				insert into #tProtocol values('В справочнике не найден счет организации: ' + @strDEP_ACC_KT,1 ,1,2)

		IF @intACC_DT IS NULL OR @intACC_KT IS NULL
		BEGIN
			
			insert into #tProtocol values('Отсутствуе счет:' + case when @intACC_DT is null then @strACC_CODE_DT else '' end + '  ' + case when @intACC_KT is null then @strACC_CODE_KT else '' end,1,1,2)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END
		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_DT and P_KASSA = 1)
			select @intEKR_DT = @intSGU_DT, @strEKR_CODE_DT = @strSGU_CODE_DT

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_DT and P_EKR = 1)
			select @intEKR_DT = EKR.LINK, @strEKR_CODE_DT = EKR.CODE
			from dbo.S_ACCOUNTS SA
			inner join dbo.KOSGU EKR on SA.ANALIT_EKR = EKR.LINK
			where SA.LINK = @intACC_DT 

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_KT and P_KASSA = 1)
			select @intEKR_KT = @intSGU_KT, @strEKR_CODE_KT = @strSGU_CODE_KT

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_KT and P_EKR = 1)
			select @intEKR_KT = EKR.LINK, @strEKR_CODE_KT = EKR.CODE
			from dbo.S_ACCOUNTS SA
			inner join dbo.KOSGU EKR on SA.ANALIT_EKR = EKR.LINK
			where SA.LINK = @intACC_KT 


	
		insert into #tProtocol values('Сохранение операции ' + @strNAME_OPER_G1,1,1,2)
		--- Сохранение операции (G_PROV1) ---
		SELECT @intLINK_G1 = NULL
		SELECT @intORDERS_G1 = (SELECT MAX (ORDERS) FROM dbo.G_PROV1 WHERE LINK_UP = @intDOC_SMETA)
		SELECT @intORDERS_G1 = ISNULL (@intORDERS_G1, 0) + 1
			
			
		EXEC @intERROR = dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @intDOC_SMETA, NULL,
			@strNAME_OPER_G1, @intORDERS_G1
		IF @intERROR <> 0
			RETURN @intERROR
		
					
		IF @intLINK_G1 IS NULL
		BEGIN
			insert into #tProtocol values('Ошибка при создании операции ' + @strNAME_OPER_G1,1,1,3)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

		--- Сохранение проводки (G_PROV2) ---
		
		SELECT @intLINK_G2 = NULL
		SELECT @intORDERS_G2 = (SELECT MAX (ORDERS) FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_G1)
		SELECT @intORDERS_G2 = ISNULL (@intORDERS_G2, 0) + 1
		SELECT @intECON_OPER = NULL

		SELECT TOP 1 @intECON_OPER = LINK
		FROM dbo.BX_BPROV_VIBOR_ECON_OPER (@intACC_DT, @intACC_KT)

		SET @strNAME_OPER_G2 = @strNAME_OPER_G1

		insert into #tProtocol values('Сохранение проводки: Дт "' + @strACC_CODE_DT + ' КБК: ' + @strKBK_CODE_DT + ' СГУ: ' + @strSGU_CODE_DT + ' ЭКР: ' + @strEKR_CODE_DT + ' Доп.кл: ' + @strDCL_CODE_DT + ' Орг.: ' + @strDEP_INN_DT + ' Счет.: ' + @strDEP_ACC_DT,1,0,3)
		insert into #tProtocol values('						Кт "' + @strACC_CODE_KT + ' КБК: ' + @strKBK_CODE_KT + ' СГУ: ' + @strSGU_CODE_KT + ' ЭКР: ' + @strEKR_CODE_KT + ' Доп.кл: ' + @strDCL_CODE_KT + ' Орг.: ' + @strDEP_INN_KT + ' Счет.: ' + @strDEP_ACC_KT,1,0,3)
		insert into #tProtocol values('						сумма ' + str(@nSUMMA,20,2),1,1,2) 
		EXEC @intERROR = dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
			@nSUMMA, 0, 0, @strNAME_OPER_G2, @intECON_OPER, @intORDERS_G2
		IF @intERROR <> 0
			RETURN @intERROR
			
		
		IF @intLINK_G2 IS NULL
		BEGIN
			insert into #tProtocol values('Ошибка при создании проводки ' + @strNAME_OPER_G2,1,1,3)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

/*
CREATE                  PROCEDURE X_UPDATE_G_PROV_AP
	@varKSLink_Up	INT,
	@varKSDB_KR	tinyint,
	@varKSAccount	INT,
	@varKSKBK		INT,
	@varKSEKR		INT,
	@varKSDEP		INT,
	@varKSSUB		INT,
	@varKSEMP		INT,
	@varKSNOMEN	INT,
	@varKSINV		INT,
	@varKSKAU		INT,
	@varKSDEP_ACC	INT,
	@varKSTMC 		INT,
	@varKSINDATE	DATETIME,
	@varKSAP1		INT,
	@varKSAP2		INT,
	@varKSAP3		INT,
	@varKSSGU		INT = null
*/
		--- Сохранение аналитики (Дебет) ---
		
				
		EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 0, @intACC_DT, @intKBK_DT, @intEKR_DT, 
			@intDEP_DT, NULL, NULL, NULL, NULL, NULL, @intDEP_ACC_DT, NULL, NULL,
			NULL, @intDCL_DT, NULL, @intSGU_DT 
		IF @intERROR <> 0
			RETURN @intERROR

		
		--- Сохранение аналитики (Кредит) ---
		EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 1, @intACC_KT, @intKBK_KT, @intEKR_KT, 
			@intDEP_KT, NULL, NULL, NULL, NULL, NULL, @intDEP_ACC_KT, NULL, NULL,
			NULL, @intDCL_KT, NULL, @intSGU_KT 
		IF @intERROR <> 0
			RETURN @intERROR
		
		SELECT @intCount_Prov_Save = @intCount_Prov_Save + 1
		FETCH FROM #CURS_BKS 
		INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
		END
	
	CLOSE #CURS_BKS
	DEALLOCATE #CURS_BKS
	
	exec dbo.X_SALDO_CommitChanges
	--SELECT * FROM #PROV_BKS
	insert into #tProtocol values('Сохранено документов: ' + LTRIM (STR (@intCount_DOC_Save)),1,0,0)
	insert into #tProtocol values('Сохранено проводок: ' + LTRIM (STR (@intCount_Prov_Save)),1,0,0)

	DROP TABLE #PROV_BKS
	
	exec dbo.BufferClear @cBufferID
	exec dbo.BufferClear @cBuffIdKBK
	exec dbo.BufferClear @cBuffIdSGU
	exec dbo.BufferClear @cBuffIdACC
	--SELECT * FROM @TABLE_DOCS
	select * from #tProtocol
	RETURN 0

END	--- END PROC ---

GO


GRANT ALL ON dbo.[BK_IMPORT_PROV_FROM_BKS] TO PUBLIC
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KJ_PERS_PENSION_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KJ_PERS_PENSION_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.KJ_PERS_PENSION_SAVE
	@varKSparLINK	 	int	OUTPUT,
	@varKSparPERS_LINK	int,
	@varKSparDOC_NUMBER	VARCHAR(40) = '', 
	@varKSparDOC_DATE	DATETIME,
	@varKSparPENS_DATE	DATETIME,
	@varKSparCHECK_SZV  tinyint = 0,
	@varKSparWORK_PENS	tinyint = 0,
	@varKSparCOMMENT	VARCHAR(200) = ''

AS
DECLARE @varKSERROR		tinyint,
	@varKSRowCount		int,
	@varKSstrVALUE		varchar(7000),
	@varKStrancount		int,
	@varKSEventText		varchar(254),
	@varKSintObj 		int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	IF @varKSparPERS_LINK IS NULL OR @varKSparPERS_LINK IS NULL
	BEGIN
		ROLLBACK
		RETURN 5
	END

	UPDATE	dbo.PERS_PENSION
	SET	DOC_NUMBER  = @varKSparDOC_NUMBER,
		DOC_DATE  = @varKSparDOC_DATE,
		PENS_DATE  = @varKSparPENS_DATE,
		COMMENT = @varKSparCOMMENT, 
		CHECK_SZV = @varKSparCHECK_SZV,
		WORK_PENS = @varKSparWORK_PENS
	WHERE	LINK = @varKSparLINK AND PERS_LINK= @varKSparPERS_LINK
		
	SELECT @varKSRowCount = @@ROWCOUNT, @varKSERROR = @@ERROR
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	IF @varKSRowCount = 0
	BEGIN
		INSERT INTO dbo.PERS_PENSION
		VALUES (@varKSparPERS_LINK, @varKSparDOC_NUMBER, @varKSparDOC_DATE, @varKSparPENS_DATE,@varKSparCOMMENT, @varKSparCHECK_SZV, @varKSparWORK_PENS)

		SELECT @varKSERROR = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	
	SELECT @varKSintObj = LINK FROM S_OBJECTS WHERE CODE = 'KJ_PERS_PENSION'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', 'Сохранение сведений о пенсии', @varKSintObj, 'PERS_PENSION', @varKSparLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[KJ_PERS_PENSION_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].[X_FORM_VIEW_DICTIONARY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_FORM_VIEW_DICTIONARY]
GO





/*
© Кейсистемс (Keysystems), 2005
*/


CREATE         PROCEDURE dbo.X_FORM_VIEW_DICTIONARY
	@varKScCode		varchar(30),
	@varKShostCode	varchar(30) = null
AS
BEGIN
	IF @varKShostCode is null
		SET @varKShostCode = @varKScCode
	DECLARE 
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSRefLINK	int,
		@varKSRefLINK2	int,
		@varKSFirst		int,
		@varKSCurCODE	varchar(30),
		@varKSparCODE	varchar(30),
		@varKSRefDict	varchar(30),
		@varKSRefField	varchar(254),
		@varKSRefField2	varchar(254),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(100),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(8000),
		@varKSCur_Str	varchar(8000),
		@varKSChan_str	varchar(8000),
		@varKSEMP		varchar(1),
		@varKSADDTYPE	varchar(100),
		@varKSOpen_Code	varchar(100),
		@varKSpntIndex	int,
		@varKShostTypeObject	varchar(30)
	
	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode
	EXECUTE X_GET_PROP @varKScCode, 'OPEN_CODE', @varKSOpen_Code OUTPUT
	IF @varKSOpen_Code is null
		print 'Свойство OPEN_CODE неопределено или ошибочно!!!!'

PRINT '---------------'+@varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END
	Select @varKSType=NAME FROM S_OBJECTS WHERE CODE=@varKScCode
	print '('+@varKSType+')'

	IF @varKSOpen_Code=''
	BEGIN
		Print 'Свойство OPEN_CODE не задано... используется CODE'
		SET @varKSOpen_Code='CODE'
	END
	ELSE
		Print 'Свойство OPEN_CODE = '+@varKSOpen_Code
		
	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT LINK, CODE 
		FROM S_OBJECTS SO
		WHERE LINK_SELF=@varKSnLink AND (SELECT CODE FROM S_OBJECTS WHERE LINK=SO.LINK_CLASS)='EDIT_FIELD_CLASS'
		ORDER BY ORDERS

	SET @varKSSel_Str=
'
/*
© Кейсистемс (Keysystems), 2005
*/

--Представление сформировано с помощью X_FORM_VIEW_DICTIONARY (Сергеев С.Н.)
--'+LTRIM(convert(char, getdate()))+'
VIEW dbo.'+@varKScCode+'
AS
SELECT A.LINK'
	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		IF Convert(int, @varKSInALIAS)&1 = 1 AND @varKSStorage<>''
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
			SELECT @varKSRefLINK=null
			SELECT @varKSRefLINK=LINK FROM S_OBJECTS WHERE CODE=RTRIM(@varKSRefDict)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSRefField OUTPUT
			SET @varKSpntIndex = CHARINDEX(',', @varKSRefField)
			IF @varKSpntIndex > 0 AND @varKSStorage <> 'CALCULATE'
			BEGIN
				SET @varKSRefField2 = LTRIM(RTRIM(SUBSTRING(@varKSRefField, @varKSpntIndex + 1, LEN(@varKSRefField) - @varKSpntIndex)))
				SET @varKSRefField = LTRIM(RTRIM(SUBSTRING(@varKSRefField, 1, @varKSpntIndex - 1)))
			END
			ELSE
				SET @varKSRefField2 = ''
			SELECT @varKSRefLINK2=null
			SELECT @varKSRefLINK2=LINK FROM S_OBJECTS WHERE CODE=RTRIM(@varKSRefField)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			IF LEN(@varKSShortCode)>10
				print 'ПРЕДУПРЕЖДЕНИЕ: Длина поля SHORT_CODE_OBJ больше 10 символов!!! ('+@varKSShortCode+')'

			SET @varKShostTypeObject = @varKSCurCODE
			IF @varKSStorage = 'DICTION_REF' AND @varKSRefField <> 'LINK' AND @varKSRefLINK2 IS NULL
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO,
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = @varKSRefLINK AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
						AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF (@varKSStorage = 'DICTION_REF' OR @varKSStorage = 'DICTION_KLADR' OR @varKSStorage = 'DICTION_DEP' OR @varKSStorage = 'SUBDIV_HEAD') AND @varKSRefField2 <> 'LINK' AND @varKSRefLINK2 IS NOT NULL
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, 
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = @varKSRefLINK2 AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField2)
						AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END

			IF @varKSStorage = 'DICTION_TAB' AND @varKSRefField2 <> 'LINK' AND @varKSRefLINK2 IS NOT NULL
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, 
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = @varKSRefLINK2 AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField2)
						AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'GROUP_INV')

				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END

			IF @varKSStorage = 'PAYS_DICTION' AND @varKSRefField <> 'LINK' AND @varKSRefLINK2 IS NULL
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO,
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = @varKSRefLINK AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
						AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'PAYS')
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'PAYS_DICTION' AND @varKSRefField2 <> 'LINK' AND @varKSRefLINK2 IS NOT NULL
			BEGIN
				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, 
						OBJECT_VALUES OVH, S_OBJECTS SOH
					WHERE OVH.OBJECT = @varKSRefLINK2 AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
						AND SOH.CODE = RTRIM(OVH.VALUE)
						AND SO.LINK_SELF = SOH.LINK
						AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField2)
						AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'PAYS')
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'DICTION_TAB' AND @varKSRefField <> 'LINK'
			BEGIN	
			  IF @varKSRefLINK2 IS NULL
			    BEGIN
				SELECT @varKSparCODE = OVD.VALUE
				FROM OBJECT_VALUES OVF, S_OBJECTS SO, OBJECT_VALUES OVD
				WHERE OVF.OBJECT = @varKSRefLINK AND
					OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') AND
					SO.CODE = RTRIM(OVF.VALUE) AND
					OVD.OBJECT = SO.LINK AND
					OVD.PROPERTY = (select LINK from S_PROPERTY where CODE = 'SERVER_TABLE_NAME') 

				SET @varKSparCODE = UPPER(@varKSparCODE)
			    END
			  ELSE
			    BEGIN
				SELECT @varKSparCODE = OV.VALUE
				FROM S_OBJECTS SO, OBJECT_VALUES OV
				WHERE SO.CODE = @varKShostTypeObject AND
					OV.OBJECT = SO.LINK_SELF AND
					OV.PROPERTY = (select LINK from S_PROPERTY where CODE = 'SERVER_TABLE_NAME') 
				SET @varKSparCODE = UPPER(@varKSparCODE)
			    END
			END

			EXECUTE X_GET_PROP  @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT
			IF UPPER(LTRIM(RTRIM(@varKSType)))='DATETIME'
				SET @varKSADDTYPE=',104'
			ELSE
				SET @varKSADDTYPE=''

DECLARE	@varKSCNE	varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT

			SET @varKSINFO=convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

			PRINT convert(char(30), @varKSShortCode)+convert(char(30), @varKSType)+@varKSINFO
			IF @varKShostTypeObject <> @varKSCurCODE
				print '-------->' + @varKShostTypeObject + @varKSType
			IF @varKSShortCode is null OR LTRIM(@varKSShortCode)=''
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			
				SET @varKSCur_Str  = ',
	['+@varKSShortCode+']='+
					CASE
						WHEN  @varKSStorage='DICTION_APP' THEN 
							CASE WHEN @varKSRefDict = ''
								THEN
									'convert(' + @varKSType +', (SELECT B.VALUE FROM  dbo.DICTION_APP B  ' +
									'WHERE  B.LINK_UP = A.LINK AND B.OBJECT= ' +LTRIM(STR(@varKSCurLINK)) +
											') '  + @varKSADDTYPE + ')'
								ELSE
									'convert(' + @varKSType +',(SELECT B.VALUE'+@varKSADDTYPE+'  FROM  dbo.DICTION_APP B, dbo.DICTION_REF DR  ' +
									'WHERE DR.REF_PRIMARY=A.LINK AND DR.OBJECT=' + LTRIM(STR(@varKSRefLINK)) + ' AND B.LINK_UP = DR.REF_FOREIGN AND B.OBJECT = '+LTRIM(STR(@varKSRefLINK2))+'))'
							END
						WHEN  @varKSStorage='DICTION_REF' THEN
						     CASE 
							WHEN @varKSRefField IN ('CODE', 'NAME') THEN
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.DICTION_REF B , dbo.DICTION C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_FOREIGN=C.LINK)'
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_FOREIGN FROM dbo.DICTION_REF B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							WHEN @varKSRefField = 'OBJECT' THEN
								'(SELECT C.OBJECT FROM dbo.DICTION_REF B , dbo.DICTION C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_FOREIGN=C.LINK)'
							WHEN @varKSRefLINK2 is not null and @varKSRefField2 <> '' THEN
								'(SELECT convert('+@varKSType+','+@varKSRefField2+@varKSADDTYPE+') FROM dbo.DICTION D2, dbo.DICTION_REF DR1, dbo.DICTION_REF DR2 WHERE DR1.REF_PRIMARY=A.LINK AND DR1.OBJECT = '+LTRIM(STR(@varKSRefLINK))+' AND DR2.REF_PRIMARY = DR1.REF_FOREIGN AND DR2.OBJECT = '+LTRIM(STR(@varKSRefLINK2))+' AND D2.LINK = DR2.REF_FOREIGN)'
							ELSE
								' '
						     END


						WHEN  @varKSStorage='DICTION_DEP' THEN
						     CASE 
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_DEP FROM dbo.DICTION_DEP B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							ELSE
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.DICTION_DEP B , dbo.DEPARTMENTS C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_DEP=C.LINK)'
						     END
						WHEN  @varKSStorage='DICTION_TAB' THEN
						     CASE 
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_TAB FROM dbo.DICTION_TAB B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							WHEN @varKSRefLINK2 is not null and @varKSRefField2 <> '' THEN
								'(SELECT convert('+@varKSType+',C.'+@varKSRefField2+@varKSADDTYPE+') FROM dbo.DICTION_REF DR, dbo.DICTION_TAB DT, dbo.'+ RTRIM(LTRIM(@varKSparCODE)) + ' C  '+ 
								'WHERE DR.REF_PRIMARY=A.LINK AND DR.OBJECT = '+LTRIM(STR(@varKSRefLINK))+' AND DT.REF_PRIMARY = DR.REF_FOREIGN AND DT.OBJECT = '+LTRIM(STR(@varKSRefLINK2))+' AND C.LINK = DT.REF_TAB)'
							ELSE
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.DICTION_TAB B , dbo.'+ RTRIM(LTRIM(@varKSparCODE)) + ' C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_TAB=C.LINK)'
						     END
						WHEN  @varKSStorage='DICTIONARY_DEPARTMENT' THEN
						     CASE 
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_DEP FROM dbo.DICTION_DEP B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							ELSE
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.DICTION_DEP B , dbo.DICTIONARY_DEPARTMENT C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_DEP=C.LINK)'
						     END

						WHEN  @varKSStorage='DICTION_KLADR' THEN
						    CASE 
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_FOREIGN FROM dbo.DICTION_KLADR B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							ELSE
								' '
						    END

						WHEN  @varKSStorage='PAYS_DICTION' THEN
						     CASE 
							WHEN @varKSRefField IN ('CODE', 'NAME') THEN
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.PAYS_DICTION B , dbo.PAYS C  '+ 
								'WHERE B.LINK_DICTION = A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.LINK_PAYS = C.LINK)'
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.LINK_PAYS  FROM dbo.PAYS_DICTION B '+ 
								'WHERE B.LINK_DICTION = A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							WHEN @varKSRefField = 'OBJECT' THEN
								'(SELECT C.OBJECT FROM dbo.PAYS_DICTION B , dbo.PAYS C  '+ 
								'WHERE B.LINK_DICTION = A.LINK AND B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.LINK_PAYS=C.LINK)'


							ELSE
								' '
						     END

						WHEN  @varKSStorage='SUBDIV_HEAD' THEN
						     CASE 
							WHEN @varKSRefField = 'LINK' THEN
								'(SELECT B.REF_SUBDIV_HEAD FROM dbo.DICTION_SUBDIV_HEAD B  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) +')'
							ELSE
								'(SELECT convert(' +@varKSType +',C.'+@varKSRefField + @varKSADDTYPE+') FROM dbo.DICTION_SUBDIV_HEAD B, dbo.DICTIONARY_SUBDIVISION C  '+ 
								'WHERE B.REF_PRIMARY=A.LINK AND  B.OBJECT='+LTRIM(STR(@varKSRefLINK)) +' AND B.REF_SUBDIV_HEAD=C.LINK)'
						     END

						WHEN  @varKSStorage='S_PERIOD' THEN
						     CASE
							WHEN @varKSRefField IN ('YEAR', 'MONTH') THEN
								'(SELECT '+@varKSRefField+' FROM Z_DICTION_PERIOD B, S_PERIOD SP'+
								' WHERE B.DICTION=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSRefLINK))+' AND SP.LINK = B.PERIOD)'
							WHEN @varKSRefField = 'PERIOD' THEN
								'(SELECT PERIOD FROM Z_DICTION_PERIOD B'+
								' WHERE B.DICTION=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) + ')'
							ELSE
								' '
							END
						WHEN  @varKSStorage='Z_DICT_OPER' THEN
						     CASE
							WHEN @varKSRefField = 'NAME_OPER' THEN
								'(SELECT convert(' +@varKSType +',G1.'+@varKSRefField + @varKSADDTYPE+') FROM Z_DICT_OPER B , G_PROV1 G1'+
								' WHERE B.DICTION=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSRefLINK))+' AND G1.LINK = B.OPER)'
							WHEN @varKSRefField = 'OPER' THEN
								'(SELECT OPER FROM Z_DICT_OPER B'+
								' WHERE B.DICTION=A.LINK AND B.OBJECT='+LTRIM(STR(@varKSCurLINK)) + ')'
							ELSE
								' '
							END
						WHEN  @varKSStorage = 'DICTION' THEN

						      CASE
							WHEN @varKSRefField IN ('NAME', 'CODE') THEN
							'convert(' + @varKSType +',A.'+@varKSRefField + @varKSADDTYPE+')' 
							WHEN @varKSRefField = 'OBJECT' THEN
							'A.OBJECT '
							ELSE	
								'0' 
						      END

						WHEN @varKSStorage = 'S_ACCOUNTS' THEN
						     CASE 
							WHEN @varKSRefField IN ('LINK') THEN
							     '(SELECT DA.ACCOUNT FROM dbo.DICTION_ACCOUNTS DA' +
							     ' WHERE DA.DICTION = A.LINK ' +
							     ' AND DA.OBJECT = ' + LTRIM(STR(@varKSCurLINK)) + ')'
							WHEN  @varKSRefField IN ('CODE', 'NAME') THEN
							     '(SELECT convert(' + @varKSType +', SA.'+@varKSRefField + @varKSADDTYPE+') ' +
							     ' FROM dbo.DICTION_ACCOUNTS DA, S_ACCOUNTS SA ' +
							     ' WHERE DA.DICTION = A.LINK ' +
							     ' AND DA.OBJECT = ' + LTRIM(STR(@varKSRefLINK)) +
							     ' AND SA.LINK = DA.ACCOUNT)' 
						     	ELSE 
								' '
						     END

						WHEN @varKSStorage = 'CALCULATE' THEN
						     CASE 
							WHEN @varKSRefField IS NOT NULL THEN
							'convert(' + @varKSType +', '+@varKSRefField + @varKSADDTYPE+')' 
							ELSE	
								'0' 
						     END

						ELSE
							' '
					 END

	
			IF (@varKSStorage='DICTION_REF' OR @varKSStorage='DICTION_KLADR' OR @varKSStorage='DICTION_DEP' OR @varKSStorage='SUBDIV_HEAD')AND @varKSRefField <> 'LINK'
				IF @varKSRefLINK is null
					Print '***Свойство REFERENCE TO FIELD ошибочно или отсутствует! '
			IF @varKSStorage='PAYS_DICTION' AND @varKSRefField <> 'LINK'
				IF @varKSRefLINK is null
					Print '***Свойство REFERENCE TO FIELD ошибочно или отсутствует! '

			IF @varKSStorage='S_PERIOD' AND @varKSRefField <> 'PERIOD'
				IF @varKSRefLINK is null
					Print '***Свойство REFERENCE TO FIELD ошибочно или отсутствует! '
			IF @varKSStorage='Z_DICT_OPER' AND @varKSRefField <> 'OPER'
				IF @varKSRefLINK is null
					Print '***Свойство REFERENCE TO FIELD ошибочно или отсутствует! '
			IF @varKSStorage='DICTION_APP' AND (@varKSRefDict <> '' OR @varKSRefDict <> '')
				IF @varKSRefLINK is null or @varKSRefLINK2 is null
					Print '***Свойство REFERENCE TO DICT(или FIELD) ошибочно или отсутствует! '


			

	  		 IF  NOT (@varKSStorage IN ('DICTION', 'DICTION_REF', 'DICTION_APP', 'Z_DICT_OPER', 'S_PERIOD',
				'S_ACCOUNTS', 'CALCULATE', 'PAYS_DICTION', 'DICTION_KLADR', 'DICTION_DEP', 'DICTION_TAB', 'DICTIONARY_DEPARTMENT', 'SUBDIV_HEAD'))
			BEGIN
				SET @varKSCur_Str=''
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE
			END

			IF @varKSCur_Str is null
			BEGIN
				SET @varKSCur_Str=''
				print 'ОШИБКА!'
			END
			SET @varKSSel_Str=@varKSSel_Str+@varKSCur_Str
		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	END
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR
	IF @varKScCode = 'DICTIONARY_STORAGE_CARD'
		SET  @varKSSel_Str=@varKSSel_Str+',
		 [PRICE] = T_PRICE.PRICE,
		 [QTY_REST] = REST.QTY
		 FROM dbo.DICTION A LEFT OUTER JOIN dbo.GetStorageRest (DEFAULT, DEFAULT) REST ON (REST.LINK_CARD = A.LINK)
			LEFT OUTER JOIN dbo.GetPriceINVByTable (DEFAULT) T_PRICE ON (T_PRICE.LINK_CARD = A.LINK)
		 WHERE OBJECT='+(SELECT LTRIM(STR(LINK)) FROM S_OBJECTS WHERE CODE = @varKShostCode)
	ELSE
		SET  @varKSSel_Str=@varKSSel_Str+'
		 FROM dbo.DICTION A  WHERE OBJECT='+(SELECT LTRIM(STR(LINK)) FROM S_OBJECTS WHERE CODE = @varKShostCode)
	
	IF object_id(@varKScCode) is not null
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str
	
PRINT (@varKSSel_Str)

	EXECUTE (@varKSSel_Str)
	
	SET @varKSCur_Str='GRANT ALL ON '+@varKScCode+' TO Public'
	
	EXECUTE (@varKSCur_Str)

	DECLARE @varKSscriptstr varchar(7000)
	IF @varKShostCode <> @varKScCode
		SET @varKSscriptstr = 'EXECUTE dbo.X_FORM_VIEW_DICTIONARY '''+@varKScCode+'''' + (',''' + RTRIM(@varKShostCode) + '''')
	ELSE
		SET @varKSscriptstr = 'EXECUTE dbo.X_FORM_VIEW_DICTIONARY '''+@varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKScCode, @varKSscriptstr


	
	
	
	


	UPDATE dbo.S_DBObjects SET Rights = 0x01 WHERE Object=@varKSnLink AND DBObject=@varKScCode
	IF @@ROWCOUNT = 0	
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScCode, 0x01)

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_SAVE_DICTIONARY_MROT_TABLE3]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE3]

GO

CREATE     PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_MROT_TABLE3
	@varKSLINK_MINROT	INT,
	@varKSLINK_PAYS	    INT,
	@varKSPREDEL	NUMERIC(15,2),
	@varKSSTAVKA	NUMERIC(15,2)
AS
DECLARE @varKSObject int
SELECT @varKSObject = LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T3'

IF @varKSLINK_MINROT IS NULL OR @varKSLINK_MINROT = 0
	RETURN 5

IF @varKSLINK_PAYS IS NULL OR @varKSLINK_PAYS = 0
	RETURN 5
	
IF EXISTS (SELECT * FROM  MINROT_PAYS where link_minrot = @varKSLINK_MINROT and LINK_PAYS = @varKSLINK_PAYS and [object] = @varKSObject)
begin 
	RETURN 8 
end	
	

INSERT INTO MINROT_PAYS (LINK_MINROT,LINK_PAYS,OBJECT,PREDEL,PERIOD,SUMMA)
VALUES(@varKSLINK_MINROT,@varKSLINK_PAYS,@varKSObject,@varKSPREDEL,0,@varKSSTAVKA)


GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE3] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RO_MULT_DIV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RO_MULT_DIV]

GO




/*
© Кейсистемс (Keysystems), 2005
добаляем размножение по строкам
*/
CREATE  PROCEDURE dbo.RO_MULT_DIV
	@varKScExecStr	varchar(500),
	@varKSiLSF	int,
	@varKScCodeRow	varchar(50) = ''
AS
	declare @val numeric(18, 2)
	
	set ansi_warnings OFF
	SET ARITHABORT OFF
	SET ARITHIGNORE OFF
	
	set @varKScExecStr = REPLACE(REPLACE(@varKScExecStr, '[', '('), ']', ',' + STR(@varKSiLSF) + ')')
	set @varKScExecStr = REPLACE(REPLACE(@varKScExecStr, '{', '('), '}', ')')
	set @varKScExecStr = REPLACE(@varKScExecStr, '###', @varKScCodeRow)
	create table #ro_mult_div_val (val float(53))
	print('declare @P float(53) set @P = ' + @varKScExecStr + ' insert #ro_mult_div_val (val) values (@P)')
	execute('declare @P float(53) set @P = ' + @varKScExecStr + ' insert #ro_mult_div_val (val) values (@P)')
	select @val = val from #ro_mult_div_val
	drop table #ro_mult_div_val

	set ansi_warnings ON
	SET ARITHABORT ON
	SET ARITHIGNORE ON

	select isnull(@val, 0)






GO


GRANT EXECUTE ON dbo.[RO_MULT_DIV] 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_UVED_GET_DOC]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_UVED_GET_DOC]
GO


create procedure dbo.BB_UVED_GET_DOC @iLinkDoc int

as
declare @cDocCode varchar(100), 
		@cDocName varchar(254),
		@iObjLink int


select	@cDocCode = SO.CODE, 
		@cDocName = OV.NAME,
		@iObjLink = SO.LINK
from dbo.G_PROV G  
inner join dbo.S_OBJECTS SO on G.OBJECT = SO.LINK  and G.LINK = @iLinkDoc
inner join dbo.OSNOV_VID OV on OV.OBJECT = SO.CODE 
					
		  

if @cDocCode = 'DOCUMENTS_RECEPTION_CASH'
	Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
			DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
			DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
			DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKATO, 
			KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = T.SUMMA, 
			[TARGET] = coalesce(T.REASON,CONVERT(VARCHAR(210), (select GPV.VALUE from dbo.G_PROV_VALUE gpv where GPV.DOC_LINK = @iLinkDoc and GPV.OBJECT = @iObjLink)),''), 
			TITLE = '', 
			DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
	from dbo.G_PROV G  
	inner join dbo.RECEPTION_CASH_TABLE T on T.LINK_UP = G.LINK
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = G.ACC
	inner join dbo.DEPARTMENTS D on D.LINK = G.DEP
	inner join dbo.KL_KBK KBK on KBK.LINK = T.KBK
	inner join dbo.KOSGU  SGU on SGU.LINK = T.EKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.DOP_CLASSIF
	where G.LINK = @iLinkDoc
	
else 
	if @cDocCode = 'BB_ZAYAVKA_KR'
		Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
				DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
				DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
				DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKATO, 
				KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = T.SUMMA, 
				[TARGET] = coalesce(T.[TARGET],LEFT(Z.TARGETTEXT,210),''), 
				TITLE = '', 
				DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
		from dbo.G_PROV G  
		inner join dbo.FINANSE_PAYS Z on Z.LINK = G.LINK
		inner join dbo.ZAYAVKA_KR_TABLE T on T.LINK_UP = G.LINK
		inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = Z.D_ACC
		inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
		inner join dbo.KL_KBK KBK on KBK.LINK = T.LINK_KBK
		inner join dbo.KOSGU  SGU on SGU.LINK = T.LINK_SGU
		left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.LINK_DCL
		where G.LINK = @iLinkDoc

	else
		if @cDocCode = 'DOCUMENTS_PAY'
			Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
					DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
					DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
					DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKATO, 
					KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = G2.SUMMA, 
					[TARGET] = isnull(LEFT(Z.TARGETTEXT,210),''), 
					TITLE = '', 
					DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
			from dbo.G_PROV G  
			inner join dbo.FINANSE_PAYS Z on Z.LINK = G.LINK
			inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = Z.D_ACC
			inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
			inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK 
			inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK 
			inner join dbo.G_PROV_AP GAP1 on GAP1.LINK_UP = G2.LINK and GAP1.DB_KR = 0 
			inner join dbo.G_PROV_AP GAP2 on GAP2.LINK_UP = G2.LINK and GAP2.DB_KR = 1 
			inner join dbo.KL_KBK KBK on KBK.LINK = isnull(GAP2.KBK,GAP1.KBK) 
			inner join dbo.KOSGU  SGU on SGU.LINK = isnull(GAP2.SGU,GAP1.SGU) 
			left join dbo.DOP_CLASSIF DCL on DCL.LINK = isnull(GAP2.AP2,GAP1.AP2) 
			where G.LINK = @iLinkDoc
			

		else
		Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
								LINK_G1 = G1.LINK, DOC_NUM = G.NUMBER, DOC_DATE = G.DATE,	DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
								DOC_NAME = CONVERT(VARCHAR(50), case @cDocCode when 'DOCUMENTS_OPER' then dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT) else @cDocName end +' № ' + LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104)),
								DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKATO, 
								KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = G2.SUMMA, 
								[TARGET] = '', TITLE = '', 
								DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
							from dbo.G_PROV G  
							inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK 
							inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK 
							inner join dbo.G_PROV_AP GAP1 on GAP1.LINK_UP = G2.LINK and GAP1.DB_KR = 0 
							inner join dbo.G_PROV_AP GAP2 on GAP2.LINK_UP = G2.LINK and GAP2.DB_KR = 1 
							left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = isnull(GAP2.DEP_ACC,GAP1.DEP_ACC) 
							left join dbo.DEPARTMENTS D on D.LINK = coalesce(GAP2.DEP,GAP1.DEP,DA.LINK_UP) 
							inner join dbo.KL_KBK KBK on KBK.LINK = isnull(GAP2.KBK,GAP1.KBK) 
							inner join dbo.KOSGU  SGU on SGU.LINK = isnull(GAP2.SGU,GAP1.SGU) 
							left join dbo.DOP_CLASSIF DCL on DCL.LINK = isnull(GAP2.AP2,GAP1.AP2) 
							where G.LINK = @iLinkDoc
							
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SAVE_IN_EXECUTOR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SAVE_IN_EXECUTOR]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

-- warning: LINK и LINK_TASK указывают на EVENT_LINKS!

CREATE  PROCEDURE dbo.DP_SAVE_IN_EXECUTOR 
    @varKSparLINK       INT OUTPUT,
    @varKSparLINK_DOC	 INT,
    @varKSparSROK_DATE  DATETIME,
    @varKSparEXECUTOR   INT,
    @varKSparCHECKED    BIT,
    @varKSparISP        BIT,
    @varKSparISP_DATE   DATETIME,
    @varKSparRES_LINK   INT,
    @varKSparRES_COMMENT   VARCHAR(1000),
    @varKSparLINK_TASK  INT = NULL
AS

DECLARE @varKSSQLError    TINYINT,
        @varKStrancount   INT,
        @varKSRowCount    INT,
        @varKSEventLink   INT,
        @varKSTaskLINK    INT,
        @varKSObjEXECUTOR INT,
		@iEOSRep bit

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON

BEGIN TRAN
COMMIT TRAN

	
IF @varKSparLINK_DOC IS NULL OR @varKSparLINK_DOC = 0
BEGIN
     ROLLBACK
     RETURN 5
END

set @iEOSRep = 0

IF @varKSparLINK <= 0 
  SET @varKSparLINK = NULL

IF ISNULL(@varKSparLINK_TASK,0) <= 0
  SET @varKSparLINK_TASK = NULL

IF EXISTS(SELECT EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK) 
  SELECT @varKSEventLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK
ELSE
  SET @varKSEventLink = NULL

IF EXISTS(SELECT EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK_TASK) 
  SELECT @varKSTaskLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK_TASK
ELSE
  SET @varKSTaskLink = NULL

IF @varKSEventLink IS NULL
BEGIN
    DECLARE	@varKSUserRef INT
	SELECT @varKSUserRef = USER_REF FROM WHO_IS_WHO WHERE SID = SUSER_SID()
	IF @varKSUserRef IS NULL
		SET @varKSUserRef = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')

     INSERT INTO dbo.EVENT_EXECUTORS WITH (ROWLOCK) (LINK_DOC,SROK_DATE,EXECUTOR,CHECKED,ISP,ISP_DATE,RES_LINK,COMMENT,EVENT_DATE,EVENT_LINK_EMPL) 
     VALUES (@varKSparLINK_DOC, @varKSparSROK_DATE, @varKSparEXECUTOR, @varKSparCHECKED, @varKSparISP, @varKSparISP_DATE, @varKSparRES_LINK, @varKSparRES_COMMENT, GETDATE(), @varKSUserRef)

     SELECT @varKSSQLError = @@ERROR, @varKSEventLink = SCOPE_IDENTITY()
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END

     SELECT @varKSObjEXECUTOR = LINK FROM S_OBJECTS WHERE CODE = 'WF_EVENT_EXECUTOR'
     SELECT @varKSparLink = LINK FROM EVENT_LINKS WHERE EVENT_LINK = @varKSEventLink AND OBJECT = @varKSObjEXECUTOR

     IF @varKSTaskLINK IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.EVENT_TASK_REF WHERE LINK_TASK = @varKSTaskLINK AND LINK_EXECUTORS = @varKSEventLink)
        INSERT INTO dbo.EVENT_TASK_REF (LINK_TASK,LINK_EXECUTORS)
        VALUES (@varKSTaskLINK,@varKSEventLink) 
	set @iEOSRep = 1
     	
END
ELSE
BEGIN
	if @varKSparISP = 1 and exists(select * from dbo.EVENT_EXECUTORS where LINK = @varKSEventLink and ISP = 0) 
		set @iEOSRep = 1

     UPDATE dbo.EVENT_EXECUTORS WITH (ROWLOCK) 
     SET LINK_DOC = @varKSparLINK_DOC, SROK_DATE = @varKSparSROK_DATE, EXECUTOR = @varKSparEXECUTOR, CHECKED = @varKSparCHECKED, ISP = @varKSparISP,
         ISP_DATE = @varKSparISP_DATE, RES_LINK = @varKSparRES_LINK, COMMENT = @varKSparRES_COMMENT
     WHERE LINK = @varKSEventLink
    
     SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END
    
     IF @varKSRowCount = 0
     BEGIN
          ROLLBACK
          RETURN 2
     END
END	

UPDATE dbo.DOCUMENTS
SET ISP = (CASE
   WHEN (((SELECT COUNT(*) FROM dbo.EVENT_EXECUTORS EE WHERE EE.LINK_DOC = D.LINK) > 0) AND
         ((SELECT COUNT(*) FROM dbo.EVENT_EXECUTORS EE WHERE EE.CHECKED = 1 AND EE.ISP = 0 AND EE.LINK_DOC = D.LINK) = 0)) THEN 1
   ELSE 0
  END)
FROM dbo.DOCUMENTS AS D
WHERE D.LINK = @varKSparLINK_DOC

   IF NOT (dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
	OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
		if @iEOSRep = 1 
			IF EXISTS (SELECT * FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC)	
				AND EXISTS (SELECT * FROM dbo.EOS_JURNAL WHERE INOUT = 0 AND TYPE_M = 1 AND LINK_DOC = @varKSparLINK_DOC)
			exec EOS_EXPORT_REPORT @varKSparLINK_DOC,@varKSparLINK_TASK

EXECUTE DP_ADD_REC_ACCESS @varKSparLINK_DOC, @varKSparEXECUTOR

IF @@TRANCOUNT > @varKStrancount
   COMMIT TRAN

RETURN 0


GO


GRANT EXECUTE ON dbo.[DP_SAVE_IN_EXECUTOR] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE4]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE4]

GO

CREATE     PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_MROT_TABLE4
	@varKSLINK_MINROT	INT,
	@varKSLINK_PAYS	    INT
AS

DECLARE @varKSObject int
SELECT @varKSObject = LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T4'

IF @varKSLINK_MINROT IS NULL OR @varKSLINK_MINROT = 0
	RETURN 5

IF @varKSLINK_PAYS IS NULL OR @varKSLINK_PAYS = 0
	RETURN 5
	
IF EXISTS (SELECT * FROM  MINROT_PAYS where link_minrot = @varKSLINK_MINROT and LINK_PAYS = @varKSLINK_PAYS and [object] = @varKSObject)
begin 
	RETURN 8 
end		

INSERT INTO MINROT_PAYS (LINK_MINROT,LINK_PAYS,[OBJECT])
VALUES(@varKSLINK_MINROT,@varKSLINK_PAYS,@varKSObject)



GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_MROT_TABLE4] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
SET ANSI_WARNINGS OFF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_CHANGE_RRO_PERSPECTIVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_CHANGE_RRO_PERSPECTIVE]
GO

CREATE procedure [dbo].[RT_CHANGE_RRO_PERSPECTIVE]
	@iLink_sf int
AS
	-- return
	-- изменить представление --
	declare @col11_t1 int,
			@col17_t1 int,
			@col18_t1 int,
			@col19_t1 int,
			@col20_t1 int,
			@col21_t1 int,
			@col22_t1 int,

			@col23_t1 int,
			@col29_t1 int,
			@col30_t1 int,
			@col31_t1 int,
			@col32_t1 int,
			@col33_t1 int,
			@col34_t1 int,

			@col11_t2 int,
			@col17_t2 int,
			@col18_t2 int,
			@col19_t2 int,
			@col20_t2 int,
			@col21_t2 int,
			@col22_t2 int,

			@col23_t2 int,
			@col29_t2 int,
			@col30_t2 int,
			@col31_t2 int,
			@col32_t2 int,
			@col33_t2 int,
			@col34_t2 int,

			@col35_t2 int,
			@col41_t2 int,
			@col42_t2 int,
			@col43_t2 int,
			@col44_t2 int,
			@col45_t2 int,
			@col46_t2 int,
	
			@link_f  int,
			@link_t1 int,
			@link_t2 int,

			@col8_t1 int,
			@col8_t2 int,
			------------
			@PeriodCode datetime
			------------
	select @PeriodCode = begin_date from dbo.report_saved_forms where link_saved_form = @iLink_sf

	select @link_f = link_form from dbo.report_saved_forms where link_saved_form = @iLink_sf
	select @link_t1 = link_table from dbo.report_tables where link_form = @link_f and orders = 1
	select @link_t2 = link_table from dbo.report_tables where link_form = @link_f and orders = 2

	select @col11_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 11 
	select @col17_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 17 
	select @col18_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 18 
	select @col19_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 19 
	select @col20_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 20 
	select @col21_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 21 
	select @col22_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 22 

	select @col23_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 23 
	select @col29_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 29 
	select @col30_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 30 
	select @col31_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 31 
	select @col32_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 32 
	select @col33_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 33 
	select @col34_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 34

	select @col8_t1 = link_col from dbo.report_coloumns where link_table = @link_t1 and orders = 8 

	select @col11_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 11 
	select @col17_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 17 
	select @col18_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 18 
	select @col19_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 19 
	select @col20_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 20 
	select @col21_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 21 
	select @col22_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 22 

	select @col23_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 23 
	select @col29_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 29 
	select @col30_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 30 
	select @col31_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 31 
	select @col32_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 32 
	select @col33_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 33 
	select @col34_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 34 

	select @col35_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 35 
	select @col41_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 41 
	select @col42_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 42 
	select @col43_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 43 
	select @col44_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 44 
	select @col45_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 45 
	select @col46_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 46 

	select @col8_t2 = link_col from dbo.report_coloumns where link_table = @link_t2 and orders = 8 

	insert into dbo.report_dinamics (link_sf,link_col,code_row,float_val,str_val)
	select @iLink_sf,@col17_t1,rd.code_row,0.0,'' from dbo.report_dinamics as rd where rd.link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t1) group by rd.code_row 
	insert into dbo.report_dinamics (link_sf,link_col,code_row,float_val,str_val)
	select @iLink_sf,@col29_t1,rd.code_row,0.0,'' from dbo.report_dinamics as rd where rd.link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t1) group by rd.code_row 

	insert into dbo.report_dinamics (link_sf,link_col,code_row,float_val,str_val)
	select @iLink_sf,@col17_t2,rd.code_row,0.0,'' from dbo.report_dinamics as rd where rd.link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2) group by rd.code_row 
	insert into dbo.report_dinamics (link_sf,link_col,code_row,float_val,str_val)
	select @iLink_sf,@col29_t2,rd.code_row,0.0,'' from dbo.report_dinamics as rd where rd.link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2) group by rd.code_row 
	insert into dbo.report_dinamics (link_sf,link_col,code_row,float_val,str_val)
	select @iLink_sf,@col41_t2,rd.code_row,0.0,'' from dbo.report_dinamics as rd where rd.link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2) group by rd.code_row
   
   SELECT TOP 0 * INTO #report_dinamics FROM dbo.report_dinamics    

	update dbo.report_dinamics 
	set str_val = 
		case
			when rd.link_col = @col11_t1 and len(rd.str_val)>0 and not (ltrim(rtrim(isnull(rd.str_val,''))) like '%от%№%' and len(dbo.RT_RRO_GET_BNAME(ltrim(rtrim(isnull(rd.str_val,'')))))>0)  -- наименование фед НПА
			then 
				replace(ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col18_t1/*TYPE*/ and rd1.code_row = rd.code_row),''))),'"','``')+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col20_t1/*DATE*/ and rd1.code_row = rd.code_row))>0 
					then ' от ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col20_t1/*DATE*/ and rd1.code_row = rd.code_row),'')))+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
					then ' № ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t1/*NUMB*/ and rd1.code_row = rd.code_row),'')))+
				' "'+
				ltrim(rtrim(isnull(rd.str_val,'')))+
				'"'

			when rd.link_col = @col17_t1 -- Дата вступления в силу и срок действия фед НПА
			then
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col21_t1/*N_DB*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col21_t1/*N_DB*/ and rd1.code_row = rd.code_row))) + ' - ' 
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен - ' 
						else ''
						end
				end +
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col22_t1/*N_DE*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col22_t1/*N_DE*/ and rd1.code_row = rd.code_row))) 
					else 						
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен' 
						else ''
						end

				end
			-------------------------------------------------------------------------------------------------------------------------------------
			when rd.link_col = @col23_t1 and len(rd.str_val)>0 and not (ltrim(rtrim(isnull(rd.str_val,''))) like '%от%№%' and len(dbo.RT_RRO_GET_BNAME(ltrim(rtrim(isnull(rd.str_val,'')))))>0)-- наименование субъ НПА
			then 
				replace(ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col30_t1/*TYPE*/ and rd1.code_row = rd.code_row),''))),'"','``')++
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col32_t1/*DATE*/ and rd1.code_row = rd.code_row))>0 
					then ' от ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col32_t1/*DATE*/ and rd1.code_row = rd.code_row),'')))+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
					then ' № ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t1/*NUMB*/ and rd1.code_row = rd.code_row),'')))+
				' "'+
				ltrim(rtrim(isnull(rd.str_val,'')))+
				'"'

			when rd.link_col = @col29_t1 -- Дата вступления в силу и срок действия субъ НПА
			then
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col33_t1/*N_DB*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col33_t1/*N_DB*/ and rd1.code_row = rd.code_row))) + ' - '
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен - ' 
						else ''
						end

				end +
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col34_t1/*N_DE*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col34_t1/*N_DE*/ and rd1.code_row = rd.code_row))) 
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t1/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен' 
						else ''
						end
				end
			---------------------------------------------------------------------------------------------------------------------------------------
			---для таблицы 2----
			when rd.link_col = @col11_t2 and len(rd.str_val)>0 and not (ltrim(rtrim(isnull(rd.str_val,''))) like '%от%№%' and len(dbo.RT_RRO_GET_BNAME(ltrim(rtrim(isnull(rd.str_val,'')))))>0)-- наименование фед НПА
			then 
				replace(ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col18_t2/*TYPE*/ and rd1.code_row = rd.code_row),''))),'"','``')++
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col20_t2/*DATE*/ and rd1.code_row = rd.code_row))>0 
					then ' от ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col20_t2/*DATE*/ and rd1.code_row = rd.code_row),'')))+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
					then ' № ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t2/*NUMB*/ and rd1.code_row = rd.code_row),'')))+
				' "'+
				ltrim(rtrim(isnull(rd.str_val,'')))+
				'"'

			when rd.link_col = @col17_t2 -- Дата вступления в силу и срок действия фед НПА
			then
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col21_t2/*N_DB*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col21_t2/*N_DB*/ and rd1.code_row = rd.code_row))) + ' - '
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен - ' 
						else ''
						end
				end +
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col22_t2/*N_DE*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col22_t2/*N_DE*/ and rd1.code_row = rd.code_row))) 
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col19_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен' 
						else ''
						end
				end
			-------------------------------------------------------------------------------------------------------------------------------------
			when rd.link_col = @col23_t2 and len(rd.str_val)>0  and not (ltrim(rtrim(isnull(rd.str_val,''))) like '%от%№%' and len(dbo.RT_RRO_GET_BNAME(ltrim(rtrim(isnull(rd.str_val,'')))))>0)-- наименование субъ НПА
			then 
				replace(ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col30_t2/*TYPE*/ and rd1.code_row = rd.code_row),''))),'"','``')++
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col32_t2/*DATE*/ and rd1.code_row = rd.code_row))>0 
					then ' от ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col32_t2/*DATE*/ and rd1.code_row = rd.code_row),'')))+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
					then ' № ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t2/*NUMB*/ and rd1.code_row = rd.code_row),'')))+
				' "'+
				ltrim(rtrim(isnull(rd.str_val,'')))+
				'"'

			when rd.link_col = @col29_t2 -- Дата вступления в силу и срок действия субъ НПА
			then
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col33_t2/*N_DB*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col33_t2/*N_DB*/ and rd1.code_row = rd.code_row))) + ' - '
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0
						then 'не установлен - ' 
						else ''
						end
				end +
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col34_t2/*N_DE*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col34_t2/*N_DE*/ and rd1.code_row = rd.code_row))) 
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col31_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0
						then 'не установлен' 
						else ''
						end
				end
			-------------------------------------------------------------------------------------------------------------------------------------
			when rd.link_col = @col35_t2 and len(rd.str_val)>0 and not (ltrim(rtrim(isnull(rd.str_val,''))) like '%от%№%' and len(dbo.RT_RRO_GET_BNAME(ltrim(rtrim(isnull(rd.str_val,'')))))>0)-- наименование местного НПА
			then 
				replace(ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col42_t2/*TYPE*/ and rd1.code_row = rd.code_row),''))),'"','``')++
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col44_t2/*DATE*/ and rd1.code_row = rd.code_row))>0 
					then ' от ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col44_t2/*DATE*/ and rd1.code_row = rd.code_row),'')))+
				case 
					when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col43_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
					then ' № ' 
					else '' 
				end+	
				ltrim(rtrim(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col43_t2/*NUMB*/ and rd1.code_row = rd.code_row),'')))+
				' "'+
				ltrim(rtrim(isnull(rd.str_val,'')))+
				'"'

			when rd.link_col = @col41_t2 -- Дата вступления в силу и срок действия местного НПА
			then
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col45_t2/*N_DB*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col45_t2/*N_DB*/ and rd1.code_row = rd.code_row))) + ' - '
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col43_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен - ' 
						else ''
						end
				end +
				case 
					when len(isnull((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col46_t2/*N_DE*/ and rd1.code_row = rd.code_row),''))>0 
					then ltrim(rtrim((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col46_t2/*N_DE*/ and rd1.code_row = rd.code_row))) 
					else 
						case 
						when len((select rd1.str_val from dbo.report_dinamics as rd1 where rd1.link_sf = @iLink_sf and rd1.link_col = @col43_t2/*NUMB*/ and rd1.code_row = rd.code_row))>0 
						then 'не установлен' 
						else ''
						end
				end
			-------------------------------------------------------------------------------------------------------------------	
			else rd.str_val
		end
	from dbo.report_dinamics as rd
	where link_sf = @iLink_sf

	--EXEC dbo.[RN_SPLIT_CODE_ROW] @iLink_sf  
	---- добаляем записи в дерево -----
	declare @nnp varchar(50),
			@code varchar(9),
			@name varchar(8000),
			@nn int,
			@code_row varchar(50)
 
	declare @t table (nn int identity(1,1), code_row varchar(50), nnp varchar(50), code varchar(9), [name] varchar(8000))
	-- для т1 --
	insert into @t(code_row, nnp, code, [name])
	select
		code_row, 
		SUBSTRING(RTRIM(CODE_ROW)+'       ',1,7),
		SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9),
		''
	from dbo.report_dinamics 
	where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t1)
	and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) not in (select code from dbo.RT_GET_RECORDS_RRO (0,@PeriodCode))
	and RIGHT(RTRIM(CODE_ROW),3) = '000'
	group by code_row
	
	update @t
	set [name] = (
		select ltrim(rtrim(isnull(rd.str_val,''))) 
		from dbo.report_dinamics as rd 
		where rd.link_sf = @iLink_sf and rd.link_col = @col8_t1 and rd.code_row = t.code_row
	)
	from @t as t

	while exists(select * from @t where code is not null) begin
		select top 1 @nn = nn, @nnp = isnull(nnp,''), @code = isnull(code,''), @name = isnull([name],'') from @t
		
		IF EXISTS(SELECT * from dbo.RT_GET_RECORDS_RRO(1,@PeriodCode) WHERE [code] = @code)
		BEGIN 
		   SELECT @name = true_name, @nnp = pnum from dbo.RT_GET_RECORDS_RRO(1,@PeriodCode) WHERE [code] = @code
	      UPDATE dbo.report_dinamics 
	      SET str_val = ISNULL(@name, '')
		   where link_sf = @iLink_sf and link_col = @col8_t1 AND SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) = @code --AND ISNULL([Str_Val], '') <> ''

         IF @@ROWCOUNT = 0
            INSERT dbo.[REPORT_DINAMICS] ([Link_SF], [Link_Col], [Code_Row], [Float_Val], [Str_Val])
            SELECT @iLink_sf, @col8_t1, LEFT(@nnp + '       ', 7) +  LEFT(@code + '         ', 9) + '000', 0, ISNULL(@name, '')
         
--         TRUNCATE table #report_dinamics
--         
--         INSERT #report_dinamics (link_sf, code_row, link_col, float_val, str_val)
--         SELECT link_sf, left(@nnp + '       ',7) + SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12), link_col, sum(float_val), max(str_val)
--         FROM dbo.report_dinamics
--         where link_sf = @iLink_sf and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12) = @code +'000'
--         GROUP BY  link_sf, left(@nnp + '       ',7) + SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12), link_col
--         
--         DELETE dbo.report_dinamics
--         WHERE link_sf = @iLink_sf and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12) = @code +'000'
--         
--         INSERT dbo.report_dinamics (link_sf, code_row, link_col, float_val, str_val)
--         SELECT link_sf, code_row, link_col, float_val, str_val
--         FROM #report_dinamics
         
	   END 
	   ELSE BEGIN
	      exec dbo.[RT_RRO_ADD_RO] @nnp,@code,@name,1,@PeriodCode
	   END 

		delete from @t where nn = @nn
	end

	-- для т2 --
	delete from @t
	insert into @t (code_row, nnp, code, [name])
	select
		code_row, 
		SUBSTRING(RTRIM(CODE_ROW)+'       ',1,7),
		SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9),
		''
	from dbo.report_dinamics 
	where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2)
	and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) not in (select code from dbo.RT_GET_RECORDS_RRO (1,@PeriodCode))
	and RIGHT(RTRIM(CODE_ROW),3) = '000'
	group by code_row
	
	update @t
	set [name] = (
		select ltrim(rtrim(isnull(rd.str_val,''))) 
		from dbo.report_dinamics as rd 
		where rd.link_sf = @iLink_sf and rd.link_col = @col8_t2 and rd.code_row = t.code_row
	)
	from @t as t

	while exists(select * from @t where code is not null) begin
		select top 1 @nn = nn, @nnp = isnull(nnp,''), @code = isnull(code,''), @name = isnull([name],'') from @t

		IF EXISTS(SELECT * from dbo.RT_GET_RECORDS_RRO(2,@PeriodCode) WHERE [code] = @code)
		BEGIN 
		   SELECT @name = true_name, @nnp = pnum from dbo.RT_GET_RECORDS_RRO(2,@PeriodCode) WHERE [code] = @code
	      UPDATE dbo.report_dinamics 
	      SET str_val = ISNULL(@name, '')
		   where link_sf = @iLink_sf and link_col = @col8_t2 AND SUBSTRING(RTRIM(CODE_ROW)+'         ',8,9) = @code AND ISNULL([Str_Val], '') <> ''

         IF @@ROWCOUNT = 0
            INSERT dbo.[REPORT_DINAMICS] ([Link_SF], [Link_Col], [Code_Row], [Float_Val], [Str_Val])
            SELECT @iLink_sf, @col8_t2, LEFT(@nnp + '       ', 7) +  LEFT(@code + '         ', 9) + '000', 0, ISNULL(@name, '')
         
         
--         TRUNCATE table #report_dinamics
--         
--         INSERT #report_dinamics (link_sf, code_row, link_col, float_val, str_val)
--         SELECT link_sf, left(@nnp + '       ',7) + SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12), link_col, sum(float_val), max(str_val)
--         FROM dbo.report_dinamics
--         where link_sf = @iLink_sf and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12) = @code +'000'
--         GROUP BY  link_sf, left(@nnp + '       ',7) + SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12), link_col
--         
--         DELETE dbo.report_dinamics
--         WHERE link_sf = @iLink_sf and SUBSTRING(RTRIM(CODE_ROW)+'         ',8,12) = @code +'000'
--         
--         INSERT dbo.report_dinamics (link_sf, code_row, link_col, float_val, str_val)
--         SELECT link_sf, code_row, link_col, float_val, str_val
--         FROM #report_dinamics
         
	   END 
	   ELSE BEGIN
   		exec dbo.[RT_RRO_ADD_RO] @nnp,@code,@name,2,@PeriodCode
   	END 

		delete from @t where nn = @nn
	end
	---- конец добавления записи в дерево -----
	-------------------------------------------
	-- добавление НПА в базу из отчётов
	declare @name_npa varchar(8000),
			@type_npa varchar(254),
			@numb_npa varchar(254),
			@dtpr_npa varchar(254),
			@dtvs_npa varchar(254),
			@srkd_npa varchar(254)
	-- для т1 -- РФ
	create table #table1(nn int identity(1,1), name_npa varchar(8000),type_npa varchar(254),numb_npa varchar(254),dtpr_npa varchar(254),dtvs_npa varchar(254),srkd_npa varchar(254),code varchar(50))
--ЗАКОММЕНТРОВАНО ПОТОМУЧТО ДОБАВЛЯТЬ НУЖНО ТОЛЬКО НПА МО
--	insert into #table1 (name_npa,type_npa,numb_npa,dtpr_npa,dtvs_npa,srkd_npa,code)
--	select 
--		rtrim(isnull(rd11.str_val,'')),
--		rtrim(isnull(rd18.str_val,'')),
--		rtrim(isnull(rd19.str_val,'')),
--		rtrim(isnull(rd20.str_val,'')),
--		rtrim(isnull(rd21.str_val,'')),
--		rtrim(isnull(rd22.str_val,'')),
--		rtrim(isnull(rd.code_row,''))
--	from (select distinct code_row from dbo.report_dinamics where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t1)) as rd
--		left join dbo.report_dinamics as rd11 on rd11.link_sf = @iLink_sf and rd.code_row = rd11.code_row and rd11.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 11)
--		left join dbo.report_dinamics as rd18 on rd18.link_sf = @iLink_sf and rd.code_row = rd18.code_row and rd18.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 18)
--		left join dbo.report_dinamics as rd19 on rd19.link_sf = @iLink_sf and rd.code_row = rd19.code_row and rd19.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 19)
--		left join dbo.report_dinamics as rd20 on rd20.link_sf = @iLink_sf and rd.code_row = rd20.code_row and rd20.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 20)
--		left join dbo.report_dinamics as rd21 on rd21.link_sf = @iLink_sf and rd.code_row = rd21.code_row and rd21.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 21)
--		left join dbo.report_dinamics as rd22 on rd22.link_sf = @iLink_sf and rd.code_row = rd22.code_row and rd22.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 22)
--	
--	while exists(select * from #table1 where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0)begin
--		select top 1 
--			@nn = nn, 
--			@name_npa = dbo.RT_RRO_GET_BNAME(name_npa), 
--			@type_npa = type_npa, 
--			@numb_npa = numb_npa,
--			@dtpr_npa = dtpr_npa,
--			@dtvs_npa = dtvs_npa,
--			@srkd_npa = srkd_npa
--		from #table1 
--		where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0
--
--		exec dbo.RT_RRO_ADD_NPA @type_npa,@name_npa,@numb_npa,@dtpr_npa,@dtvs_npa,@srkd_npa,'f'
--
--		delete from #table1 where nn = @nn
--	end
--	delete from #table1 where nn = @nn
--	--------------------------------------
--	-- для т1 -- Субъект РФ
--	insert into #table1 (name_npa,type_npa,numb_npa,dtpr_npa,dtvs_npa,srkd_npa,code)
--	select 
--		rtrim(isnull(rd23.str_val,'')),
--		rtrim(isnull(rd30.str_val,'')),
--		rtrim(isnull(rd31.str_val,'')),
--		rtrim(isnull(rd32.str_val,'')),
--		rtrim(isnull(rd33.str_val,'')),
--		rtrim(isnull(rd34.str_val,'')),
--		rtrim(isnull(rd.code_row,''))
--	from (select distinct code_row from dbo.report_dinamics where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t1)) as rd
--		left join dbo.report_dinamics as rd23 on rd23.link_sf = @iLink_sf and rd.code_row = rd23.code_row and rd23.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 23)
--		left join dbo.report_dinamics as rd30 on rd30.link_sf = @iLink_sf and rd.code_row = rd30.code_row and rd30.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 30)
--		left join dbo.report_dinamics as rd31 on rd31.link_sf = @iLink_sf and rd.code_row = rd31.code_row and rd31.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 31)
--		left join dbo.report_dinamics as rd32 on rd32.link_sf = @iLink_sf and rd.code_row = rd32.code_row and rd32.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 32)
--		left join dbo.report_dinamics as rd33 on rd33.link_sf = @iLink_sf and rd.code_row = rd33.code_row and rd33.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 33)
--		left join dbo.report_dinamics as rd34 on rd34.link_sf = @iLink_sf and rd.code_row = rd34.code_row and rd34.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t1 and Orders = 34)
--	
--	while exists(select * from #table1 where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0)begin
--		select top 1 
--			@nn = nn, 
--			@name_npa = dbo.RT_RRO_GET_BNAME(name_npa), 
--			@type_npa = type_npa, 
--			@numb_npa = numb_npa,
--			@dtpr_npa = dtpr_npa,
--			@dtvs_npa = dtvs_npa,
--			@srkd_npa = srkd_npa
--		from #table1 
--		where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0
--
--		exec dbo.RT_RRO_ADD_NPA @type_npa,@name_npa,@numb_npa,@dtpr_npa,@dtvs_npa,@srkd_npa,'s'
--
--		delete from #table1 where nn = @nn
--	end
--	delete from #table1 where nn = @nn
--	----------------------------------------------------------------------------------------------------------------------
--	-- для т2 -- РФ
--	insert into #table1 (name_npa,type_npa,numb_npa,dtpr_npa,dtvs_npa,srkd_npa,code)
--	select 
--		rtrim(isnull(rd11.str_val,'')),
--		rtrim(isnull(rd18.str_val,'')),
--		rtrim(isnull(rd19.str_val,'')),
--		rtrim(isnull(rd20.str_val,'')),
--		rtrim(isnull(rd21.str_val,'')),
--		rtrim(isnull(rd22.str_val,'')),
--		rtrim(isnull(rd.code_row,''))
--	from (select distinct code_row from dbo.report_dinamics where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2)) as rd
--		left join dbo.report_dinamics as rd11 on rd11.link_sf = @iLink_sf and rd.code_row = rd11.code_row and rd11.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 11)
--		left join dbo.report_dinamics as rd18 on rd18.link_sf = @iLink_sf and rd.code_row = rd18.code_row and rd18.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 18)
--		left join dbo.report_dinamics as rd19 on rd19.link_sf = @iLink_sf and rd.code_row = rd19.code_row and rd19.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 19)
--		left join dbo.report_dinamics as rd20 on rd20.link_sf = @iLink_sf and rd.code_row = rd20.code_row and rd20.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 20)
--		left join dbo.report_dinamics as rd21 on rd21.link_sf = @iLink_sf and rd.code_row = rd21.code_row and rd21.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 21)
--		left join dbo.report_dinamics as rd22 on rd22.link_sf = @iLink_sf and rd.code_row = rd22.code_row and rd22.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 22)
--	
--	while exists(select * from #table1 where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0)begin
--		select top 1 
--			@nn = nn, 
--			@name_npa = dbo.RT_RRO_GET_BNAME(name_npa), 
--			@type_npa = type_npa, 
--			@numb_npa = numb_npa,
--			@dtpr_npa = dtpr_npa,
--			@dtvs_npa = dtvs_npa,
--			@srkd_npa = srkd_npa
--		from #table1 
--		where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0
--
--		exec dbo.RT_RRO_ADD_NPA @type_npa,@name_npa,@numb_npa,@dtpr_npa,@dtvs_npa,@srkd_npa,'f'
--
--		delete from #table1 where nn = @nn
--	end
--	delete from #table1 where nn = @nn
--	--------------------------------------
--	-- для т2 -- Субъект РФ
--	insert into #table1 (name_npa,type_npa,numb_npa,dtpr_npa,dtvs_npa,srkd_npa,code)
--	select 
--		rtrim(isnull(rd23.str_val,'')),
--		rtrim(isnull(rd30.str_val,'')),
--		rtrim(isnull(rd31.str_val,'')),
--		rtrim(isnull(rd32.str_val,'')),
--		rtrim(isnull(rd33.str_val,'')),
--		rtrim(isnull(rd34.str_val,'')),
--		rtrim(isnull(rd.code_row,''))
--	from (select distinct code_row from dbo.report_dinamics where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2)) as rd
--		left join dbo.report_dinamics as rd23 on rd23.link_sf = @iLink_sf and rd.code_row = rd23.code_row and rd23.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 23)
--		left join dbo.report_dinamics as rd30 on rd30.link_sf = @iLink_sf and rd.code_row = rd30.code_row and rd30.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 30)
--		left join dbo.report_dinamics as rd31 on rd31.link_sf = @iLink_sf and rd.code_row = rd31.code_row and rd31.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 31)
--		left join dbo.report_dinamics as rd32 on rd32.link_sf = @iLink_sf and rd.code_row = rd32.code_row and rd32.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 32)
--		left join dbo.report_dinamics as rd33 on rd33.link_sf = @iLink_sf and rd.code_row = rd33.code_row and rd33.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 33)
--		left join dbo.report_dinamics as rd34 on rd34.link_sf = @iLink_sf and rd.code_row = rd34.code_row and rd34.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 34)
--	
--	while exists(select * from #table1 where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0)begin
--		select top 1 
--			@nn = nn, 
--			@name_npa = dbo.RT_RRO_GET_BNAME(name_npa), 
--			@type_npa = type_npa, 
--			@numb_npa = numb_npa,
--			@dtpr_npa = dtpr_npa,
--			@dtvs_npa = dtvs_npa,
--			@srkd_npa = srkd_npa
--		from #table1 
--		where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0
--
--		exec dbo.RT_RRO_ADD_NPA @type_npa,@name_npa,@numb_npa,@dtpr_npa,@dtvs_npa,@srkd_npa,'s'
--
--		delete from #table1 where nn = @nn
--	end
--	delete from #table1 where nn = @nn
--
--	--------------------------------------
--	-- для т2 -- МО
--	insert into #table1 (name_npa,type_npa,numb_npa,dtpr_npa,dtvs_npa,srkd_npa,code)
--	select 
--		rtrim(isnull(rd35.str_val,'')),
--		rtrim(isnull(rd42.str_val,'')),
--		rtrim(isnull(rd43.str_val,'')),
--		rtrim(isnull(rd44.str_val,'')),
--		rtrim(isnull(rd45.str_val,'')),
--		rtrim(isnull(rd46.str_val,'')),
--		rtrim(isnull(rd.code_row,''))
--	from (select distinct code_row from dbo.report_dinamics where link_sf = @iLink_sf and link_col in (select link_col from dbo.report_coloumns where link_table = @link_t2)) as rd
--		left join dbo.report_dinamics as rd35 on rd35.link_sf = @iLink_sf and rd.code_row = rd35.code_row and rd35.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 35)
--		left join dbo.report_dinamics as rd42 on rd42.link_sf = @iLink_sf and rd.code_row = rd42.code_row and rd42.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 42)
--		left join dbo.report_dinamics as rd43 on rd43.link_sf = @iLink_sf and rd.code_row = rd43.code_row and rd43.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 43)
--		left join dbo.report_dinamics as rd44 on rd44.link_sf = @iLink_sf and rd.code_row = rd44.code_row and rd44.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 44)
--		left join dbo.report_dinamics as rd45 on rd45.link_sf = @iLink_sf and rd.code_row = rd45.code_row and rd45.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 45)
--		left join dbo.report_dinamics as rd46 on rd46.link_sf = @iLink_sf and rd.code_row = rd46.code_row and rd46.link_col = (select link_col from dbo.report_coloumns where link_table = @link_t2 and Orders = 46)
--	
--	while exists(select * from #table1 where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0)begin
--		select top 1 
--			@nn = nn, 
--			@name_npa = dbo.RT_RRO_GET_BNAME(name_npa), 
--			@type_npa = type_npa, 
--			@numb_npa = numb_npa,
--			@dtpr_npa = dtpr_npa,
--			@dtvs_npa = dtvs_npa,
--			@srkd_npa = srkd_npa
--		from #table1 
--		where len(isnull(numb_npa,''))>0 and len(isnull(dtpr_npa,''))>0
--
--		exec dbo.RT_RRO_ADD_NPA @type_npa,@name_npa,@numb_npa,@dtpr_npa,@dtvs_npa,@srkd_npa,'l'
--
--		delete from #table1 where nn = @nn
--	end
	delete from #table1 where nn = @nn
	drop table #table1
   DROP TABLE #report_dinamics
GO
grant execute on [dbo].[RT_CHANGE_RRO_PERSPECTIVE] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO

/*
exec RT_CHANGE_RRO_PERSPECTIVE 19054
*/
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_kons_budg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_kons_budg]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_kons_budg]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
	declare @table varchar(100), @RunStr varchar(8000), @vcCode VARCHAR(50), @vcName VARCHAR(100), @i INT, @vcI VARCHAR(10) 

	create table #table (COL1 varchar(200), COL2 varchar(200), COL3 NUMERIC(20,2), COL4 NUMERIC(20,2), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2), COL16 varchar(8000), COL17 varchar(8000), COL18 NUMERIC(20,2), CODE varchar(50))
   CREATE TABLE #res(COL1 varchar(8000), COL2 varchar(8000), COL3 NUMERIC(20,2), COL4 NUMERIC(20,2), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2))
      
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18, CODE from ' + @table
	insert #table (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18, CODE) execute(@RunStr)
   
   INSERT #res (COL1, COL2)
   SELECT DISTINCT COL1, COL2 FROM #table
   
   UPDATE R
   SET COL3 = T.COL3,
      COL4 = T.COL4,
      COL5 = T.COL5,
      COL6 = T.COL6,
      COL7 = T.COL7,
      COL8 = T.COL8,
      COL9 = T.COL9,
      COL10 = T.COL10,
      COL11 = T.COL11,
      COL12 = T.COL12,
      COL13 = T.COL13,
      COL14 = T.COL14,
      COL15 = T.COL15                 
   FROM #RES R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = '9999999999999999'
   
   DECLARE cur CURSOR LOCAL STATIC FOR SELECT DISTINCT COL16, COL17 FROM #table WHERE COL16 <> '9999999999999999' ORDER BY COL16
   
   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcCode, @vcName
   
   SET @i = 1
   SET @vcI = LTRIM(RTRIM(STR(@i)))
   
   WHILE @@FETCH_STATUS = 0 
   BEGIN
      SET @RunStr = 'ALTER TABLE #res ADD COL_C_' + @vcI + ' VARCHAR(100) ALTER TABLE #res ADD COL_N_' + @vcI + ' VARCHAR(100) ALTER TABLE #res ADD COL_S_' + @vcI + ' NUMERIC(20,2)'
      EXECUTE (@RunStr)

      SET @RunStr = 'UPDATE R ' + 
      'SET  COL_C_' + @vcI + ' = ''' + @vcCode + ''', ' +
           'COL_N_' + @vcI + ' = ''' + @vcName + ''' ' + 
      'FROM #Res R'
      EXECUTE (@RunStr)    
      
      SET @RunStr = 'UPDATE R ' + 
      'SET COL_S_' + @vcI + ' = COL18 ' + 
      'FROM #Res R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = ''' + @vcCode +''''
      EXECUTE (@RunStr)     

      SET @i = @i + 1
      SET @vcI = LTRIM(RTRIM(STR(@i)))
      
      FETCH NEXT FROM cur INTO  @vcCode, @vcName
   END

   SELECT * FROM #res

   TRUNCATE TABLE #table
   DEALLOCATE cur
   
   ----------------------------------------------------------
   CREATE TABLE #res1(COL1 varchar(254), COL2 varchar(254), COL3 NUMERIC(20,2), COL4 NUMERIC(20,2), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2))
      
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18,CODE from ' + @table
	insert #table (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18,CODE) execute(@RunStr)
   
   INSERT #res1 (COL1, COL2)
   SELECT DISTINCT RTRIM(COL1), RTRIM(COL2) FROM #table
   
   UPDATE R
   SET COL3 = T.COL3,
      COL4 = T.COL4,
      COL5 = T.COL5,
      COL6 = T.COL6,
      COL7 = T.COL7,
      COL8 = T.COL8,
      COL9 = T.COL9,
      COL10 = T.COL10,
      COL11 = T.COL11,
      COL12 = T.COL12,
      COL13 = T.COL13,
      COL14 = T.COL14,
      COL15 = T.COL15
   FROM #RES1 R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = '9999999999999999'
   
   DECLARE cur CURSOR LOCAL STATIC FOR SELECT DISTINCT COL16, COL17 FROM #table WHERE COL16 <> '9999999999999999' ORDER BY COL16
   
   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcCode, @vcName
   
   SET @i = 1
   SET @vcI = LTRIM(RTRIM(STR(@i)))
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
      SET @RunStr = 'ALTER TABLE #res1 ADD COL_C_' + @vcI + ' VARCHAR(100) ALTER TABLE #res1 ADD COL_N_' + @vcI + ' VARCHAR(100) ALTER TABLE #res1 ADD COL_S_' + @vcI + ' NUMERIC(20,2)'
      EXECUTE (@RunStr)

      SET @RunStr = 'UPDATE R ' + 
      'SET  COL_C_' + @vcI + ' = ''' +RTRIM( @vcCode) + ''', ' +
           'COL_N_' + @vcI + ' = ''' + RTRIM(@vcName) + ''' ' + 
      'FROM #Res1 R'
      EXECUTE (@RunStr)    
      
      SET @RunStr = 'UPDATE R ' + 
      'SET COL_S_' + @vcI + ' = COL18 ' + 
      'FROM #Res1 R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = ''' + @vcCode +''''
      EXECUTE (@RunStr)     

      SET @i = @i + 1
      SET @vcI = LTRIM(RTRIM(STR(@i)))
      
      FETCH NEXT FROM cur INTO  @vcCode, @vcName
   END

    SELECT TOP 10 * FROM #res1

   TRUNCATE TABLE #table
     DEALLOCATE cur
   
   ----------------------------------------------------------
   CREATE TABLE #res2(COL1 varchar(8000), COL2 varchar(8000), COL3 NUMERIC(20,2), COL4 NUMERIC(20,2), COL5 NUMERIC(20,2), COL6 NUMERIC(20,2), COL7 NUMERIC(20,2), COL8 NUMERIC(20,2), COL9 NUMERIC(20,2), COL10 NUMERIC(20,2)
               , COL11 NUMERIC(20,2), COL12 NUMERIC(20,2), COL13 NUMERIC(20,2), COL14 NUMERIC(20,2), COL15 NUMERIC(20,2))
      
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18,CODE from ' + @table
	insert #table (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15,COL16,COL17,COL18,CODE) execute(@RunStr)
   
   INSERT #res2 (COL1, COL2)
   SELECT DISTINCT COL1, COL2 FROM #table
   
   UPDATE R
   SET COL3 = T.COL3,
      COL4 = T.COL4,
      COL5 = T.COL5,
      COL6 = T.COL6,
      COL7 = T.COL7,
      COL8 = T.COL8,
      COL9 = T.COL9,
      COL10 = T.COL10,
      COL11 = T.COL11,
      COL12 = T.COL12,
      COL13 = T.COL13,
      COL14 = T.COL14,
      COL15 = T.COL15                 
   FROM #RES2 R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = '9999999999999999'
   
   DECLARE cur CURSOR LOCAL STATIC FOR SELECT DISTINCT COL16, COL17 FROM #table WHERE COL16 <> '9999999999999999' ORDER BY COL16
   
   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcCode, @vcName
   
   SET @i = 1
   SET @vcI = LTRIM(RTRIM(STR(@i)))
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
      SET @RunStr = 'ALTER TABLE #res2 ADD COL_C_' + @vcI + ' VARCHAR(100) ALTER TABLE #res2 ADD COL_N_' + @vcI + ' VARCHAR(100) ALTER TABLE #res2 ADD COL_S_' + @vcI + ' NUMERIC(20,2)'
      EXECUTE (@RunStr)

      SET @RunStr = 'UPDATE R ' + 
      'SET  COL_C_' + @vcI + ' = ''' + RTRIM(@vcCode) + ''', ' +
           'COL_N_' + @vcI + ' = ''' + RTRIM(@vcName) + ''' ' + 
      'FROM #Res2 R'
      EXECUTE (@RunStr)    
      
      SET @RunStr = 'UPDATE R ' + 
      'SET COL_S_' + @vcI + ' = COL18 ' + 
      'FROM #Res2 R JOIN #table T ON R.COL1 = T.COL1 AND T.COL16 = ''' + @vcCode +''''
      EXECUTE (@RunStr)     

      SET @i = @i + 1
      SET @vcI = LTRIM(RTRIM(STR(@i)))
      
      FETCH NEXT FROM cur INTO  @vcCode, @vcName
   END
   
   SELECT TOP 10 * FROM #res2  
   
   DROP TABLE #table
   DROP TABLE #res
   DROP TABLE #res1
   DROP TABLE #res2
  
       

GO
GRANT ALL ON dbo.[RO_PRINT_kons_budg] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_86n_GET_SEND_FORMS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].RN_86n_GET_SEND_FORMS
GO
/*
© Кейсистемс (Keysystems), 2012
*/
CREATE  PROCEDURE dbo.RN_86n_GET_SEND_FORMS
   @cForm varchar(20) = '(86н)001',
   @dStartDate DATETIME = '20111101'
AS

DECLARE @dDate       DATETIME
       ,@vcDateTime  VARCHAR(30)
       ,@vcDate      VARCHAR(10)
       ,@vcID        VARCHAR(100)
       ,@IDp         UNIQUEIDENTIFIER
       ,@vcModifyDateTime VARCHAR(30)
       ,@vcPositionVersion VARCHAR(10)
       ,@bCancel     BIT
       ,@vcPath      VARCHAR(1000)
       ,@vcINN        VARCHAR(50)
       ,@vcFileName  VARCHAR(8000)
       ,@vcFileBase64 VARCHAR(8000)
       ,@dFileCreateDate DATETIME
       ,@cCodeRegion  VARCHAR(100)
       ,@ppo VARCHAR(100)


-- проверка 
-- пройдемся по всем отчетам 

CREATE TABLE #ORG(LINK_ORG INT, [CLOSE] VARCHAR(10) DEFAULT(''))
INSERT #ORG(LINK_ORG, [CLOSE])
SELECT DISTINCT A.LINK, B.[END] FROM DEPARTMENTS A, R_86n_SEND_ORG B
--WHERE  A.INN = B.INN
WHERE  A.CODE = B.CODE
 
IF NOT EXISTS (SELECT * FROM #ORG)
INSERT #ORG(LINK_ORG, [CLOSE])
SELECT DISTINCT A.LINK, 'НЕТ' FROM DEPARTMENTS A

DECLARE @LF INT
SELECT @LF = LINK_FORM FROM REPORT_FORMS  WHERE code = @cForm  --AND START_DATE = @dStartDate

CREATE TABLE #LSF(LSF INT)
INSERT #LSF (LSF)
SELECT C.Link_saved_form FROM 
(SELECT Link_Organization, Link_Type_Svod,max(dbo.rn_get_date_from_atr(ATR_CODE)) atr FROM REPORT_SAVED_FORMS RSF WHERE LINK_FORM = @LF and del = 0 
	   group by Link_Organization, Link_Type_Svod) B,
(SELECT version,Link_saved_form,dbo.rn_get_date_from_atr(ATR_CODE) atr, RSF.Link_Organization, RSF.Link_Type_Svod
   FROM REPORT_SAVED_FORMS RSF WHERE LINK_FORM = @LF  and del = 0 ) C
INNER JOIN #ORG D ON D.LINK_ORG = C.link_organization   
WHERE B.link_organization = C.link_organization AND B.Link_Type_Svod = C. Link_Type_Svod AND B.atr = C.atr
AND C.version = (
SELECT max(version)  FROM REPORT_SAVED_FORMS D WHERE LINK_FORM = @LF
AND   D.link_organization = C.link_organization AND D.Link_Type_Svod = C. Link_Type_Svod AND dbo.rn_get_date_from_atr(ATR_CODE) = C.atr 
) 

SELECT 
--CASE WHEN ISNULL(F.code_str,'')='Отчет успешно загружен' OR E.[CLOSE] = 'ДА' THEN 0 ELSE 0 END 
   0 as CHECKED,1 as filterfield,  
   0 AS UPD,
      link_saved_form as link,
      RSF.link_saved_form,
      RSF.Link_form,
      RF.code,
      RF.name,
      (case period_Type when 1 then convert(char(4),year(RSF.BEGIN_DATE)) + ' год'
      when 2 then convert(char(1),RSF.period_number) + ' квартал'
      when 4 then convert(char(2),RSF.period_number) + ' месяц'
   end) as period,
      convert(CHAR(10),DD.CODE) as dep_code,
      convert(VARCHAR(100),dbo.GetDepName(RSF.Link_Organization, RSF.begin_date)) as dep_name,
  convert(VARCHAR(10), DD.BUDG) as dep_budg,
      RSF.Version,
      '' as Str_Analit,
      RSF.begin_date,
      RSF.period_type,
      RSF.period_number,
      RSF.link_organization,
      RSF.isUpload,
      RSF.isSvod,
  isnull(RSF.Link_Type_Svod,0) Link_Type_Svod,
 [Type_Svod] = isnull((select Name from KL_BUDG_TYPE D where D.link = RSF.Link_Type_Svod), ''),
      RSF.isChangeAnalit,
  Note = convert(VARCHAR(254),RSF.NOTE),
   RSF.IsRO,
 RSF.IsRightKS,
  RF.Export_Proc,
 RF.IsSvod as Svod_Form,
--255 as rules,
-- RF.RULES,
  RSF.CountSave,
  DateLastEdit = SJ.date,
 WhoLastEdit = CONVERT (VARCHAR(254), (Isnull (ltrim(rtrim(SJ.FIO)), '') + ' ('+ltrim(rtrim(SJ.Login))+') - ' + ltrim(rtrim(SJ.HOSTNAME)))),
  RSF.isExam,
 IsSign = isnull((select max(type_who) from dbo.report_sign S  where S.lsf = RSF.link_saved_form), 0), --(select top 1 'sign' from report_sign where lsf = RSF.link_saved_form),
	left(RF.atributs,250) atributs,
case when RF.atributs<>'' then 
--then left(dbo.rn_get_atr_val(RSF.link_saved_form,0,0),250) 
 isnull(RSF.atr,'') 
else '' end  as atr_val,
  [START_DATE] = CONVERT(CHAR(10),[RF].[START_DATE],104),
   RF.code as form_code,
   date_transfer_web,
   ISNULL(F.code_str,'') AS SEND_STATUS,   
   ISNULL(F.name,'') AS    SEND_DATE,   
   ISNULL(LEFT(F.long_name,100),'') AS  SEND_COUNT_DOC,
   F.add_info AS SEND_PROTOKOL,     
   CAST('' as VARCHAR(8000)) AS SEND_XML,
   CASE WHEN ISNULL(F.code_str,'')='Отчет успешно загружен' THEN 1 
   ELSE 0 END AS SEND_STATUS_NOM,
   E.[CLOSE],
   DD.INN   
  from report_saved_forms RSF (NOLOCK)
   inner join  dbo.Report_Forms RF on RSF.Link_Form = RF.Link_Form  
   left outer join  dictionary_department DD on DD.link = RSF.link_organization
   left outer join  dbo.RO_SF_OWNER SJ on SJ.Link = RSF.link_saved_form
   LEFT JOIN report_kbk F ON  F.code_form = 'spr_info_send_razdel_'+@cForm AND F.code = DD.code AND RSF.atr = F.LONG_NAME
   --INNER join (SELECT distinct link_report_org,link_report_budg FROM dbo.RN_ACCESS_ORG_TABLE() where Access=1) O
  --ON RSF.link_organization=O.link_REPORT_ORG and isnull(RSF.link_type_svod,0)=O.link_REPORT_BUDG
  INNER JOIN #LSF D ON RSF.Link_Saved_Form = D.LSF
  INNER JOIN #ORG E ON RSF.Link_Organization = E.LINK_ORG
     WHERE  del = 0

 
--SELECT  LINK_FORM FROM REPORT_FORMS  WHERE code = '(86н)001'  


GO
GRANT ALL ON dbo.RN_86n_GET_SEND_FORMS TO PUBLIC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_PRINT_RS14_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].RN_PRINT_RS14_NEW
GO

/*
© Кейсистемс (Keysystems), 2011
*/

CREATE PROCEDURE dbo.RN_PRINT_RS14_NEW
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF INT
AS
	create table #table (Itog INT, TableNum INT, CODE varchar(50), COL1 varchar(8000), COL2 varchar(8000), COL3 varchar(8000), COL4 varchar(8000), COL5 varchar(8000), COL6 VARCHAR(8000) DEFAULT(''), COL7 varchar(8000) DEFAULT(''), COL8 varchar(8000) DEFAULT(''), COL9 varchar(8000), COL10 NUMERIC(20,4) DEFAULT(0),
      COL11 NUMERIC(20,4) DEFAULT(0), COL12 NUMERIC(20,4) DEFAULT(0), COL13 NUMERIC(20,4) DEFAULT(0), COL14 NUMERIC(20,4) DEFAULT(0), COL15 NUMERIC(20,4) DEFAULT(0), COL16 NUMERIC(20,4) DEFAULT(0), COL17 NUMERIC(20,4) DEFAULT(0), COL18 NUMERIC(20,4) DEFAULT(0), COL19 NUMERIC(20,4) DEFAULT(0), COL20 NUMERIC(20,4) DEFAULT(0),
      COL21 NUMERIC(20,4) DEFAULT(0), COL22 NUMERIC(20,4) DEFAULT(0), COL23 NUMERIC(20,4) DEFAULT(0), COL24 NUMERIC(20,4) DEFAULT(0), COL25 NUMERIC(20,4) DEFAULT(0), COL26 NUMERIC(20,4) DEFAULT(0), COL27 NUMERIC(20,4) DEFAULT(0), COL28 NUMERIC(20,4) DEFAULT(0), COL29 NUMERIC(20,4) DEFAULT(0), COL30 NUMERIC(20,4) DEFAULT(0),
      COL31 NUMERIC(20,4) DEFAULT(0), COL32 NUMERIC(20,4) DEFAULT(0), COL33 NUMERIC(20,4) DEFAULT(0), COL34 NUMERIC(20,4) DEFAULT(0), COL35 NUMERIC(20,4) DEFAULT(0), COL36 NUMERIC(20,4) DEFAULT(0), COL37 NUMERIC(20,4) DEFAULT(0), COL38 NUMERIC(20,4) DEFAULT(0), COL39 NUMERIC(20,4) DEFAULT(0), COL40 NUMERIC(20,4) DEFAULT(0),
      COL41 NUMERIC(20,4) DEFAULT(0), COL42 NUMERIC(20,4) DEFAULT(0), COL43 NUMERIC(20,4) DEFAULT(0), COL44 NUMERIC(20,4) DEFAULT(0), COL45 NUMERIC(20,4) DEFAULT(0), COL46 NUMERIC(20,4) DEFAULT(0), COL47 NUMERIC(20,4) DEFAULT(0))

     
                        
	CREATE TABLE #all1 (CODE VARCHAR(50), DEL BIT DEFAULT (0), ITOG INT DEFAULT (0), orders int IDENTITY(1,1), COL1 VARCHAR(8000),COL_0_P_1 VARCHAR(8000),COL_1_P_1 VARCHAR(8000),COL_2_P_1 VARCHAR(8000),COL_3_P_1 VARCHAR(8000),COL_4_P_1 VARCHAR(8000))
	CREATE TABLE #all2 (CODE VARCHAR(50), DEL BIT DEFAULT (0), ITOG INT DEFAULT (0), orders int IDENTITY(1,1), COL1 VARCHAR(8000),COL_0_P_1 VARCHAR(8000),COL_1_P_1 VARCHAR(8000),COL_2_P_1 VARCHAR(8000),COL_3_P_1 VARCHAR(8000),COL_4_P_1 VARCHAR(8000))   
	CREATE TABLE #all3 (CODE VARCHAR(50), DEL BIT DEFAULT (0), ITOG INT DEFAULT (0), orders int IDENTITY(1,1), COL1 VARCHAR(8000),COL_0_P_1 VARCHAR(8000),COL_1_P_1 VARCHAR(8000),COL_2_P_1 VARCHAR(8000),COL_3_P_1 VARCHAR(8000),COL_4_P_1 VARCHAR(8000))   
	declare @table varchar(100), @RunStr varchar(8000), @TypeSubv VARCHAR(100), @I INT, @cI VARCHAR(10), @CODE VARCHAR(50), @cI1 VARCHAR(10), @cI2 VARCHAR(10), @tableNum INT, @tableNumOld INT, @CodeOrg VARCHAR(100), @col INT, @ved_name VARCHAR(1000)
         
    DECLARE @colPlan VARCHAR(10), @colFact VARCHAR(10), @itog INT, @cNameTable VARCHAR(1000), @cCodePrint VARCHAR(1000), @currSheet INT, @currCol INT
    SET @currSheet = 1
    SET @currCol = 1  
    SET @i = 1
    WHILE @i <= 3
      BEGIN    
      	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
        set @RunStr = 'SELECT CASE WHEN CODE LIKE ''%8888888888%'' THEN 1 ELSE 0 END, '+str(@i)+', CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9,
                       COL10, COL11, COL12, COL13, COL14, COL15, COL16, COL17, COL18, COL19,
                       COL20, COL21, COL22, COL23, COL24, COL25, COL26, COL27, COL28, COL29,
                       COL30, COL31, COL32, COL33, COL34, COL35, COL36, COL37, COL38, COL39,
                       COL40, COL41, COL42, COL43, COL44, COL45, COL46, COL47
                        from ' + @table + ' drop table ' + @table
                        
        -- print @RunStr                        
      	insert #table execute(@RunStr)
        SET @i = @i + 1 
      END   

   CREATE TABLE #OrgCode (NAME VARCHAR(8000), CODE VARCHAR(50), [COL] INT, UPD INT)
   INSERT #OrgCode (NAME, CODE, [COL])
   SELECT 'Абыйский', '01', 10
   UNION 
   SELECT 'Алданский', '02', 11
   UNION 
   SELECT 'Аллаиховский', '03', 12
   UNION 
   SELECT 'Амгинский', '04', 13
   UNION 
   SELECT 'Анабарский', '05', 14
   UNION 
   SELECT 'Булунский', '06', 15
   UNION 
   SELECT 'Верхневилюйский', '07', 16
   UNION 
   SELECT 'Верхнеколымский', '08', 17
   UNION 
   SELECT 'Верхоянский', '09', 18
   UNION 
   SELECT 'Вилюйский', '10', 19
   UNION 
   SELECT 'Горный', '11', 20
   UNION 
   SELECT 'Жиганский', '12', 21
   UNION 
   SELECT 'Кобяйский', '13', 22
   UNION 
   SELECT 'Ленский', '14', 23
   UNION 
   SELECT 'Мегино-Кангаласский', '15', 24
   UNION 
   SELECT 'Мирнинский', '16', 25
   UNION 
   SELECT 'Момский', '17', 26
   UNION 
   SELECT 'Намский', '18', 27
   UNION 
   SELECT 'Нижнеколымский', '19', 28
   UNION 
   SELECT 'Нерюнгринский', '20', 29
   UNION 
   SELECT 'Нюрбинский', '21', 30
   UNION 
   SELECT 'Оймяконский', '22', 31
   UNION 
   SELECT 'Олекминский', '23', 32
   UNION 
   SELECT 'Оленекский', '24', 33
   UNION 
   SELECT 'Среднеколымский', '25', 34
   UNION 
   SELECT 'Сунтарский', '26', 35
   UNION 
   SELECT 'Таттинский', '27', 36
   UNION 
   SELECT 'Томпонский', '28', 37
   UNION 
   SELECT 'Хангаласский', '29', 38
   UNION 
   SELECT 'Усть-Алданский', '30', 39
   UNION 
   SELECT 'Усть-Майский', '31', 40
   UNION 
   SELECT 'Усть-Янский', '32', 41
   UNION 
   SELECT 'Чурапчинский', '33', 42
   UNION 
   SELECT 'Эвено-Бытантайский', '34', 43
   UNION 
   SELECT 'Якутск', '35', 44
   UNION 
   SELECT 'Жатай', '36', 45
   UNION 
   SELECT 'не распределенная часть', '88', 46
   UNION 
   SELECT 'Всего', '99', 47
   
   UPDATE #OrgCode SET [UPD] = 0

   INSERT #all1 ([CODE],[COL1])
   SELECT CODE, NAME FROM #OrgCode ORDER BY CODE   

   INSERT #all2 ([CODE],[COL1])
   SELECT CODE, NAME FROM #OrgCode ORDER BY CODE   

   INSERT #all3 ([CODE],[COL1])
   SELECT CODE, NAME FROM #OrgCode ORDER BY CODE   
  
   CREATE TABLE #TypeCode (NAME VARCHAR(8000), CODE VARCHAR(50), UPD INT, ORD INT)
   INSERT #TypeCode (NAME, CODE, UPD, ORD)
   SELECT 'Дотации','10', 0, 1
   UNION
   SELECT 'Субсидии','20', 0, 2
   UNION
   SELECT 'Субвенции','30', 0, 3
   UNION
   SELECT 'Иные межбюджетные трансферты','40', 0, 4
   UNION
   SELECT 'Итого','88', 0, 0

 
   -- Если данных по таблице нет, добавим фиктивные строки
   IF NOT EXISTS(SELECT * FROM [#table]  WHERE COL8 = '10')
      INSERT #TABLE ([TableNum], CODE, COL8)
      SELECT 1, '10', '10'
   IF NOT EXISTS(SELECT * FROM [#table]  WHERE COL8 = '20')
      INSERT #TABLE ([TableNum], CODE, COL8)
      SELECT 1, '20', '20'
   IF NOT EXISTS(SELECT * FROM [#table]  WHERE COL8 = '30')
      INSERT #TABLE ([TableNum], CODE, COL8)
      SELECT 1, '30', '30'
   IF NOT EXISTS(SELECT * FROM [#table]  WHERE COL8 = '40')
      INSERT #TABLE ([TableNum], CODE, COL8)
      SELECT 1, '40', '40'

   --выравнивание данных
   INSERT #TABLE([TableNum], CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9)
   SELECT 2, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9
   FROM #TABLE A WHERE NOT EXISTS(SELECT * FROM #table B  WHERE A.CODE = B.CODE AND B.[TableNum] = 2) 
   AND A.[TableNum] = 1

   INSERT #TABLE([TableNum], CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9)
   SELECT 1, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9
   FROM #TABLE A WHERE NOT EXISTS(SELECT * FROM #table B  WHERE A.CODE = B.CODE AND B.[TableNum] = 1) 
   AND A.[TableNum] = 2

   INSERT #TABLE([TableNum], CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9)
   SELECT 3, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9
   FROM #TABLE A WHERE NOT EXISTS(SELECT * FROM #table B  WHERE A.CODE = B.CODE AND B.[TableNum] = 3) 
   AND A.[TableNum] = 1
   

   CREATE TABLE #tableCode (CODE VARCHAR(50), ITOG INT)

   INSERT #tableCode 
   SELECT DISTINCT SUBSTRING(CODE,1,50), ITOG FROM #table

   DECLARE @cSection VARCHAR(10), @cSectionOLD VARCHAR(10)
   SET @I = 2
   SET @tableNumOld = 1
   
   WHILE EXISTS(SELECT TOP 1 * FROM #tableCode)
   BEGIN
      SELECT top 1 @cSection = left(code, 2), @code = CODE, @itog = ITOG FROM #tableCode
      ORDER BY  case when LEFT(CODE,2) = '88' then '00' ELSE LEFT(CODE,2) end ,  ITOG desc, CODE
      
      SELECT @ved_name = RTRIM(ISNULL((SELECt NAME FROM dbo.R_SPR_ADM_2011 S where S.CODE =  SUBSTRING(@code,3,3)),''))
            
      --PRINT @CODE
      
      IF @cSection <> @cSectionOld 
       SET @i = 2
       
      SELECT @tableNum = [ORD] FROM #TypeCode A WHERE A.[CODE] = LEFT(@code,2)

      IF @currCol > 50 AND @currSheet = 1
      begin
         SET @currSheet = 2
         SET @i = 2 
      END 

      IF @currCol > 100 AND @currSheet = 2
      begin
         SET @currSheet = 3
         SET @i = 2 
      END 
            
      set @RunStr = 'ALTER TABLE #all' + LTRIM(STR(@currSheet)) + ' ADD COL_' + LTRIM(STR(@tableNum)) + '_P_' + LTRIM(STR(@i)) + ' varchar(8000)'
/*'ALTER TABLE #ALL ADD COL_' + LTRIM(STR(@tableNum)) + '_F_' + LTRIM(STR(@i)) + ' FLOAT  
ALTER TABLE #ALL ADD COL_' + LTRIM(STR(@tableNum)) + '_O_' + LTRIM(STR(@i)) + ' FLOAT
ALTER TABLE #ALL ADD COL_' + LTRIM(STR(@tableNum)) + '_N_' + LTRIM(STR(@i)) + ' VARCHAR(250) NOT NULL DEFAULT('''')
ALTER TABLE #ALL ADD COL_' + LTRIM(STR(@tableNum)) + '_D_' + LTRIM(STR(@i)) + ' VARCHAR(250) NOT NULL DEFAULT('''')
ALTER TABLE #ALL ADD COL_' + LTRIM(STR(@tableNum)) + '_R_' + LTRIM(STR(@i)) + ' VARCHAR(250) NOT NULL DEFAULT('''')'*/
      --PRINT @RunStr
      --PRINT @tableNum
      --PRINT @i
      --PRINT @code
      EXECUTE(@RunStr)
      SET @currCol = @currCol + 1
      


      SET @cSectionOld  = @cSection
     
      SELECT @cNameTable = 'Всего '+NAME FROM #TypeCode WHERE [ORD] =  @tableNum 

      -- Обновим ячейки выходной таблицы
      WHILE EXISTS(SELECT * FROM #OrgCode WHERE [UPD] = 0) 
         BEGIN
            SELECT TOP 1 @codeOrg = CODE, @Col = COL FROM #OrgCode WHERE UPD = 0
            UPDATE #OrgCode SET UPD = 1 WHERE CODE = @codeOrg 

            set @RunStr = 'UPDATE A
    SET COL_' + LTRIM(STR(@tableNum)) + '_P_' + LTRIM(STR(@i)) + ' = LTRIM(STR(ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 1),0),20,2)) + ''#&'' +
     LTRIM(STR(ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 2),0),20,4)) + ''#&'' + 
     LTRIM(STR(ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 3),0),20,4)) + ''#&'' + ' +      
    CASE WHEN @itog = 1 THEN '''' +@cNameTable +'''' ELSE  '''' + @ved_name + ''' + CHAR(10) +   ISNULL((SELECT MAX(COL1) FROM  #table T WHERE CODE = '''+@code+'''),'''')'  END + ' + ''#&'' + ' +   
    CASE WHEN @itog = 1 THEN '''' + '''' ELSE   + '''Код дохода: '+SUBSTRING(@code,20,20)+'''' END + ' + ''#&'' + ' +
    CASE WHEN @itog = 1 THEN '''' + '''' ELSE   + ''''+
    'Код расхода:'+CHAR(10)+ 
    'Ведомство: '+SUBSTRING(@code,3,3)+CHAR(10)+
    'РЗПР: '+SUBSTRING(@code,6,4)+CHAR(10)+
    'Целевая статья: '+SUBSTRING(@code,10,7)+CHAR(10)+
    'Вид расхода: '+SUBSTRING(@code,17,3)+CHAR(10)+
    'Дополнительная классификация: '+SUBSTRING(@code,40,3)+CHAR(10)+ ''''
    END + '
    FROM #ALL' + LTRIM(STR(@currSheet)) + ' A WHERE CODE= '''+@codeOrg+''''
/*
            set @RunStr = 'UPDATE A
    SET COL_' + LTRIM(STR(@tableNum)) + '_P_' + LTRIM(STR(@i)) + ' = ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 1),0),
    COL_' + LTRIM(STR(@tableNum)) + '_F_' + LTRIM(STR(@i)) + ' = ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 2),0),
    COL_' + LTRIM(STR(@tableNum)) + '_O_' + LTRIM(STR(@i)) + ' = ISNULL((SELECT COL'+LTRIM(STR(@col))+' FROM  #table T WHERE CODE = '''+@code+''' and TableNum = 3),0),    
    COL_' + LTRIM(STR(@tableNum)) + '_N_' + LTRIM(STR(@i)) + ' = '+
    CASE WHEN @itog = 1 THEN '''' +@cNameTable +'''' ELSE   + 'ISNULL((SELECT MAX(COL1) FROM  #table T WHERE CODE = '''+@code+'''),'''')' END + ',  
    COL_' + LTRIM(STR(@tableNum)) + '_D_' + LTRIM(STR(@i)) + ' = '+
    CASE WHEN @itog = 1 THEN '''' + '''' ELSE   + '''Код дохода: '+SUBSTRING(@code,20,20)+'''' END + ',
    COL_' + LTRIM(STR(@tableNum)) + '_R_' + LTRIM(STR(@i)) + ' = '+
    CASE WHEN @itog = 1 THEN '''' + '''' ELSE   + ''''+
    'Код расхода:'+CHAR(10)+ 
    'Ведомство: '+SUBSTRING(@code,3,3)+CHAR(10)+
    'РЗПР: '+SUBSTRING(@code,6,4)+CHAR(10)+
    'Целевая статья: '+SUBSTRING(@code,10,7)+CHAR(10)+
    'Вид расхода: '+SUBSTRING(@code,17,3)+CHAR(10)+ ''''
    END + '
    FROM #ALL A WHERE CODE= '''+@codeOrg+''''
*/
            --PRINT @RunStr
            EXECUTE(@RunStr)
         END   
      SET @i = @i + 1
      UPDATE #OrgCode SET [UPD] = 0
      delete #tableCode WHERE [CODE] = @CODE
   END

	select * from #all1 ORDER BY orders
   IF @currSheet = 1
      select TOP 1 * from #all2 ORDER BY orders
   ELSE 
      select * from #all2 ORDER BY orders

   IF @currSheet < 3
      select TOP 1 * from #all3 ORDER BY orders
   ELSE 
      select * from #all3 ORDER BY orders

	drop table #all1
   drop table #all2
   drop table #all3
GO
GRANT EXECUTE ON dbo.RN_PRINT_RS14_NEW TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_SAVE_REPORT_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_SAVE_REPORT_KBK]
GO

/*
c Кейсистемс (Keysystems), 2006
*/
--сохранение REPORT_KBK
CREATE        PROCEDURE dbo.RN_SAVE_REPORT_KBK
  @iLINK     int  OUTPUT,
  @cCode         varchar (200)='', --код кбк
  @iLink_self   int = NULL,
  @cName         varchar(250)='', --наименование
  @cCode_Form    varchar(250)='',
  @iChildrens  bit=0,
  @cCode_str  varchar(50)='', --код строки
  @property  int =0, --свойства строки
  @add_info varchar(4000)='',  -- Доп информация
  @long_name varchar(4000)='',  -- длинное наименование
	@dBegin_date datetime = NULL,
	@dEnd_date	datetime = NULL,
   @bCheck     BIT = 0,       -- проверка для новых кодов, на то что уже есть в спраовчнике или в федеральном спрвочнике	
   @bSysJurnal BIT = 0        -- записывать в системный журнал    
AS

IF @bCheck = 1 
BEGIN
   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = @cCode_Form AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1100 
   END    

   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = REPLACE(@cCode_Form, '_USER', '') AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1101 
   END    
END    

DECLARE @Date DATETIME , @dOldBeginDate DATETIME , @dOldEndDate DATETIME , @vcOldName VARCHAR(254), @vcOldLongName VARCHAR(8000), @bJastWas bit
-- очищение кэша проверки внутридокументных КС
delete report_control_protokol

set @cCode=RTRIM(@cCode)
set @iLink_self=isnull(@iLink_self,0) 

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT -1 -- Время ожидания разблокировки ресурсов 3 сек.

BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.
  -- Чтобы не было двойных кодов
 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')
   END

 IF (SELECT COUNT(*) 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form ) = 1 and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form
   END

 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') 
   END

SET @bJastWas = 0
   
IF isnull(@iLink, 0) <> 0
BEGIN
   SELECT @dOldBeginDate = begin_date, @dOldEndDate = end_date, @vcOldName = NAME, @vcOldLongName = Long_Name
   FROM dbo.report_kbk
   WHERE link = @iLink 
   
   set @bJastWas = 1

   IF (SELECT NAME FROM dbo.report_kbk WHERE link = @iLink) <> @cName OR  (SELECT LONG_NAME FROM dbo.report_kbk WHERE link = @iLink) <> @long_name
   BEGIN
      SET @Date = CONVERT(DATETIME,CONVERT(VARCHAR(10), GETDATE(), 112), 112)
      IF NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @iLink)
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         SELECT @iLink, '20000101', NAME, rk.[Long_name]
         FROM  dbo.[REPORT_KBK] rk
         WHERE link = @iLink
      END
      UPDATE dbo.[REPORT_KBK_HIST]
      SET NAME = @cName, [LONG_NAME] = @long_name
      WHERE LINK_UP =  @iLink AND [DATE] = @Date 
      IF @@ROWCOUNT = 0
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         VALUES( @iLink, @Date, @cName, @long_name)
      END 
   END
END    
   

   -- Обновление записи (если она существует).
  UPDATE [REPORT_KBK]
  SET   [CODE] =    @cCODE,
        [NAME] =    @cNAME,
        [CODE_FORM]=@cCODE_FORM,
        [CHILDRENS]=@iChildrens,
        [LINK_SELF]=@iLink_Self,
        [CODE_STR]=@cCode_str,
        [property]=@property,
        [add_info]=@add_info,
        [LONG_NAME] =    @LONG_NAME,
		[BEGIN_DATE] = @dBegin_date,
		[END_DATE] = @dEnd_date
  WHERE [LINK] = @iLINK

DECLARE @liRowCount   INT, -- Число обработанных строк.
        @liError      INT  -- Код ошибки.
   -- Сохранение количества обработанных строк и кода ошибки. 
   SELECT @liRowCount = @@ROWCOUNT, 
          @liError    = @@ERROR

   -- Восстановление точки сохранения при ошибке.
  IF @liError <> 0 BEGIN
    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
    RETURN 7 -- Возврат кода ошибки.
  END
 
  IF @liRowCount = 0  
   BEGIN
    INSERT 
      INTO dbo.[REPORT_KBK] ([CODE],[NAME],[LINK_SELF],[CHILDRENS],[CODE_FORM],[CODE_STR],[property],[add_info],long_name, begin_date, end_date)
    VALUES (@cCODE, @cNAME,@iLink_Self,@iChildrens,@cCode_Form,@cCode_Str,@property,@add_info,@long_name, @dBegin_date, @dEnd_date)

      -- Сохранение первичного ключа и кода ошибки. 
    SELECT @iLINK   = @@IDENTITY 
    SELECT @liError = @@ERROR
      -- Восстановление точки сохранения при ошибке.
    IF @liError <> 0
    BEGIN
      ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
      RETURN 7 -- Возврат кода ошибки.
    END
  END

IF @cCode_Form='HEADER'
begin  
  UPDATE REPORT_KBK 
  SET childrens=case when exists(select * from REPORT_KBK A where A.link_self=REPORT_KBK.link) then 0 else 1 end
  WHERE link=@iLink OR link=@iLink_self
  update report_kbk 
  set imageindex=4  
  where code_form='header'
end

EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK

DECLARE @LF INT, @LSF INT 

EXEC dbo.DropTempTable '#t_CodeRow' 
CREATE TABLE #t_CodeRow (Code VARCHAR(50))

if @bJastWas = 1 AND ((isnull(@dBegin_date, '19000101') <> isnull(@dOldBeginDate, '19000101')
    OR ISNULL(case when @dEnd_date > '20200101' THEN '30000101'  ELSE @dEnd_date END , '30000101') <> ISNULL(case when @dOldEnddate > '20200101' THEN '30000101'  ELSE @dOldEnddate END, '30000101')
      OR @vcOldName <> @cName OR @vcOldLongName <> @long_name)
   AND (@cCode_Form LIKE '%_2011_USER%' OR (RTRIM(@cCode_Form) LIKE '%_2011' AND NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = RTRIM(@cCode_Form) + '_USER' AND @cCode = Code))))
BEGIN
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503117M','0503117G','0503127G','0503127M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   SET @LSF = NULL
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503114M','0503114G','0503137G','0503137M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      TRUNCATE TABLE #t_CodeRow
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      IF @cCode_Form LIKE '%ЦСР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
      END
      IF @cCode_Form LIKE '%РЗПР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   SET @LSF = NULL
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503317M_ФК','0503317G_ФК') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      TRUNCATE TABLE #t_CodeRow
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 15,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 15,3) = @cCode
      END
      IF @cCode_Form LIKE '%ЦСР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 8,7) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 8,7) = @cCode
      END
      IF @cCode_Form LIKE '%РЗПР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 4,4) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 4,4) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   
END     

COMMIT TRANSACTION -- Фиксация транзакции.
DECLARE @link_task INT, @vcText VARCHAR(250)

IF @bSysJurnal = 1
BEGIN 
   SELECT @link_task = ui.[LINK_TASK] 
   FROM dbo.[USER_INFO] ui

   SET @vcText = RTRIM(@cCode_Form) + ' редактирование строки ' + @cCode

   EXEC [dbo].[WF_GENERATEEVENT]
      @varKSevent = 'Универсальный справочник',
      @varKSText = @vcText,
      @varKSObject = @link_task,
      @varKSDB_Object = 'report_kbk',
      @varKSLinkObj = @iLINK
END       

RETURN 0 -- Ошибок нет.




GO
GRANT ALL ON dbo.[RN_SAVE_REPORT_KBK] 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.[X_SAVE_DICTIONARY_DEPARTMENT3]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_SAVE_DICTIONARY_DEPARTMENT3]
GO

CREATE       PROCEDURE dbo.X_SAVE_DICTIONARY_DEPARTMENT3

	@varKSparLINK				INT,
	@TFOMS_REG_NUM varchar(15) = '',
	@TFOMS_KT varchar(2) = ''	,
	@varKScEMail varchar(254) = '',
	@intBUH_TYPE_PARM	TINYINT = 0,
	@FSS_KP_P1 INT = NULL, @FSS_KP_P2 INT = NULL, @FSS_KP_P3 INT = NULL, --реквизиты шифра страхователя для ФСС
	@CORP VARCHAR(5) = '',
	@iUchrLink int = null,
	@iIsUsed tinyint = 1
	
AS BEGIN
	
	DECLARE 
		@varKSSQLError	tinyint,
		  @varKStrancount	int,
		  @varKSEventText	varchar(254),
		  @varKSObjLink    int,
		  @varKSRowCount   int,
		@intBUH_TYPE	TINYINT 

	IF @FSS_KP_P1 IS NULL OR @FSS_KP_P1 = 0
		SET @FSS_KP_P1 = (SELECT TOP 1 LINK FROM dbo.SA_4FSS_KATEG_PLAT_P1 WHERE CODE = '071')

	IF @FSS_KP_P2 IS NULL OR @FSS_KP_P2 = 0
		SET @FSS_KP_P2 = (SELECT TOP 1 LINK FROM dbo.SA_4FSS_KATEG_PLAT_P2 WHERE CODE = '00')

	IF @FSS_KP_P3 IS NULL OR @FSS_KP_P3 = 0
		SET @FSS_KP_P3 = (SELECT TOP 1 LINK FROM dbo.SA_4FSS_KATEG_PLAT_P3 WHERE CODE = '00')

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN

	SELECT @intBUH_TYPE = BUH_TYPE FROM dbo.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @intBUH_TYPE_PARM
	SET @intBUH_TYPE = ISNULL (@intBUH_TYPE, 0)

	UPDATE dbo.DEPARTMENTS WITH (ROWLOCK) 
	SET 
		TFOMS_REG_NUM = @TFOMS_REG_NUM,
		TFOMS_KT = @TFOMS_KT,
		EMail = @varKScEMail,
		BUH_TYPE = @intBUH_TYPE,
		FSS_KP_P1 = @FSS_KP_P1,
		FSS_KP_P2 = @FSS_KP_P2,
		FSS_KP_P3 = @FSS_KP_P3,
		CORP = ISNULL(@CORP,''),
		UCHR_LINK = @iUchrLink,
		ISUSED = @iIsUsed
	WHERE LINK = @varKSparLINK
	
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0

END



GO


GRANT EXECUTE ON dbo.[X_SAVE_DICTIONARY_DEPARTMENT3] 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_SAVE_UVED_817_69N') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].BB_SAVE_UVED_817_69N
GO





CREATE     
PROCEDURE dbo.BB_SAVE_UVED_817_69N
	@iLINK		int	OUTPUT,
	@cNUMBER	char(25) = null,
	@dDATE		datetime = null,
	@dDATE_PROV	datetime = null,
	@cComment	varchar(254) = null,
	@iDepLink   INT = null,
	@iAccLink   INT = null,
	@iPDepLink  INT = null,
	@iOsnovLink	INT = null,
	@iPunkt1	INT
	
	


AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKStrancount	int,
		@varKSLinkObj	int,
		@varKS_param	int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	--Проверка рабочего периода
	IF @dDATE_PROV is not null and not exists(Select * from admin_info Where @dDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END


	SELECT @varKSLinkObj = LINK FROM S_OBJECTS WHERE CODE = 'BB_UVED_817_69N'

	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV @iLINK OUTPUT, @cNUMBER, @dDATE, 
											  @varKSLinkObj, @dDATE_PROV, 0, @cComment,0,@iDepLink,@iAccLink

	IF @varKSERROR <> 0
		RETURN @varKSERROR	

	SELECT @varKS_param = LINK FROM S_OBJECTS WHERE CODE = 'BB_UVED_817_69N_PDEP_LINK'
	
	EXEC @varKSERROR = dbo.X_UPDATE_G_PROV_DEPARTMENT @iLINK, @varKS_param, @iPDepLink
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	SELECT @varKS_param = LINK FROM S_OBJECTS WHERE CODE = 'BB_UVED_817_69N_OSN_LINK'
	
	EXEC @varKSERROR = dbo.X_UPDATE_G_PROV_OSNOV @iLINK, @varKS_param, @iOsnovLink
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	SELECT @varKS_param = LINK FROM S_OBJECTS WHERE CODE = 'BB_UVED_817_69N_P1'
	
	EXEC @varKSERROR = dbo.X_UPDATE_G_PROV_VALUE @iLINK, @varKS_param, @iPunkt1
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	--Событие системного журнала
	SET @varKSEventText = 'Уведомление по расчетам между бюджетами(69н)' + ' №' + RTRIM(@cNUMBER) + ' от ' + convert(varchar, @dDATE, 104)
	EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSLinkObj, 'G_PROV', @iLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_EMPL_PHONE_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_EMPL_PHONE_SAVE]

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE	 PROCEDURE [dbo].KU_EMPL_PHONE_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparEMPL_LINK	int,
	@varKSparCODE	varchar(10),
	@varKSparNumber	varchar(15),
	@varKSparADD		varchar(5),
	@varKSparTYPE	tinyint,
	@varKSparEMAIL  varchar(100)
AS
DECLARE @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254), @varKSEventText varchar(254), @varKSObjectLink int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSparEMPL_LINK is null or @varKSparNumber is null or @varKSparNumber=''
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @varKSparEMAIL is null	SET @varKSparEMAIL = ''
	
	IF @varKSparLINK is null OR @varKSparLINK = 0
	BEGIN
		INSERT INTO EMPL_PHONE WITH (ROWLOCK) (EMPL_LINK, CODE, NUMBER, [ADD], TYPE, EMAIL)
			VALUES (@varKSparEMPL_LINK, @varKSparCODE, @varKSparNumber, @varKSparADD, @varKSparTYPE, @varKSparEMAIL)

		SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	ELSE
	BEGIN
		UPDATE EMPL_PHONE SET EMPL_LINK = @varKSparEMPL_LINK, CODE = @varKSparCODE, NUMBER = @varKSparNumber,
				[ADD] = @varKSparADD, TYPE = @varKSparTYPE, EMAIL = @varKSparEMAIL
		WHERE link=@varKSparLINK
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
	SELECT @varKSObjectLink = link FROM s_objects WHERE code='KU_EMPL_PHONE'
	SET @varKSEventText = 'Рабочие телефоны ' + dbo.ku_GetEmplTFIO(@varKSparEMPL_LINK)
	EXECUTE WF_GENERATEEVENT 'Сохранение строки', @varKSEventText, @varKSObjectLink, 'EMPL_PHONE', @varKSparLINK


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0








GO


GRANT EXECUTE ON dbo.[KU_EMPL_PHONE_SAVE] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_ADV63]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_ADV63]

GO

CREATE PROCEDURE dbo.SZV4_PRINT_ADV63(@Link int) 
AS

DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
	@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9), @Month int, @Year int, @date datetime

SELECT 
	@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
	@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP,
	@Month = month_end, @year = year_begin
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
WHERE P.link = @link


Set @date = dbo.ConvertDMY2Date(1,@Month,@Year)
Set @date = dbo.DateEndOfMonth(@date)

DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT4')
Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)


Select 	
	[YEAR] = ISNULL(CASE WHEN year_begin <> 2010 THEN year_begin ELSE NULL END ,0),
	[NGROUP] = S.pachka,
	[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
			+ SUM(case when S.forma = 1 then 1 else 0 end),
	[PERS_CNT] = COUNT(S.orders),
	[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
	[OPT1] = (case when type = 1 then 1 else 0 end),
	[OPT2] = (case when type = 2 then 1 else 0 end),
	[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
	[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
	[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
	[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str+S.SUM_UPLATA_DOLGA_STR)),@ROUND_LEN,@ROUND_TYPE),
	[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
	[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop+S.SUM_UPLATA_DOLGA_NAK)),@ROUND_LEN,@ROUND_TYPE),
	[REG_NOM_PF] = @varKSNOM_PF,
	[DEP_NAME] = @varKSname,
	[OKPO] = @varKSOKPO,
	[INN] = @varKSINN,
	[KPP] = @varKSKPP,
	[CODE] = K.CODE,
	[PER] = ISNULL(CASE WHEN year_begin <> 2010 THEN PER ELSE NULL END ,0),
	[PER10] = ISNULL(CASE WHEN year_begin = 2010 THEN PER ELSE NULL END ,0),
	[TYPE] = P.vid_kor,
	[PER_EDT] = ISNULL(PER_EDT,0),
	[YEAR_EDT] = ISNULL(YEAR_EDT,0),
	DATE_CRT = @date,
	DATE_DOC = [date],
	SZV = MAX(S.forma)
from 
	dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
where
	P.link = @Link
	and P.proverka = 1
group by
	s.pachka, year_begin, [type], vid_kor, [date], K.CODE, PER, PER_EDT, YEAR_EDT
order by
	S.pachka





GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_ADV63] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DP_SAVE_IN_TASK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[DP_SAVE_IN_TASK]

GO
CREATE  PROCEDURE dbo.DP_SAVE_IN_TASK 
    @varKSparLINK	          INT OUTPUT,
    @varKSparLINK_DOC       INT,	
    @varKSparTASK_DATE      DATETIME,
    @varKSparTASK_AUTH      INT = NULL,
    @varKSparTASK_LINK      INT = NULL,
    @varKSparCOMMENT        VARCHAR(1000) = '',
    @varKSparLINK_EXECUTOR  INT = NULL
AS

DECLARE @varKSSQLError      TINYINT,
        @varKStrancount     INT,
        @varKSRowCount      INT,
        @varKSEventLink     INT,
        @varKSObjLink       INT,
        @varKSExecutorLink  INT,
        @varKSObjTASK       INT

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON

BEGIN TRAN
COMMIT TRAN
	

IF @varKSparLINK_DOC IS NULL OR @varKSparLINK_DOC = 0
BEGIN
  ROLLBACK
  RETURN 5
END

IF @varKSparLINK <= 0
  SET @varKSparLINK = NULL

IF @varKSparLINK_EXECUTOR <= 0 
  SET @varKSparLINK_EXECUTOR = NULL

IF EXISTS(SELECT EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK) 
  SELECT @varKSEventLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK
ELSE
  SET @varKSEventLink = NULL

IF EXISTS(SELECT EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK_EXECUTOR)
  SELECT @varKSExecutorLink = EVENT_LINK FROM EVENT_LINKS WHERE LINK = @varKSparLINK_EXECUTOR
ELSE
  SET @varKSExecutorLink = NULL


IF @varKSEventLink IS NULL 
BEGIN
    DECLARE	@varKSUserRef INT
	SELECT @varKSUserRef = USER_REF FROM WHO_IS_WHO WHERE SID = SUSER_SID()
	IF @varKSUserRef IS NULL
		SET @varKSUserRef = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')
    
     INSERT INTO dbo.EVENT_TASK WITH (ROWLOCK) (LINK_DOC,TASK_DATE,TASK_AUTH,TASK_LINK,COMMENT,EVENT_DATE,EVENT_LINK_EMPL) 
     VALUES (@varKSparLINK_DOC, @varKSparTASK_DATE, @varKSparTASK_AUTH, @varKSparTASK_LINK, @varKSparCOMMENT, GETDATE(), @varKSUserRef)
    
     SELECT @varKSSQLError = @@ERROR, @varKSEventLink = SCOPE_IDENTITY()
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END
    
     SELECT @varKSObjTASK = LINK FROM S_OBJECTS WHERE CODE = 'WF_EVENT_TASK'
     SELECT @varKSparLink = LINK FROM EVENT_LINKS WHERE EVENT_LINK = @varKSEventLink AND OBJECT = @varKSObjTASK
    
     IF @varKSExecutorLink IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.EVENT_EXECUTORS_REF WHERE LINK_EXECUTORS = @varKSExecutorLink AND LINK_TASK = @varKSEventLink)
        INSERT INTO dbo.EVENT_EXECUTORS_REF (LINK_EXECUTORS,LINK_TASK)
        VALUES (@varKSExecutorLink,@varKSEventLink) 	
        
       
END
ELSE
BEGIN
     UPDATE dbo.EVENT_TASK WITH (ROWLOCK) 
     SET LINK_DOC = @varKSparLINK_DOC,TASK_DATE = @varKSparTASK_DATE,TASK_AUTH = @varKSparTASK_AUTH,TASK_LINK = @varKSparTASK_LINK,COMMENT = @varKSparCOMMENT
     WHERE LINK = @varKSEventLink
      
     SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
     IF @varKSSQLError <> 0
     BEGIN
          ROLLBACK
          RETURN 7
     END
      
     IF @varKSRowCount = 0
     BEGIN
          ROLLBACK
          RETURN 2
     END
END	

UPDATE dbo.DOCUMENTS
SET ISP = (CASE
   WHEN (((SELECT COUNT(*) FROM dbo.EVENT_EXECUTORS EE WHERE EE.LINK_DOC = D.LINK) > 0) AND
         ((SELECT COUNT(*) FROM dbo.EVENT_EXECUTORS EE WHERE EE.CHECKED = 1 AND EE.ISP = 0 AND EE.LINK_DOC = D.LINK) = 0)) THEN 1
   ELSE 0
  END)
FROM dbo.DOCUMENTS AS D
WHERE D.LINK = @varKSparLINK_DOC

EXECUTE DP_ADD_REC_ACCESS @varKSparLINK_DOC, @varKSparTASK_AUTH

IF NOT ( dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 0
OR NOT EXISTS (SELECT * FROM EMPL WHERE LINK = dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT3')) )
	IF EXISTS (SELECT * FROM dbo.EVENT_REG WHERE LINK_DOC = @varKSparLINK_DOC)	
		AND EXISTS (SELECT * FROM dbo.EOS_JURNAL WHERE INOUT = 0 AND TYPE_M = 1 AND LINK_DOC = @varKSparLINK_DOC)
		and @varKSparLINK_EXECUTOR is NOT NULL
	EXEC dbo.EOS_EXPORT_REPORT @varKSparLINK_DOC        

IF @@TRANCOUNT > @varKStrancount
   COMMIT TRAN

RETURN 0







GO


GRANT EXECUTE ON dbo.[DP_SAVE_IN_TASK] 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_WEB_SELECT_TYPE_FORM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_SELECT_TYPE_FORM]
GO


CREATE   PROCEDURE dbo.RO_WEB_SELECT_TYPE_FORM
	@nLink bigint = 0,
	@cSearch varchar(250) = '',
	@Tree bit = 0
AS
BEGIN

declare @LinkTree int, @Type tinyint, @access bit, @LinkMode int, @LinkGroup int, @pType tinyint, @pNom tinyint

declare @iYear int, @iPeriod int, @bAllPeriod bit,@ddate datetime 
exec RN_GET_VIEW_PERIOD @iYear output , @iPeriod output , @bAllPeriod  output 

set @ddate=convert(datetime,CONVERT(VARCHAR(10), (select enddate from user_info), 112), 112)
--IF @iPeriod>=5 
--	set @ddate=@ddate - 1


if IS_MEMBER('db_owner')=1 or IS_MEMBER('Главный бухгалтер')=1 or isnull(IS_MEMBER('Начальник отдела кадров'),0)=1 or IS_MEMBER('Свод-КС')=1
	set @access = 1
else
	set @access = 0

if @cSearch <> ''
	set @LinkTree = convert(int, @cSearch)
set @Type = isnull((select childrens from dbo.RO_SVOD_TREE where Link = isnull(@LinkTree,0)), 0)

if @nLink = 0
begin
	if @access = 1 -- доступ Распорядителя
	begin
		if @LinkTree = 0 -- режим все отчеты
		begin
			select convert(bigint, 0) as link, 0 as parent, 'report' as code, 'Нельзя создавать отчет в режиме "Все отчеты"' as name, 'FOLDER' as image_id, 0 as hasChildren, '' as obj_code
		end
		else begin
			if @Type = 0
			begin
				select convert(bigint, 2) as link, 0 as parent, 'report' as code, 'Свод' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
--				union
--				select convert(bigint, 5) as link, 0 as parent, 'report' as code, 'Свод из первичных документов' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
--				union
	--			select convert(bigint, 4) as link, 0 as parent, 'report' as code, 'Консолидированный свод' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
	--			union
--				select convert(bigint, 3), 0, 'REPORT_SVOD_REPORT', 'Свод однотипных', 'FOLDER', 0, 'REPORT_SVOD_REPORT'
			end
			else begin
				select convert(bigint, 1) as link, 0 as parent, 'new' as code, 'Новый отчет' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
				union
				select convert(bigint, 3), 0, 'REPORT_SVOD_REPORT', 'Свод однотипных', 'FOLDER', 0, 'REPORT_SVOD_REPORT'
	--			union
	--			select convert(bigint, 4) as link, 0 as parent, 'report' as code, 'Консолидированный свод' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
			end
		end
	end
	else begin
		if @Type = 1
		begin
			select convert(bigint, 1) as link, 0 as parent, 'new' as code, 'Новый отчет' as name, 'FOLDER' as image_id, 1 as hasChildren, '' as obj_code
			union
			select convert(bigint, 3), 0, 'REPORT_SVOD_REPORT', 'Свод однотипных', 'FOLDER', 0, 'REPORT_SVOD_REPORT'
		end
		else begin
			select convert(bigint, 0) as link, 0 as parent, '' as code, 'ошибка: У ВАС НЕТ ПРАВ!' as name, '' as image_id, 0 as hasChildren, '' as obj_code
		end
	end
end
else BEGIN
	set @LinkMode = convert(int, @nLink/4294967296)
	if @LinkMode = 0 -- открываем группы форм!
	begin
			select convert(bigint, link + @nLink * 4294967296) as link, 1 as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 1 as hasChildren, 'RV_FORM_GROUPS' as obj_code
			from report_form_groups RFG1 where  exists(select * from REPORT_FORM_GROUPS_REF B,i_report_forms C where 
			B.link_form_groups=RFG1.link and B.link_form=C.link_form
			and  START_DATE<=@ddate AND ISNULL(END_DATE,'29990101')>=@ddate)
			union all
			select convert(bigint, 4294967296*@nLink), 1 as parent, '_', 'Все формы', 'FOLDER' as image_id, 1 as hasChildren, 'RV_FORM_GROUPS' as obj_code
			order by code
	end 
	else begin
		set @LinkGroup = @nLink -  @LinkMode * 4294967296
		if @LinkMode = 1 --  новый отчет
		BEGIN
        
			select convert(bigint, link_form + @LinkMode * 4294967296) as link, @LinkMode as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, case when charindex('#', isnull(RF1.Object, '')) = 0 then 'REPORT_SVOD' else  LEFT(RF1.Object, case when CHARINDEX(',', RF1.Object) = 0 then CHARINDEX('#', RF1.Object) - 1 else CHARINDEX(',', RF1.Object) - 1 end )  end as obj_code
			from i_report_forms RF1 
			WHERE rules&2 = 2 AND start_date = (select max(start_date) 
												from report_forms RF2
												where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
				AND (link_form in (Select LINK_FORM from report_form_groups_ref WHERE LINK_FORM_GROUPS = @LinkGroup) or @LinkGroup = 0)
			order by code
		end
		if @LinkMode = 2 -- свод
		begin
			select convert(bigint, -(link_form + @LinkMode * 4294967296)) as link, @LinkMode as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, case isnull(atributs,'') when '' then 'REPORT_WEB_SVOD' else 'REPORT_WEB_SVOD_ATR' end as obj_code
			from i_report_forms RF1 
			WHERE isSvod = 1 and rules&2 = 2 AND start_date = (select max(start_date) 
												from report_forms RF2
												where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
				AND (link_form in (Select LINK_FORM from report_form_groups_ref WHERE LINK_FORM_GROUPS = @LinkGroup) or @LinkGroup = 0)
			order by code
		end		
		if @LinkMode = 5 -- свод однотипных
		begin
			select convert(bigint, link_form + @LinkMode * 4294967296) as link, @LinkMode as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, case isnull(atributs,'') when '' then 'REPORT_WEB_SVOD' else 'REPORT_WEB_SVOD_ATR' end as obj_code
			from i_report_forms RF1 
			WHERE isSvod = 1 and rules&2 = 2 AND start_date = (select max(start_date) 
												from report_forms RF2
												where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
				AND (link_form in (Select LINK_FORM from report_form_groups_ref WHERE LINK_FORM_GROUPS = @LinkGroup) or @LinkGroup = 0)
			order by code
		end		

	end
	





/*

		if @nLink = 1
		begin
			select convert(bigint, link + @nLink * 8) as link, 1 as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 1 as hasChildren, 'RV_FORM_GROUPS' as obj_code
			from report_form_groups RFG1 where  exists(select * from REPORT_FORM_GROUPS_REF B,i_report_forms C where 
			B.link_form_groups=RFG1.link and B.link_form=C.link_form
			and  START_DATE<=@ddate AND ISNULL(END_DATE,'29990101')>=@ddate)

			order by code
		end
		if @nLink in  (2,5) 
		begin
			select convert(bigint, link_form + @nLink * 4294967296) as link, 2 as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, 'REPORT_WEB_SVOD' as obj_code
			from i_report_forms RF1 
			WHERE isSvod = 1 and rules&2 = 2 AND start_date = (select max(start_date) 
												from report_forms RF2
												where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
		
			order by code
		end
	if @nLink = 4
	begin
		select convert(bigint, link_form + @nLink * 4294967296) as link, 4 as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, 'REPORT_WEB_SVOD' as obj_code
		from i_report_forms RF1 
		WHERE isKonsolid = 1 and rules&2 = 2 AND start_date = (select max(start_date) 
		                                    from report_forms RF2
		                                    where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
		order by code
	end
	if @nLink between 8 and 4294967296
	begin
		select convert(bigint, link_form + @nLink * 4294967296) as link, @nLink as parent, code, '<B>' + code + '</B> ' + name as name, 'FOLDER' as image_id, 0 as hasChildren, case when charindex('#', isnull(RF1.Object, '')) = 0 then 'REPORT_SVOD' else  LEFT(RF1.Object, CHARINDEX('#', RF1.Object) - 1) end as obj_code
		from i_report_forms RF1 
		WHERE rules&2 = 2 AND start_date = (select max(start_date) 
		                                    from report_forms RF2
		                                    where RF2.code = RF1.code and  RF2.START_DATE<=@ddate AND ISNULL(RF2.END_DATE,'29990101')>=@ddate)
			AND link_form in (Select LINK_FORM from report_form_groups_ref WHERE LINK_FORM_GROUPS = ROUND(@nLink-8,0))
		order by code
	end*/

end



END

GO
GRANT ALL ON dbo.[RO_WEB_SELECT_TYPE_FORM] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_368]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_368]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2010

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_368]
	@iLINK_SAVED_FORM INT,	                  -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @iORDERS INT
SET NOCOUNT ON

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
   SELECT @iORDERS = MIN([A].[ORDERS])
   FROM (
      SELECT [ORDERS],[CODE_INT] = CAST(dbo.[RA_GETWORDNUM]([TXT],1,'|') AS INT)
      FROM #FileExportReport
      WHERE dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],1,'|')) = 1
   ) [A]
   WHERE [A].[CODE_INT] >= 310


   UPDATE #FileExportReport
   SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
   WHERE [ORDERS] = @iORDERS
   
   IF @@ROWCOUNT = 0
   BEGIN
      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
      WHERE [ORDERS] = (SELECT MIN(ORDERS) FROM #FileExportReport WHERE TXT = '#'
                        AND ORDERS > (SELECT MIN(ORDERS) FROM #FileExportReport WHERE TXT = 'ТБ=01'))
   END 
END



GO
GRANT ALL ON dbo.RA_EXPORT_FORM_368 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_kbk where code= 'send'

select * from report_kbk where link_self in (168972,210085)
sp_helptext ra_script_send

select *
FROM dbo.[REPORT_KBK]
WHERE [CODE_FORM] = 'SEND'

exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[XD_DEP_SEARCH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[XD_DEP_SEARCH]
GO


CREATE  PROCEDURE dbo.XD_DEP_SEARCH
	@intGroupLink int,
	@strType varchar(20),
	@strName varchar(254),
	@strNameType varchar(10),
	@strINN		 varchar(12),
	@strCODE	 varchar(10)
AS

IF @strType IS NULL
	SET @strType = ''

IF @strName IS NULL
	SET @strName = ''

SET @strName = REPLACE(REPLACE(@strName,'?','_'),'*','%')

IF @strNameType IS NULL
	SET @strNameType = ''

IF @strINN IS NULL
	SET @strINN = ''

SET @strINN = REPLACE(REPLACE(@strINN,'?','_'),'*','%')

IF @strCODE IS NULL
	SET @strCODE = ''

SET @strCODE = REPLACE(REPLACE(@strCODE,'?','_'),'*','%')

DECLARE @intTypeDep int

SELECT @intTypeDep =  (CASE @strType
WHEN  'Корреспондент' THEN 1
WHEN  'Подведомственная' THEN 2
WHEN  'Физическое лицо' THEN  3
ELSE  -1
END)

SELECT D.LINK,D.CODE,D.NAME,D.FULL_NAME,D.INN,
	[INN_LONG]  	= RTRIM(D.INN) + CASE WHEN D.INN_DOP = '' THEN '' ELSE '/' + D.INN_DOP END,
	[TYPE_NAME] 	=  (SELECT NAME FROM dbo.DICTIONARY_DEPARTMENT_TYPE WHERE NUMBER = D.TYPE),
	D.BUDG,dbo.xd_DepGroups(D.LINK) AS GROUPS, 	
	[DEP_TYPE2_NAME]= 	case D.DEP_TYPE2 when 1 then 'Малое предприятие'
						 when 2 then 'Учреждение УИС'
						 when 3 then 'Организация инвалидов'
						 else 'Прочие' end

FROM dbo.DEPARTMENTS D
WHERE	(@intTypeDep = -1 OR D.TYPE = @intTypeDep)
	AND (@intGroupLink = -1 OR
		 (@intGroupLink = 0 AND NOT EXISTS(SELECT DEP_LINK FROM DEPARTMENT_GROUPS_REF WHERE DEP_LINK = D.LINK))
		 OR (@intGroupLink > 0 AND EXISTS(SELECT DEP_LINK FROM DEPARTMENT_GROUPS_REF WHERE DEP_LINK = D.LINK AND GROUP_LINK = @intGroupLink )))
	AND (@strName = '' OR (@strNameType = 'краткое' AND D.NAME LIKE @strName)
					   OR (@strNameType = 'полное' AND D.FULL_NAME LIKE @strName))
	AND	(@strINN = '' OR D.INN LIKE @strINN)
	AND	(@strCODE = '' OR D.CODE LIKE @strCODE)
	and D.ISUSED = 1



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_SAVE_DOC_OPER_FROM_INVOICE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_SAVE_DOC_OPER_FROM_INVOICE]

GO

/* --- ФОРМИРОВАНИЕ ПРОЧИХ ОПЕРАЦИЙ ИЗ СЧЕТ-ФАКТУРЫ --- */
CREATE PROCEDURE dbo.BK_SAVE_DOC_OPER_FROM_INVOICE
	@parm_intINVOICE	INT,
	@intDEL_OLD		TINYINT = 0
AS
BEGIN
	DECLARE

		@parm_intLINK_DOC	INT,	-- Старый выходной параметр
		@intTO_MZ		INT, 	-- ТО для Материалов
		@intTO_OS		INT, 	-- ТО для ОС
		@intTO_TMC		INT, 	-- ТО для ТМЦ
		@intTO_SERV		INT, 	-- ТО для УСЛУГИ
		@intKIND_DOC		INT, 	-- По умолчанию Вид документа
		@intTYPE_NUMBER		INT, 	-- 0 - номер док-та генерируется, 1 - номер равен номеру СЧФК
		@intOPT_PROV		INT,

		@intOBJ_REF	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		@intLINK_EMPL	INT,
		@intLINK_SUB	INT,
		@intLINK_KBK	INT,
		@strDOC_NUMBER	VARCHAR (25),
		@strINVOICE_NUMBER	VARCHAR (25),
		@dDOC_DATE	DATETIME,
		@intSELLER	INT,
		@intKBK_DOC	INT,
		@intDOG_TYPE	INT,
		@intLINK_OSNOV	INT,
		@intLINK_TO	INT,
		@intERROR	INT,
	--20070412
		@cTYPE_INV	VARCHAR (30),
		@intLINK_MC	INT,
		@cGRID_SOURCE	CHAR (1),

		@SUM		NUMERIC (28,4),
		@SUM_NALOG	NUMERIC (28,4),
		@SUMMA_ALL	NUMERIC (28,4),
		@LINK_EKR	INT,
		@cCODE_EKR	VARCHAR (3),
		@intROWCOUNT	INT,

	/* -- 20070317 -- */
		@cSOURCE	CHAR (1),
		@cSINTH_BY_TO	CHAR (3),
		@cANALIT_BY_TO CHAR (3),
		@intP_EKR	TINYINT,
		@p_KASSA	TINYINT,
		@intKBK_DEFAULT	INT,
		
	/* --- РАБОТА С G_PROV1 --- */
		@intLINK_G1	INT,
		@strNAME_OPER	VARCHAR (254),
		@intORDERS	INT,

	/* --- РАБОТА С G_PROV2 --- */
		@intLINK_G2	INT,
		@intECON_OPER	INT,
		@intSTORNO	INT,
		@strNAME_OPER2	VARCHAR (254),
		@strNAME_OPER21	VARCHAR (254),
		@intLINK_G2_TO	INT,
		@SUMMA_G2	NUMERIC (28,4),
		@QTY		NUMERIC (28,4),
	
	--- РАБОТА С G_PROV_AP --- 
		@intSGU		INT,
		@intACCOUNT	INT,
		@intEKR		INT,
		@intKAU		INT,
		@intKBK		INT,
		@intDB_KR	TINYINT,
		@intAP_DEP	INT,
		@intAP_EMP	INT,
		@intAP_NOMEN	INT,
		@intAP_INV	INT,
		@intAP_TMC	INT,
		@intAP1		INT,
		@intAP2		INT,
		@intAP3		INT,
		@intSUB		INT

/*	-- Аналитика с настроек документа --
		@intSGU_DOC	INT,
		@intACCOUNT_DOC	INT,
		@intEKR_DOC	INT,
		@intKAU_DOC	INT,
		@intDB_KR_DOC	TINYINT,
		@intSUB_DOC	INT,
		@intAP_DEP_DOC	INT,
		@intAP_EMP_DOC	INT,
		@intAP_NOMEN_DOC INT,
		@intAP_INV_DOC	INT,
		@intAP_TMC_DOC	INT,
		@intAP1_DOC	INT,
		@intAP2_DOC	INT,
		@intAP3_DOC	INT
*/
	--- Настройки счет-фактуры ---
	SELECT @intTO_MZ	=	TO_LINK1,
		@intTO_OS	=	TO_LINK2,	-- ТО для ОС
		@intTO_TMC	=	TO_LINK3,	-- ТО для ТМЦ
		@intTO_SERV	=	TO_LINK4,	-- ТО для УСЛУГИ
		@intKIND_DOC	=	KIND_LINK,	-- По умолчанию Вид документа
		@intTYPE_NUMBER	=	TYPE_NUM,	-- 0 - номер док-та генерируется, 1 - номер равен номеру СЧФК
		@intOPT_PROV	=	OPT_PROV
	FROM dbo.DOC_INVOICE_RECIEVED_OPT

	EXEC @intOBJ_REF = dbo.X_GET_OBJ_LINK 'DOC_RECEIVED_LINK_DOC_OPER'

	/* -- ДАННЫЕ ИЗ СЧЕТ ФАКТУРЫ -- */
	SELECT 	@intDEP_LINK	=	G.DEP_LINK,
		@dDOC_DATE	=	G.[DATE],
		@strINVOICE_NUMBER = G.NUMBER,
		@intACC_LINK	=	T1.MAIN_LINK,
		@intSELLER	=	G.SEL_LINK,
		@intLINK_OSNOV	=	G.OSNOV
	FROM dbo.DOCUMENTS_INVOICE_RECEIVED	G 
	INNER JOIN dbo.DICTIONARY_DEPARTMENT T1 ON (T1.LINK = G.DEP_LINK)
	WHERE G.LINK = @parm_intINVOICE

	DECLARE @TAB_AP_DOC TABLE (
		SGU	INT,
		EKR	INT,
		KAU	INT,
		DB_KR	TINYINT,
		KBK	INT,
		SUB	INT,
		AP_DEP	INT,
		AP_EMP	INT,
		AP_NOMEN INT,
		AP_INV	INT,
		AP_TMC	INT,
		AP1	INT,
		AP2	INT,
		AP3	INT)

	INSERT INTO @TAB_AP_DOC
	SELECT SGU,
		AP_EKR,
		AP_KAU,
		DB_KR,
		AP_KBK,
		AP_SUB,
		AP_DEP,
		AP_EMP,
		AP_NOMEN,
		AP_INV,
		AP_TMC,
		AP1,
		AP2,
		AP3
	FROM dbo.BK_UNFOLD_TABLE_AP (@parm_intINVOICE, DEFAULT)

	--- ФОРМИРОВАНИЕ ДОКУМЕНТА --- 
	IF ISNULL (@intOPT_PROV, 0) = 0
	BEGIN
	--- Создание ---
		IF ISNULL (@intTYPE_NUMBER, 0) = 1
			SET @strDOC_NUMBER = @strINVOICE_NUMBER
		ELSE
			EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_OPER', @strDOC_NUMBER output, @intDEP_LINK
		
		SET @intKIND_DOC = (SELECT LINK FROM dbo.DICTIONARY_DOC_TYPES WHERE LINK = @intKIND_DOC)
	
		SET @parm_intLINK_DOC = (SELECT LINK FROM dbo.XK_GetTable_Doc_FOREIGN (@parm_intINVOICE)
						WHERE DOC_CODE = 'DOCUMENTS_OPER')
		EXEC dbo.X_SAVE_DOCUMENTS_OPER @parm_intLINK_DOC OUTPUT, @strDOC_NUMBER, @dDOC_DATE,
			DEFAULT, DEFAULT, DEFAULT, DEFAULT, @intKIND_DOC, @intDEP_LINK, @intACC_LINK
		
		EXEC dbo.X_UPDATE_G_PROV_REF @parm_intINVOICE, @intOBJ_REF, @parm_intLINK_DOC
	END
	ELSE 
		SET @parm_intLINK_DOC = @parm_intINVOICE

	/* --- !!!СОХРАНЯЕМ ПРОВОДКИ!!! --- */
	-- Табличная часть СЧ-Фактуры --
	SELECT TOP 1 @intKBK_DEFAULT = KBK_LINK
	FROM dbo.DEPARTMENT_KBK
	WHERE DEP_LINK = @intDEP_LINK
		AND OSN = CONVERT (BIT, 1)

	IF ISNULL (@intDEL_OLD, 0) = 1
		DELETE FROM dbo.G_PROV1 WHERE LINK_UP = @parm_intLINK_DOC

	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT INV_TYPE,
				INV_LINK,
				QTY,
				SUMMA,
				SUMMA_NDS,
				SUMMA_ALL,
				EKR_LINK,
				EKR_CODE,
				SFIN_CODE
			FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (@parm_intINVOICE) T1

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @cTYPE_INV, @intLINK_MC, @QTY, @SUM, @SUM_NALOG, @SUMMA_ALL,
			@LINK_EKR, @cCODE_EKR, @cGRID_SOURCE

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- !! Определим ЭКР, если нету по типу МЗ !! --
		IF @LINK_EKR IS NULL
			SELECT @LINK_EKR = LINK,
				@cCODE_EKR = CODE
			FROM dbo.KOSGU
			WHERE (@cTYPE_INV = 'BV_NOMENCLATURE' AND CODE = '340')
				OR (@cTYPE_INV = 'INVENTORY_CARD' AND CODE = '310')

		-- !!Определяем какую ТО использовать (от кода ЭКР) и типа МЦ!! --
		SELECT @intLINK_TO = CASE
					WHEN @cCODE_EKR IN ('310', '320', '330')
						AND @cTYPE_INV IN ('BV_NOMENCLATURE', 'INVENTORY_CARD') THEN @intTO_OS
					WHEN @cCODE_EKR IN ('340')
						AND @cTYPE_INV = 'BV_NOMENCLATURE' THEN @intTO_MZ
					WHEN @cTYPE_INV = 'DICTIONARY_TMC' THEN @intTO_TMC
					WHEN @cTYPE_INV = 'DICTIONARY_SERV' THEN @intTO_SERV
				END

		-- Не указана ТО --
		IF @intLINK_TO IS NULL
		BEGIN
			FETCH NEXT FROM #DATA_CURSOR
				INTO @cTYPE_INV, @intLINK_MC, @QTY, @SUM, @SUM_NALOG, @SUMMA_ALL,
					@LINK_EKR, @cCODE_EKR, @cGRID_SOURCE
			CONTINUE
		END

		-- ЗАПИСЬ В G_PROV1 --
		SELECT	@strNAME_OPER = NAME_OPER FROM dbo.G_PROV1 WHERE LINK = @intLINK_TO
		SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS) FROM G_PROV1 WHERE LINK_UP = @parm_intLINK_DOC), 0) + 1
		
		SET @intLINK_G1 = NULL
		EXEC @intERROR = dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @parm_intLINK_DOC, @intLINK_TO,
			@strNAME_OPER, @intORDERS
		IF @intERROR <> 0
			RETURN @intERROR

		IF @intLINK_G1 IS NULL
		BEGIN
			FETCH NEXT FROM #DATA_CURSOR
				INTO @cTYPE_INV, @intLINK_MC, @QTY, @SUM, @SUM_NALOG, @SUMMA_ALL,
					@LINK_EKR, @cCODE_EKR, @cGRID_SOURCE
			CONTINUE
		END

		SET @intAP_NOMEN = CASE WHEN @cTYPE_INV IN ('DICTIONARY_SERV', 'BV_NOMENCLATURE') THEN @intLINK_MC ELSE NULL END
		SET @intAP_INV = CASE WHEN @cTYPE_INV = 'INVENTORY_CARD' THEN @intLINK_MC ELSE NULL END
		SET @intAP_TMC	= CASE WHEN @cTYPE_INV = 'DICTIONARY_TMC' THEN @intLINK_MC ELSE NULL END

		-- ЗАПИСЬ G_PROV2 --
		DECLARE #CURSOR_G2 CURSOR STATIC LOCAL
			FOR SELECT LINK, STORNO, [NAME], ORDERS, ECON_OPER
				FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_TO
	
		OPEN #CURSOR_G2
		FETCH NEXT FROM #CURSOR_G2
			INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @strNAME_OPER2 = (SELECT RTRIM ([NAME]) FROM dbo.XOZ_OPER WHERE LINK = @intECON_OPER)
			SET @strNAME_OPER21 = CASE @cTYPE_INV
							WHEN 'BV_NOMENCLATURE' THEN
								(SELECT '(МЗ.:)'+ RTRIM (CODE) + '-' + RTRIM ([NAME]) FROM dbo.NOMENCLATURE
									WHERE LINK = @intLINK_MC)
							WHEN 'DICTIONARY_SERV' THEN
								(SELECT '(Услуги:)'+ RTRIM (CODE) + '-' + RTRIM ([NAME]) FROM dbo.NOMENCLATURE
									WHERE LINK = @intLINK_MC)
							WHEN 'DICTIONARY_TMC' THEN
								(SELECT '(ТМЦ:)'+ RTRIM (CODE) + '-' + RTRIM ([NAME]) FROM dbo.DICTIONARY_TMC
									WHERE LINK = @intLINK_MC)
							WHEN 'INVENTORY_CARD' THEN
								(SELECT '(ОС:)'+ RTRIM (CODE) + '-' + RTRIM ([NAME]) FROM dbo.INVENTORY
									WHERE LINK = @intLINK_MC)
						END

			SET @strNAME_OPER2 = CONVERT (VARCHAR (254), ISNULL (@strNAME_OPER2, '') + ISNULL (@strNAME_OPER21, ''))

			SET @SUMMA_G2 = ISNULL (@SUMMA_ALL, 0)
			SET @QTY = ISNULL (@QTY, 0)
			SET @intLINK_G2 = NULL
			EXEC @intERROR = dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
						@SUMMA_G2, @QTY, @intSTORNO, @strNAME_OPER2, @intECON_OPER, @intORDERS
			IF @intERROR <> 0
				RETURN @intERROR

			IF @intLINK_G2 IS NULL
			BEGIN
				FETCH NEXT FROM #CURSOR_G2
					INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
				CONTINUE
			END

			-- ЗАПИСЬ G_PROV_AP --
			SET @intDB_KR = 0
			WHILE @intDB_KR < 2
			BEGIN
				-- Аналитика в проводках (ТО) --
				SELECT @intACCOUNT = ACCOUNT,
					@intSGU	= SGU,
					@cSINTH_BY_TO = SA.cSINTH,
					@cANALIT_BY_TO = SA.cANALIT,
					@cSOURCE = ISNULL (@cGRID_SOURCE, SA.cSOURCE),
					@intP_EKR = P_EKR,
					@p_KASSA = p_KASSA,
					@intLINK_KBK = ISNULL (@intKBK_DOC, GAP.KBK),
					@intLINK_EMPL = GAP.EMP,
					@intKAU = GAP.KAU,
					@intLINK_SUB = SUB,
					@intAP1	= ISNULL (@intLINK_OSNOV, AP1),
					@intAP2	= AP2,
					@intAP3	= AP3
				FROM dbo.G_PROV_AP GAP
				INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = GAP.ACCOUNT)
				WHERE LINK_UP = @intLINK_G2_TO
					AND DB_KR = @intDB_KR
	
				-- Аналитика в проводках (документ) --
				SELECT	@intSGU	= ISNULL (SGU, @intSGU),
					@intLINK_KBK = ISNULL (KBK, @intLINK_KBK),
					@intLINK_EMPL = ISNULL (AP_EMP, @intLINK_EMPL),
					@intKAU = ISNULL (KAU, @intKAU),
					@intLINK_SUB = ISNULL (SUB, @intLINK_SUB),
					@intAP1	= ISNULL (AP1, @intLINK_OSNOV),
					@intAP2	= ISNULL (AP2, @intAP2),
					@intAP3	= ISNULL (AP3, @intAP3)
				FROM @TAB_AP_DOC
				WHERE DB_KR = @intDB_KR

				SET @intLINK_KBK = ISNULL (@intLINK_KBK, @intKBK_DEFAULT)

				SELECT @intROWCOUNT = @@ROWCOUNT 
				IF @cSOURCE = ''
					SET @cSOURCE = '1'
	
				IF @intROWCOUNT > 0
				BEGIN
					IF @intP_EKR = 1
						SET @intACCOUNT = (SELECT TOP 1 LINK
									FROM dbo.S_ACCOUNTS
									WHERE cSINTH = @cSINTH_BY_TO
										AND cSOURCE = @cSOURCE
										AND ((@LINK_EKR IS NULL AND cANALIT = @cANALIT_BY_TO)
											OR ANALIT_EKR = @LINK_EKR))
					ELSE
					BEGIN
						IF @cTYPE_INV = 'BV_NOMENCLATURE' AND @cCODE_EKR = '340'
								AND @cSINTH_BY_TO = '105'
							SET @cANALIT_BY_TO = (SELECT TOP 1 SA.cANALIT
										FROM dbo.S_ACCOUNTS SA
										INNER JOIN dbo.GROUP_INV GR ON (GR.ACCOUNT = SA.LINK)
										INNER JOIN dbo.NOMENCLATURE N ON (N.GROUP_INV = GR.LINK)
											AND N.LINK = @intLINK_MC)
	
						IF @cTYPE_INV = 'INVENTORY_CARD'
								AND (@cCODE_EKR = '310' OR @cCODE_EKR = '320' OR @cCODE_EKR = '330')
								AND @cSINTH_BY_TO = '106'
						BEGIN
							SET @cANALIT_BY_TO = (SELECT TOP 1 SA.cANALIT
										FROM dbo.INVENTORY INV
										INNER JOIN dbo.NOMENCLATURE N ON (N.LINK = INV.NOMENCLATURE)
										INNER JOIN dbo.GROUP_INV GR ON (GR.LINK = N.GROUP_INV)										
										INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = GR.ACCOUNT)
										WHERE INV.LINK = @intLINK_MC)

							SET @cANALIT_BY_TO = LEFT (@cANALIT_BY_TO, 1)
								+ CASE
									WHEN @cCODE_EKR = '310' THEN '1'
									WHEN @cCODE_EKR = '320' THEN '2'
									WHEN @cCODE_EKR = '330' THEN '3'
								END
						END

						SET @intACCOUNT = (SELECT TOP 1 link FROM S_ACCOUNTS WHERE cSINTH = @cSINTH_BY_TO
										AND cSOURCE = @cSOURCE
										AND (cANALIT = @cANALIT_BY_TO))
					END
				
					SET @intACCOUNT = dbo.BK_GetDBKTAccount (@intACCOUNT, DEFAULT, DEFAULT, DEFAULT)
					IF @intACCOUNT IS NULL
					BEGIN
						DELETE FROM dbo.G_PROV2 WHERE LINK = @intLINK_G2
						BREAK
					END

					IF @cSINTH_BY_TO = '302'
						SET @intAP_DEP = @intSELLER
					ELSE
						SET @intAP_DEP = @intDEP_LINK
					
					IF @p_KASSA = 1
						SET @intSGU = @LINK_EKR
					ELSE
						IF @intSGU IS NULL
							SELECT TOP 1 @intSGU = T1.LINK_SGU
							FROM dbo.S_ACCOUNTS_SGU T1
							INNER JOIN dbo.KOSGU T2 ON (T2.LINK = T1.LINK_SGU
								AND T2.DB_KR = @intDB_KR)
							WHERE T1.ACCOUNT = @intACCOUNT

					EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP
						@intLINK_G2, @intDB_KR, @intACCOUNT,
						@intLINK_KBK, @LINK_EKR, @intAP_DEP,
						@intLINK_SUB, @intLINK_EMPL, @intAP_NOMEN, @intAP_INV,
						@intKAU, @intACC_LINK, 
						@intAP_TMC, @dDOC_DATE,
						@intAP1, @intAP2, @intAP3, @intSGU

					IF @intERROR <> 0
						RETURN @intERROR
				END	-- @intROWCOUNT > 0
				SET @intDB_KR = @intDB_KR + 1
			END	-- @intDB_KR < 2

			FETCH NEXT FROM #CURSOR_G2
				INTO @intLINK_G2_TO, @intSTORNO, @strNAME_OPER2, @intORDERS, @intECON_OPER
		END	-- #CURSOR_G2

		CLOSE #CURSOR_G2
		DEALLOCATE #CURSOR_G2
		
		IF NOT EXISTS (SELECT * FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_G1)
			DELETE FROM dbo.G_PROV1 WHERE LINK = @intLINK_G1

		FETCH NEXT FROM #DATA_CURSOR
			INTO @cTYPE_INV, @intLINK_MC, @QTY, @SUM, @SUM_NALOG, @SUMMA_ALL,
				@LINK_EKR, @cCODE_EKR, @cGRID_SOURCE
	END	-- #DATA_CURSOR

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	UPDATE dbo.G_PROV SET SUMMA = ISNULL(dbo.CalcDocSumma(LINK), 0)
	WHERE LINK = @parm_intLINK_DOC

RETURN 0

END



GO


GRANT EXECUTE ON dbo.[BK_SAVE_DOC_OPER_FROM_INVOICE] 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].[BV_GET_DEPRECIATION_ALIAS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_GET_DEPRECIATION_ALIAS]
GO


/*
© Кейсистемс (Keysystems), 2007
20081113 КлимченкоМВ: Добавлен расчет амортизации с учетом настроек на начисление 100%
*/



CREATE	PROCEDURE dbo.BV_GET_DEPRECIATION_ALIAS
	@varKSdWorkDate DATETIME = NULL,
	@varKSnFlagAllDepre INT = 0,
	@varKSnFlagDepreMP	INT = 0,
	@varKSnDepLink INT = NULL
AS
BEGIN

	DECLARE /*
@SUM_MIN	NUMERIC (23,2),
			@SUM_MAX	NUMERIC (23,2),
*/			@intMODE_148N	INT,
			@intKAZNA_CALC	INT,
		@dDOC_DATE	DATETIME

	IF @varKSdWorkDate is NULL
		SET @varKSdWorkDate = (SELECT WORKDATE FROM dbo.USER_INFO)

	SET @dDOC_DATE = @varKSdWorkDate
	
	SET @varKSdWorkDate = DATEADD (DAY, 1, @varKSdWorkDate)

	SELECT @intMODE_148N = dbo.XK_GET_NASTR_INT ('XK_CONV_SA_148N')
	SELECT @intMODE_148N = ISNULL (@intMODE_148N, 0)

	SELECT @intKAZNA_CALC = dbo.XK_GET_NASTR_INT ('DOC_DEPRE_OS_OPT_KAZNA_CALC')
	SELECT @intKAZNA_CALC = ISNULL (@intKAZNA_CALC, 0)

	DECLARE @TMP_TABLE1 TABLE
		(
		[ACC_LINK] [INT],
		[ACC_CODE] [VARCHAR] (13), 
		[ACC_NAME] [VARCHAR] (254),
		[INV_LINK] [INT],
		[INV_NAME] [VARCHAR] (254),
		[INV_CODE]  [VARCHAR] (20),
		[GRP_CODE]  [VARCHAR] (10),
		[SOU_LINK]  [INT],
		[SOU_CODE] [CHAR] (1),
		[SOU_NAME]  [VARCHAR] (254),
		[BALANCE]	[NUMERIC] (20,2),
		[DEPRE_SUM]	[NUMERIC] (20,2),
		[LAST_COST] [NUMERIC] (20,2),
		[QTY] [NUMERIC] (20,2),
		[DEPRE_RATE] [NUMERIC] (20,2),
		[PER_USED] [SMALLINT],
		[QTY_MONTHS] [TINYINT],
		[SUMMA_RATE] [NUMERIC] (20,2),
		[DEPRE_SUM_A] [NUMERIC] (20,2),
		[LAST_COST_A] [NUMERIC] (20,2),
		[DEPRE_CODE] [VARCHAR] (13),
		[KBK] [INT],
		[EKR] [INT],
		[DEP] [INT],
		[SUB] [INT],
		[EMP] [INT],
		[NOMEN] [INT],
		[KAU] [INT],
		[DEP_ACC] [INT],
		[TMC] [INT],
		[INDATE] [DATETIME],
		[SGU] [INT],
		[AP1] [INT],
		[AP2] [INT],
		[AP3] [INT],
		[NOTICE] [VARCHAR] (254)
		)

	DECLARE @DEPRE_TABLE TABLE
		(
		[DEPRE_SUM] [NUMERIC] (20,2),
		[INV] [INT]
		)
	INSERT INTO @DEPRE_TABLE
	SELECT SUM(ART.K_SUMMA), ART.INV
	FROM dbo.ARestTableByConditions(@varKSdWorkDate, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
		, dbo.S_ACCOUNTS SA
	WHERE ART.ACCOUNT = SA.LINK AND SA.cSinth = '104' AND (@varKSnDepLink IS NULL OR ART.DEP_LINK = @varKSnDepLink)
	GROUP BY ART.INV

	INSERT INTO @TMP_TABLE1
	SELECT	[ACC_LINK] = SA2.LINK,		-- Это то, что в итоге попадет в поле Account, а там нам важнее знать линк 104-го счета, а не 101-го
		[ACC_CODE] = SA1.CODE,
		[ACC_NAME] = SA1.NAME,
		[INV_LINK] = ART.INV,
		[INV_NAME] = INV.NAME,
		[INV_CODE] = INV.CODE,
		[GRP_CODE] = (SELECT GI.CODE FROM NOMENCLATURE N, GROUP_INV GI WHERE N.LINK = INV.NOMENCLATURE AND GI.LINK = N.GROUP_INV),
		[SOU_LINK] = (SELECT D.LINK FROM S_ACCOUNTS SA, DICTIONARY_FINANCE_SOURCE D WHERE SA.LINK = ART.ACCOUNT AND SA.cSource = D.CODE),
		[SOU_CODE] = (SELECT SA.cSource FROM S_ACCOUNTS SA WHERE SA.LINK = ART.ACCOUNT),
		[SOU_NAME] = (SELECT D.NAME FROM S_ACCOUNTS SA, DICTIONARY_FINANCE_SOURCE D WHERE SA.LINK = ART.ACCOUNT AND SA.cSource = D.CODE),
		[BALANCE] = ISNULL(ART.D_SUMMA,0),
		[DEPRE_SUM] = ISNULL(DT.DEPRE_SUM,0), --ISNULL(dbo.RestOSDepreByDate(DEFAULT, ART.INV, @varKSdWorkDate),0),
		[LAST_COST] = ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0),
		[QTY] = CONVERT(NUMERIC(13,3), ISNULL(ART.D_QUANTITY,0)),
--		[DEPRE_RATE] = CASE WHEN (ASS.WEAR_OS IS NULL OR ASS.WEAR_OS <= 0) AND (ASS.PERIOD_USED IS NOT NULL AND ASS.PERIOD_USED > 0) THEN CONVERT(NUMERIC(5,2),100 / ISNULL(ASS.PERIOD_USED,0)) ELSE ISNULL(AGW.DEPRE_RATE,0) END,
		[DEPRE_RATE] = DNT.DEPRE_RATE,
		[PER_USED] = ISNULL(DNT.PER_USED,1),
		[QTY_MONTHS] = CONVERT(TINYINT,1),
--		[SUMMA_RATE] = ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),0),
--		[DEPRE_SUM_A] = (ISNULL(DT.DEPRE_SUM,0) + ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),0)),
--		[LAST_COST_A] = ((ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0)) - ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),0)),
		[SUMMA_RATE] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2)	-- По коэффициентам
					ELSE ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2) END 		-- По срокам полезного использования
					ELSE DNT.SUMMA_RATE END, 						-- По остаточной стоимости
		[DEPRE_SUM_A] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN (ISNULL(DT.DEPRE_SUM,0) + ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2))	-- По коэффициентам
					ELSE (ISNULL(DT.DEPRE_SUM,0) + ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2)) END 			-- По срокам полезного использования
					ELSE (ISNULL(DT.DEPRE_SUM,0) + DNT.SUMMA_RATE) END, 							-- По остаточной стоимости
		[LAST_COST_A] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2))	-- По коэффициентам
					ELSE (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2)) END 			-- По срокам полезного использования
					ELSE (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - DNT.SUMMA_RATE) END, 							-- По остаточной стоимости
		[DEPRE_CODE] = SA2.CODE,
		ART.KBK,
		ART.EKR,
		ART.DEP,
		ART.SUB,
		ART.EMP,
		ART.NOMEN,
		ART.KAU,
		ART.DEP_ACC,
		ART.TMC,
		ART.INDATE,
		ART.SGU,
		ART.AP1,
		ART.AP2,
		ART.AP3,

		[NOTICE] = Null -- CONVERT(VARCHAR(254),'')
		
	FROM dbo.ARestGroupedTableByConditions(@varKSdWorkDate, DEFAULT, 0xFFBFF, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
	INNER JOIN dbo.INVENTORY INV ON (INV.LINK = ART.INV)
	INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)
	INNER JOIN dbo.ASSETS ASS ON (ART.INV IS NOT NULL AND ASS.LINK_UP = ART.INV)
	INNER JOIN dbo.GROUP_INV GR ON (GR.LINK = NOMEN.GROUP_INV)
	LEFT JOIN dbo.S_ACCOUNTS AM ON (AM.LINK = GR.ACCOUNT_AM)
	INNER JOIN dbo.BK_GetInvAmortInMonth (@dDOC_DATE, @varKSnDepLink) A_LIST ON (A_LIST.INV = INV.LINK)
	LEFT OUTER JOIN dbo.BK_GetNormDepreTableByOS_M(DEFAULT) DNT ON (DNT.INV = ART.INV)
	LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = ART.ACCOUNT)
	LEFT OUTER JOIN dbo.S_ACCOUNTS SA2 ON (SA2.cSource = SA1.cSource
		AND SA2.cSinth = '104'
		AND SA2.cANALIT = AM.cANALIT
		AND (SA2.cUser = SA1.cUser OR SA2.cUser = '' AND dbo.AccountsHasNoChild (SA2.LINK) = 1))
	LEFT JOIN  @DEPRE_TABLE DT ON (DT.INV = ART.INV)
	INNER JOIN dbo.BK_AMORT_FULL_CALC_PERIOD AFCP ON (ASS.DATE_BEGIN BETWEEN AFCP.DATE_BEGIN AND AFCP.DATE_END)
	WHERE ART.INV IS NOT NULL
		AND (WEAR_FLAG = 1 OR WEAR_FLAG = 2)
		AND (@varKSnDepLink IS NULL OR ART.DEP_LINK = @varKSnDepLink)
		AND (SA1.cSinth LIKE '10[1-2]'
			OR (@intKAZNA_CALC = 1 AND SA1.cSinth = '108'))
		AND (ART.D_SUMMA <> 0 or ART.K_SUMMA <> 0)

		AND ART.D_SUMMA IS NOT NULL 
		AND (
		@varKSnFlagDepreMP = 0
			AND ((ART.D_QUANTITY <> 0 AND ART.D_SUMMA > AFCP.SUM_MAX * ISNULL(ART.D_QUANTITY,1))
				OR (ART.D_QUANTITY = 0 AND ART.D_SUMMA > AFCP.SUM_MAX))
		 OR  @varKSnFlagDepreMP = 1 AND ISNULL(DT.DEPRE_SUM,0) < ART.D_SUMMA AND 
						(
			(ART.D_QUANTITY <> 0  AND ART.D_SUMMA > AFCP.SUM_MIN * ISNULL(ART.D_QUANTITY,1)) 
			OR (ART.D_QUANTITY = 0  AND ART.D_SUMMA > AFCP.SUM_MIN))
			)
	AND ISNULL(YEAR(ASS.DATE_BEGIN),0) > 0	-- Проверка - дата ввода в эксплуатацию не NULL

	AND (ISNULL(YEAR(ASS.DATE_BEGIN),0) < YEAR(@dDOC_DATE)
		OR (WEAR_FLAG <> 2 AND ISNULL(YEAR(ASS.DATE_BEGIN),0) = YEAR(@dDOC_DATE)
			AND ISNULL(MONTH(ASS.DATE_BEGIN),0) < MONTH(@dDOC_DATE))
		OR (WEAR_FLAG = 2 AND ASS.DATE_BEGIN <= @dDOC_DATE))
	ORDER BY ACC_CODE

/*
select @varKSdWorkDate, * from @TMP_TABLE1

select @varKSdWorkDate, date_begin, * from assets
*/
	--- Библиотечный фонд ---
	INSERT INTO @TMP_TABLE1 
	SELECT	[ACC_LINK] = SA2.LINK,		-- Это то, что в итоге попадет в поле Account, а там нам важнее знать линк 104-го счета, а не 101-го
		[ACC_CODE] = SA1.CODE,
		[ACC_NAME] = SA1.NAME,
		[INV_LINK] = ART.INV,
		[INV_NAME] = INV.NAME,
		[INV_CODE] = INV.CODE,
		[GRP_CODE] = (SELECT GI.CODE FROM NOMENCLATURE N, GROUP_INV GI WHERE N.LINK = INV.NOMENCLATURE AND GI.LINK = N.GROUP_INV),
		[SOU_LINK] = (SELECT D.LINK FROM S_ACCOUNTS SA, DICTIONARY_FINANCE_SOURCE D WHERE SA.LINK = ART.ACCOUNT AND SA.cSource = D.CODE),
		[SOU_CODE] = (SELECT SA.cSource FROM S_ACCOUNTS SA WHERE SA.LINK = ART.ACCOUNT),
		[SOU_NAME] = (SELECT D.NAME FROM S_ACCOUNTS SA, DICTIONARY_FINANCE_SOURCE D WHERE SA.LINK = ART.ACCOUNT AND SA.cSource = D.CODE),
		[BALANCE] = ISNULL(ART.D_SUMMA,0),
		[DEPRE_SUM] = ISNULL(DT.DEPRE_SUM,0), --ISNULL(dbo.RestOSDepreByDate(DEFAULT, ART.INV, @varKSdWorkDate),0),
		[LAST_COST] = ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0),
		[QTY] = CONVERT(NUMERIC(13,3), ISNULL(ART.D_QUANTITY,0)),
		[DEPRE_RATE] = DNT.DEPRE_RATE,
		[PER_USED] = ISNULL(DNT.PER_USED,1),
		[QTY_MONTHS] = CONVERT(TINYINT,1),
		[SUMMA_RATE] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2)	-- По коэффициентам
					ELSE ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2) END 		-- По срокам полезного использования
					ELSE DNT.SUMMA_RATE END, 						-- По остаточной стоимости
		[DEPRE_SUM_A] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN (ISNULL(DT.DEPRE_SUM,0) + ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2))	-- По коэффициентам
					ELSE (ISNULL(DT.DEPRE_SUM,0) + ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2)) END 			-- По срокам полезного использования
					ELSE (ISNULL(DT.DEPRE_SUM,0) + DNT.SUMMA_RATE) END, 							-- По остаточной стоимости
		[LAST_COST_A] = CASE WHEN DNT.DEPRE_DATE_CALC IS NULL 
				THEN CASE WHEN ISNULL(DNT.PER_USED,0) = 0 
					THEN (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - ROUND((ISNULL(ART.D_SUMMA,0) * ISNULL(DNT.DEPRE_RATE,0) / 100),2))	-- По коэффициентам
					ELSE (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - ROUND((ISNULL(ART.D_SUMMA,0) / DNT.PER_USED) ,2)) END 			-- По срокам полезного использования
					ELSE (ISNULL(ART.D_SUMMA,0) - ISNULL(DT.DEPRE_SUM,0) - DNT.SUMMA_RATE) END, 							-- По остаточной стоимости
		[DEPRE_CODE] = SA2.CODE,
		ART.KBK,
		ART.EKR,
		ART.DEP,
		ART.SUB,
		ART.EMP,
		ART.NOMEN,
		ART.KAU,
		ART.DEP_ACC,
		ART.TMC,
		ART.INDATE,
		ART.SGU,
		ART.AP1,
		ART.AP2,
		ART.AP3,
		[NOTICE] = Null -- CONVERT(VARCHAR(254),'')
		
	FROM dbo.ARestGroupedTableByConditions(@varKSdWorkDate, DEFAULT, 0xFFBFF, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
	INNER JOIN dbo.INVENTORY INV ON (ART.INV IS NOT NULL AND INV.LINK = ART.INV)
	INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)
	INNER JOIN dbo.ASSETS ASS ON (ART.INV IS NOT NULL AND ASS.LINK_UP = ART.INV)
	INNER JOIN dbo.GROUP_INV GR ON (GR.LINK = NOMEN.GROUP_INV)
	LEFT JOIN dbo.S_ACCOUNTS AM ON (AM.LINK = GR.ACCOUNT_AM)
	INNER JOIN dbo.BK_GetInvAmortInMonth (@dDOC_DATE, @varKSnDepLink) A_LIST ON (A_LIST.INV = INV.LINK)
	LEFT OUTER JOIN dbo.BK_GetNormDepreTableByOS_M(DEFAULT) DNT ON (DNT.INV = ART.INV)
	LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = ART.ACCOUNT)
	LEFT OUTER JOIN dbo.S_ACCOUNTS SA2 ON (SA2.cSource = SA1.cSource AND SA2.cSinth = '104' 
		AND (SA2.cAnalit = AM.cAnalit)
		AND (SA2.cUser = SA1.cUser OR SA2.cUser = ''
		AND dbo.AccountsHasNoChild (SA2.LINK) = 1))
	LEFT JOIN  @DEPRE_TABLE DT ON (DT.INV = ART.INV)
	WHERE ART.INV IS NOT NULL
		AND (WEAR_FLAG = 1 OR WEAR_FLAG = 2)
		AND (@varKSnDepLink IS NULL OR ART.DEP_LINK = @varKSnDepLink)
		AND ((SA1.cSinth = '101' AND SA1.cAnalit LIKE '_7')
		AND (ART.D_SUMMA <> 0 OR ART.K_SUMMA <> 0)
		AND ART.D_SUMMA IS NOT NULL 
		AND (ISNULL(DT.DEPRE_SUM,0) < ART.D_SUMMA
			 AND (ART.D_QUANTITY <> 0 AND ART.D_SUMMA <= 3000 * ISNULL(ART.D_QUANTITY,1)) 
			OR (ART.D_QUANTITY = 0  AND ART.D_SUMMA <= 3000))
			)
	ORDER BY ACC_CODE

-- select @varKSdWorkDate, * from @TMP_TABLE1

	DECLARE @TMP_TABLE2 TABLE
		(
		[ACCOUNT] [INT],
		[ACC_CODE] [VARCHAR] (13), 
		[ACC_NAME] [VARCHAR] (254),
		[INV_LINK] [INT],
		[INV_NAME] [VARCHAR] (254),
		[INV_CODE]  [VARCHAR] (20),
		[GRP_CODE]  [VARCHAR] (10),
		[SOU_LINK]  [INT],
		[SOU_CODE] [CHAR] (1),
		[SOU_NAME]  [VARCHAR] (254),
		[BALANCE]	[NUMERIC] (20,2),
		[DEPRE_SUM]	[NUMERIC] (20,2),
		[LAST_COST] [NUMERIC] (20,2),
		[QTY] [NUMERIC] (20,2),
		[DEPRE_RATE] [NUMERIC] (20,2),
		[PER_USED] [SMALLINT],
		[QTY_MONTHS] [TINYINT],
		[SUMMA_RATE] [NUMERIC] (20,2),
		[DEPRE_SUM_A] [NUMERIC] (20,2),
		[LAST_COST_A] [NUMERIC] (20,2),
		[DEPRE_CODE] [VARCHAR] (13),
		[KBK] [INT],
		[EKR] [INT],
		[DEP] [INT],
		[SUB] [INT],
		[EMP] [INT],
		[NOMEN] [INT],
		[KAU] [INT],
		[DEP_ACC] [INT],
		[TMC] [INT],
		[INDATE] [DATETIME],
		[SGU] [INT],
		[AP1] [INT],
		[AP2] [INT],
		[AP3] [INT],
		[NOTICE] [VARCHAR] (254)
		)

	INSERT INTO @TMP_TABLE2
	SELECT	ACC_LINK, ACC_CODE, ACC_NAME, INV_LINK, INV_NAME, INV_CODE, GRP_CODE, SOU_LINK, SOU_CODE, SOU_NAME, 
		SUM(BALANCE) AS BALANCE, SUM(DEPRE_SUM) AS DEPRE_SUM, SUM(LAST_COST) AS LAST_COST, SUM(QTY) AS QTY, 
		DEPRE_RATE, PER_USED, QTY_MONTHS, SUM(SUMMA_RATE) AS SUMMA_RATE,
		SUM(DEPRE_SUM_A) AS DEPRE_SUM_A, SUM(LAST_COST_A) AS LAST_COST_A, DEPRE_CODE,
		KBK, EKR, DEP, SUB, EMP, NOMEN, KAU, DEP_ACC, TMC, INDATE, SGU, AP1, AP2, AP3, NOTICE
	FROM @TMP_TABLE1
	GROUP BY ACC_LINK, ACC_CODE, ACC_NAME, INV_LINK, INV_NAME, INV_CODE, GRP_CODE,
		SOU_LINK, SOU_CODE, SOU_NAME, QTY_MONTHS, DEPRE_RATE, PER_USED, DEPRE_CODE,
		KBK, EKR, DEP, SUB, EMP, NOMEN, KAU, DEP_ACC, TMC, INDATE, SGU, AP1, AP2, AP3, NOTICE

	UPDATE 	@TMP_TABLE2
	SET	QTY = CASE WHEN QTY = 0 THEN 1 ELSE QTY END,
		SUMMA_RATE = CASE WHEN (SUMMA_RATE + DEPRE_SUM) > BALANCE
				THEN (ISNULL(BALANCE,0) - ISNULL(DEPRE_SUM,0))
				ELSE SUMMA_RATE END,
		DEPRE_SUM_A = CASE WHEN (SUMMA_RATE + DEPRE_SUM) > BALANCE
				THEN ISNULL(BALANCE,0)
				ELSE DEPRE_SUM + SUMMA_RATE END,
		LAST_COST_A = CASE WHEN (SUMMA_RATE + DEPRE_SUM) > BALANCE
				THEN 0
				ELSE LAST_COST - SUMMA_RATE END

	UPDATE @TMP_TABLE2 SET DEPRE_RATE = 100,
				SUMMA_RATE = T1.BALANCE - T1.DEPRE_SUM,
				DEPRE_SUM_A = T1.BALANCE,
				LAST_COST_A = 0
	FROM @TMP_TABLE2 T1
	INNER JOIN ASSETS ASS ON (ASS.LINK_UP = T1.INV_LINK)
	INNER JOIN dbo.BK_AMORT_FULL_CALC_PERIOD AFCP ON (ASS.DATE_BEGIN BETWEEN AFCP.DATE_BEGIN AND AFCP.DATE_END)
	WHERE BALANCE > (QTY * AFCP.SUM_MIN) AND BALANCE <= (QTY * AFCP.SUM_MAX)

-- select * from @TMP_TABLE2

	IF @varKSnFlagAllDepre = 1
		UPDATE 	@TMP_TABLE2
		SET SUMMA_RATE = SUMMA_RATE + LAST_COST_A,
		    LAST_COST_A = 0
		WHERE LAST_COST_A < SUMMA_RATE

--	FROM @TMP_TABLE2 T1
	
--	DELETE FROM @TMP_TABLE2 WHERE LAST_COST_A = 0

	SELECT * FROM @TMP_TABLE2 WHERE LAST_COST <> 0 ORDER BY INV_CODE

END

GO
GRANT ALL ON dbo.[BV_GET_DEPRECIATION_ALIAS] 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.[KO_REP_RASPORIAZENIE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KO_REP_RASPORIAZENIE]

GO

CREATE    PROCEDURE [dbo].KO_REP_RASPORIAZENIE
	@nSel_Spr1 int,
	@nSel_Spr2 int = NULL,-- пункт приказа 1
	@nSel_Spr3 int = NULL,-- пункт приказа 2
	@nSel_Spr4 int = NULL,-- пункт приказа 3
	@nSel_Spr5 int = NULL,-- пункт приказа 4
	@nSel_Spr6 int = NULL, -- пункт приказа 5
	@prik_type int
AS

DECLARE	@punkt_postanov  varchar(8000), -- Общий результат
		@punkt_postanov1 varchar(1600),
		@punkt_postanov2 varchar(1600),
		@punkt_postanov3 varchar(1600),
		@punkt_postanov4 varchar(1600),
		@punkt_postanov5 varchar(1600),
		@punkt_count int


-- посмотреть тип приказа

SET @punkt_postanov1 = ISNULL((SELECT [NAME] FROM dbo.KO_PUNKT_POSTANOV WHERE LINK = @nSel_Spr2),'')
SET @punkt_postanov2 = ISNULL((SELECT [NAME] FROM dbo.KO_PUNKT_POSTANOV WHERE LINK = @nSel_Spr3),'')
SET @punkt_postanov3 = ISNULL((SELECT [NAME] FROM dbo.KO_PUNKT_POSTANOV WHERE LINK = @nSel_Spr4),'')
SET @punkt_postanov4 = ISNULL((SELECT [NAME] FROM dbo.KO_PUNKT_POSTANOV WHERE LINK = @nSel_Spr5),'')
SET @punkt_postanov5 = ISNULL((SELECT [NAME] FROM dbo.KO_PUNKT_POSTANOV WHERE LINK = @nSel_Spr6),'')

SET @punkt_count = 0
SET @punkt_postanov = ''
IF @punkt_postanov1 IS NOT NULL AND @punkt_postanov1 <> ''
BEGIN
	SET @punkt_count = @punkt_count + 1
	SET @punkt_postanov = @punkt_postanov + CONVERT(varchar(256),@punkt_count) + '. ' + RTRIM (@punkt_postanov1) + CHAR(10)
END

IF @punkt_postanov2 IS NOT NULL AND @punkt_postanov2 <> ''
BEGIN
	SET @punkt_count = @punkt_count + 1
	SET @punkt_postanov = @punkt_postanov + CONVERT(varchar(256),@punkt_count) + '. ' + RTRIM (@punkt_postanov2) + CHAR(10)
END

IF @punkt_postanov3 IS NOT NULL AND @punkt_postanov3 <> ''
BEGIN
	SET @punkt_count = @punkt_count + 1
	SET @punkt_postanov = @punkt_postanov + CONVERT(varchar(256),@punkt_count) + '. ' + RTRIM (@punkt_postanov3)+ CHAR(10)
END

IF @punkt_postanov4 IS NOT NULL AND @punkt_postanov4 <> ''
BEGIN
	SET @punkt_count = @punkt_count + 1
	SET @punkt_postanov = @punkt_postanov + CONVERT(varchar(256),@punkt_count) + '. ' + RTRIM (@punkt_postanov4)+ CHAR(10)
END

IF @punkt_postanov5 IS NOT NULL AND @punkt_postanov5 <> ''
BEGIN
	SET @punkt_count = @punkt_count + 1
	SET @punkt_postanov = @punkt_postanov + CONVERT(varchar(256),@punkt_count) + '. ' + RTRIM (@punkt_postanov5)+ CHAR(10)
END

CREATE TABLE #P1(LINK INT, P1 VARCHAR(1600))
INSERT INTO #P1 (LINK, P1)
EXEC DBO.EXECUTE_STR @punkt_postanov,@nSel_Spr1,@prik_type


DECLARE @prikazType INT
SET @prikazType = (	SELECT [TYPE] FROM dbo.ORDERS WHERE LINK = @nSel_Spr1)
					
-- 1 - о приеме на работу
IF @prikazType IN (1,101)
BEGIN
	-- формировать строку пункта распоряжения/постановления для приказа "О приеме на работу"
	SELECT
		[DATE] = DATE,
		[NUMBER] = NUMBER,
		[NEW_POST] = NEW_POST,
		[FIO] = FIO,
		[IO] = (SELECT 'исполняющий обязанности ' FROM NEW_FACE WHERE order_link = @nSel_Spr1 AND [IO]=1),
		[PUNKTS] = P1
	FROM dbo.NEW_FACE A INNER JOIN #P1 B ON A.LINK = B.LINK
	WHERE ORDER_LINK = @nSel_Spr1
    

END

IF @prikazType IN (2, 102)
-- 2 - о переводе на другую должность
BEGIN
	-- формировать строку пункта распоряжения/постановления для приказа "О пеперводе на другую должность"
	SELECT	
		[DATE] = DATE,
		[NUMBER] = NUMBER,
		[NEW_POST] = NEW_POST,
		[FIO] = FIO,
		[IO] = (SELECT 'исполняющий обязанности ' FROM NEW_FACE WHERE order_link = @nSel_Spr1 AND [IO]=1),
		[PUNKTS] = P1
	FROM dbo.MOVES A INNER JOIN #P1 B ON A.LINK = B.LINK 
	WHERE ORDER_LINK = @nSel_Spr1
	
END

GO


GRANT EXECUTE ON dbo.[KO_REP_RASPORIAZENIE] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS OFF
GO
SET LOCK_TIMEOUT -1
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_SYNC_KBK_DIFF]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_SYNC_KBK_DIFF]
GO

CREATE procedure [dbo].[RT_SYNC_KBK_DIFF]
    @CodeDict varchar(250)
AS

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT -1 -- Время ожидания разблокировки ресурсов 30 сек.

BEGIN TRANSACTION 
SAVE TRANSACTION SaveTran 

declare @liError INT, @dDate_End DATETIME, @dDate_Begin DATETIME  , @vcName VARCHAR(254), @link_kbk INT, @dBegin_date DATETIME, @dEnd_date DATETIME, @vcLong_Name VARCHAR(8000), @link_self INT, @childrens BIT, @vcCode_Str VARCHAR(1000), @iproperty INT, @vcAdd_Info VARCHAR(8000) 
----------------------------------------------------------------------
declare @fed_dict_code varchar(250),
		@is_ist tinyint,
		@link int,
		@code varchar(20)

set @is_ist = case when left(@CodeDict,3)='ИСТ' then 1 else 0 end
set @fed_dict_code = left(ltrim(@CodeDict),len(@CodeDict)-5)

while exists(select top 1 * from #bks_report_kbk) begin
	select top 1 @link = link, @code = code, @dDate_End = date_end, @dDate_Begin = date_begin, @vcName = left(rtrim(ltrim(cname)),250), @vcLong_Name = NAME
   from #bks_report_kbk
	----------------------------------------------
	if exists(select top 1 * from dbo.report_kbk where rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code) BEGIN
      select @link_kbk = link , @dBegin_date = begin_date, @dEnd_Date = end_date, @link_self = link_self,
                     @childrens = childrens, @vcCode_Str = code_str, @iproperty = [property], @vcAdd_info = add_info
      from dbo.report_kbk where rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code

      IF NOT EXISTS (SELECT * FROM dbo.[REPORT_KBK_HIST] rkh WHERE link_up = @link_kbk)
      BEGIN 
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         SELECT link, isnull(BEGIN_date, '20000101'), NAME, Long_Name
         FROM dbo.report_kbk
         WHERE link = @link_kbk

         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         SELECT @link_kbk, isnull(@dDate_Begin, '20000101'), @vcName, @vcLong_Name
         WHERE NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE link_up = @link_kbk AND date = isnull(@dDate_Begin, '20000101'))

      END
      ELSE BEGIN
         UPDATE dbo.[REPORT_KBK_HIST]
         SET NAME = @vcName,
            Long_Name = @vcLong_Name
         WHERE link_up = @link_kbk AND Date >= isnull(@dDate_Begin, '19000101') AND Date <= isnull(@dDate_End, '30000101')
      END    
                    
      
      SELECT @dBegin_date = case when isnull(@dDate_Begin, '19000101') > ISNULL(@dBegin_date, '19000101') THEN ISNULL(@dBegin_date, '19000101') ELSE isnull(@dDate_Begin, '19000101') END,
			@dEnd_Date = case when isnull(@dDate_End, '30000101') > ISNULL(@dEnd_Date, '30000101') THEN isnull(@dDate_End, '30000101') ELSE ISNULL(@dEnd_Date, '30000101') END
         
      EXEC dbo.[RN_SAVE_REPORT_KBK] @link_kbk, @code, @link_self, @vcName, @CodeDict, @childrens,@vcCode_Str, @iproperty, @vcAdd_info, @vcLong_Name,  @dBegin_date, @dEnd_Date
     
--      
--      INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
--      SELECT link, begin_date,  NAME, long_name
--      FROM dbo.report_kbk K
--      WHERE  rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code
--            AND NOT EXISTS(SELECT * FROM dbo.report_kbk_hist H WHERE H.link_up = K.link AND H.date = K.begin_date)
--      
--		update dbo.report_kbk
--		set [name] = (select left(rtrim(ltrim(cname)),250) from #bks_report_kbk where link = @link), 
--			[long_name] = (select rtrim(name) from #bks_report_kbk where link = @link),
--		 where rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code
--       
--      DELETE dbo.[REPORT_KBK_HIST]
--      WHERE link_up IN (SELECT link FROM dbo.report_kbk WHERE  rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code)
--            AND [DATE] > @dDate_Begin
--               
--      INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
--      SELECT link, @dDate_Begin,  (select left(rtrim(ltrim(cname)),250) from #bks_report_kbk where link = @link), (select rtrim(name) from #bks_report_kbk where link = @link)
--      FROM dbo.report_kbk 
--      WHERE  rtrim(code_form) = @CodeDict and (case @is_ist when 1 then right(rtrim(code),20) else code end) = @code
                     
            
	end
	else begin
		insert into dbo.report_kbk(code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,orders,Long_name,begin_date,end_date)
		select 
			[code], 
			0,
			rtrim(@CodeDict),
			0,
			left(ltrim([cname]),250),
			0,
			'',
			0,
			'',/*'BKS_'+convert(varchar,getdate(),112),*/
			NULL,
			rtrim([name]), 
			[date_begin], 
			[date_end]
		from #bks_report_kbk where link = @link
	end
	----------------------------------------------
	delete from #bks_report_kbk where link = @link
end
----------------------------------------------------------------------
SELECT @liError    = @@ERROR

EXEC dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = @CodeDict

IF @liError <> 0 
	ROLLBACK TRANSACTION SaveTran 

COMMIT TRANSACTION

return 0
GO
grant execute on [dbo].[RT_SYNC_KBK_DIFF] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO
SET LOCK_TIMEOUT 30000
GO



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_SELECT_TABLES]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_SELECT_TABLES]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_SELECT_TABLES]	
   @tMode TINYINT = 0, -- 1 - режим инициализации таблицы. 
							  -- 0 - режим заполнения таблицы Таблицы,
							  -- 2 - режим заполнения таблицы Колонки
                       -- 3 - режим анализа формы
	@vcInfo VARCHAR(8000) = '' OUTPUT
AS
SET NOCOUNT ON

SET @vcInfo = ''

DECLARE @cCODE_FORM			CHAR(20),
        @vcTmp					VARCHAR(250),
        @iLINK_FORM			INT,        
        @bStandartImport	BIT,
		  @vcNameFile			VARCHAR(100),
		  @iError				INT,
		  @i						INT,
		  @iLINK_SAVED_FORM	INT,

		  @dDT					DATETIME,		  
		  @vcKBP					VARCHAR(100),
		  @tPRD					TINYINT,
		  @vcVB					VARCHAR(100),
		  @vcATRIBUTS			VARCHAR(8000),
		  @bVF0					BIT,	
		  @vcDepartments		VARCHAR(8000),
		  @vcBudgets			VARCHAR(8000),
        @iFormCount        INT,
        @iKBPCount         INT,
        @iVBCount          INT,
        @vcSOFT            VARCHAR(8000),
        @vcUK              VARCHAR(50)
      

IF @tMode = 1
BEGIN
   SELECT [CHECKED] = CAST(0 AS TINYINT),
          [ORDERS] = CAST(0 AS TINYINT),
          [NAME] = CAST(REPLICATE('A',50) AS VARCHAR(50)),
			 [LINK_TABLE] = CAST(1000000 AS INT),
			 [LINK_COL] = CAST(1000000 AS INT)
END

-- Возвращаем ссылку на сохраненную форму, если необходимо.
IF OBJECT_ID('tempdb..#tabImport') IS NULL
BEGIN
   RETURN -1
END

SET @bStandartImport = 1

SELECT TOP 1 @vcNameFile = [FILENAME]
FROM #tabImport

SELECT @iFormCount = COUNT(*)
FROM #tabImport
WHERE [TXT] = '#%'

SELECT @iKBPCount = COUNT(*)
FROM #tabImport
WHERE LEFT([TXT],4) IN ('ИСТ=','КБП=') OR
      LEFT([TXT],3) = 'КП='

SELECT @iVBCount = COUNT(*)
FROM #tabImport
WHERE LEFT([TXT],4) = 'ВИД=' OR
      LEFT([TXT],3) = 'ВБ='

IF @iLINK_FORM IS NULL
BEGIN

	CREATE TABLE #IMPORT_TABLE([TXT] VARCHAR(8000),[ORDER] INT IDENTITY(1,1))

	INSERT #IMPORT_TABLE([TXT])
	SELECT [TXT]	
	FROM #tabImport
	ORDER BY [ORDERS]

   -- Разбор загловочной части отчета, получение всех его свойств кроме данных (в REPORT_IMPORT_SAVED_FORMS).
   SET @i = dbo.[RA_GET_ERRORS_LOG_ORDER]() + 1
   
   EXEC @iError = dbo.[RA_IMPORT_FORM_ANALYZE] @iLINK_SAVED_FORM OUTPUT,
                                               DEFAULT,
                                               @vcNameFile

	SELECT @iLINK_FORM  = [LINK_FORM],
			 @vcKBP		  = CASE 
                            WHEN @iKBPCount > 1  THEN NULL
                            ELSE [KBP]
                         END,
			 @vcVB		  = CASE 
                            WHEN @iVBCount > 1  THEN NULL
                            ELSE [VB]
                         END,
			 @dDT			  = [DT],
			 @tPRD		  = [PRD],
          @bVF0		  = [VF0],
          @vcATRIBUTS  = [ATRIBUTS],
          @vcSOFT      = [SOFT]
	FROM dbo.[REPORT_IMPORT_SAVED_FORMS]
	WHERE [LINK_SAVED_FORM]=@iLINK_SAVED_FORM
   
	DELETE dbo.[REPORT_IMPORT_SAVED_FORMS]
	WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

   -- Очистка журнала ошибок dbo.[RA_IMPORT_FORM_ANALYZE]
   EXEC dbo.[RA_ERRORS_LOG_CLEAR] DEFAULT,DEFAULT,@i     

	DROP TABLE #IMPORT_TABLE

/*
	IF @iError <> 0
	BEGIN
		RETURN @iError
	END
*/

END

IF @iLINK_FORM IS NULL
BEGIN
   RETURN 
END

IF @tMode = 0
BEGIN
	SELECT [CHECKED] = 1,
			 [ORDERS],
			 [NAME],
			 [LINK_TABLE],
			 [LINK_COL]=0
	FROM dbo.[REPORT_TABLES]
	WHERE [LINK_FORM] = @iLINK_FORM
END

IF @tMode = 2
BEGIN
	SELECT [CHECKED] = 1,
			 [B].[ORDERS],
			 [B].[NAME],
			 [B].[LINK_TABLE],
			 [B].[LINK_COL]
	FROM dbo.[REPORT_TABLES]	[A]
	JOIN dbo.[REPORT_COLOUMNS] [B] ON [A].[LINK_TABLE]=[B].[LINK_TABLE]
	WHERE [A].[LINK_FORM] = @iLINK_FORM AND
			[B].[ISEXPORTED] = 1 AND
		   (ISNULL([B].[PROPERTY],0) & 1 <> 1) AND -- исключаем невидимые столбцы
			[IsEdited] = 1
END

IF @tMode = 3
BEGIN

	SELECT @vcDepartments = '',
			 @vcBudgets = ''

   IF LEN(@vcKBP)>0 
   BEGIN
	   SELECT @vcDepartments = @vcDepartments + 
									   CASE 
										   WHEN LEN(@vcDepartments)>0 THEN ', ' 
										   ELSE ''
									   END + 
									   RTRIM(LTRIM([NAME]))
	   FROM dbo.[DEPARTMENTS]
	   WHERE [BUDG] = @vcKBP
   END

	SELECT @vcBudgets = @vcBudgets +
							  CASE 
								  WHEN LEN(@vcBudgets)>0 THEN ', ' 
								  ELSE ''
							  END + 
							  RTRIM(LTRIM([NAME])) + ' ('+RTRIM(LTRIM([CODE]))+')'
	FROM dbo.[KL_BUDG_TYPE]
	WHERE [OUTCODE] = @vcVB

   IF (SELECT CODE FROM dbo.[REPORT_FORMS] WHERE [LINK_FORM] = @iLINK_FORM) = '0531467' AND @bVF0 = 0 
      BEGIN
          SELECT @vcBudgets = NULLIF(@vcBudgets,''),
			 @vcDepartments = NULLIF(@vcDepartments,''),
			 @vcInfo = CHAR(10) + 						 
						  'Код формы : ' + ISNULL(LTRIM(RTRIM([CODE])),'<н/д>') + CHAR(10) + 
						  'Период : ' + ISNULL(REPLACE(@vcATRIBUTS,'REPORTS_ATR_DATA_DAY=',''),'<н/д>')+ CHAR(10) + 
						  'Выгружено с помощью ПО : ' + ISNULL(@vcSOFT,'<н/д>') + CHAR(10) 
         	FROM dbo.[REPORT_FORMS]
	         WHERE [LINK_FORM] = @iLINK_FORM
      END   
      ELSE
          SELECT @vcBudgets = NULLIF(@vcBudgets,''),
			 @vcDepartments = NULLIF(@vcDepartments,''),
			 @vcInfo = CHAR(10) + 						 
						  'Код формы : ' + ISNULL(LTRIM(RTRIM([CODE])),'<н/д>') + CHAR(10) + 
						  'Период : ' + ISNULL(CASE @tPRD
														  WHEN 1 THEN LTRIM(STR(YEAR(@dDT-1))) + ' год'
														  WHEN 2 THEN LTRIM(STR(MONTH(@dDT-1)/4+1)) + ' квартал ' + LTRIM(STR(YEAR(@dDT-1))) + ' года'
														  WHEN 4 THEN LTRIM(STR(MONTH(@dDT-1))) + ' месяц ' + LTRIM(STR(YEAR(@dDT-1))) + ' года'														  
											 END,'<н/д>') + CHAR(10) + 
						  'Получатель (КБП=' + ISNULL(LTRIM(RTRIM(@vcKBP)),'<н/д>') + ') : ' + ISNULL(@vcDepartments,'<н/д>') + CHAR(10) +
						  'Бюджет (Код=' + ISNULL(LTRIM(RTRIM(@vcVB)),'<н/д>') +') : ' + ISNULL(@vcBudgets,'<н/д>') + CHAR(10) +
						  'Формат выгрузки : ' + ISNULL(CASE @bVF0
																	  WHEN 1 THEN ' внутренний'
																	  WHEN 0 THEN ' МФ РФ'
																  END,'<н/д>') + CHAR(10) +
                    'Выгружено с помощью ПО : ' + ISNULL(@vcSOFT,'<н/д>') + CHAR(10) +
                    CASE 
                       WHEN @iFormCount>1 THEN 'Примечание: Несколько форм в файле.' + CHAR(10) 
                       ELSE '' 
                    END
	FROM dbo.[REPORT_FORMS]
	WHERE [LINK_FORM] = @iLINK_FORM


/*
(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) as period,

select * from report_import_saved_forms
select * from report_saved_forms

select 


*/
	SELECT [INFO] = @vcInfo
END

/*
select * from report_coloumns
select case 11 when 1 then 1 when 2 then 2 when 3 then 3 end
*/
 
GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_SELECT_TABLES] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
exec xa_watchd

exec xa_watchs

SELECT * from ##tabImport 
DROP TABLE ##tabImport 
select * from report_forms where link_form = 1358

select * from report_import_saved_forms

sp_helptext RA_IMPORT_FORM_SELECT_TABLES

   IF @lvcKBP IS NULL
   BEGIN
      SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_KBP_152'
   END
   
   IF @lvcVB IS NULL 
   BEGIN
      SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
      FROM dbo.[REPORT_OPTIONS] 
      WHERE [RAZDEL] = 'FORM_152' AND
            [CODE] = 'IMPORT_VB_152'
   END

*/

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_UPDATE_OUT_TABLE_INVOICE_COR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_UPDATE_OUT_TABLE_INVOICE_COR]

GO
CREATE PROCEDURE dbo.BK_UPDATE_OUT_TABLE_INVOICE_COR
	(@intLINK	INT OUTPUT,
	@DOC_LINK	INT,
	@LINK_UP	INT,
	@QTY_AFTER	NUMERIC(19, 4) = 0,
	@PRICE_AFTER	NUMERIC(19, 4) = 0,
	@SUM_AFTER	NUMERIC(19, 4) = 0,
	@AKCIZ_AFTER 	NUMERIC(19, 4) = 0,
	@SUM_NDS_AFTER	NUMERIC(19, 4) = 0,
	@SUM_ALL_AFTER	NUMERIC(19, 4) = 0,
	@STAVKA_NDS_AFTER	NUMERIC(5, 2) = 0,
	@NO_NDS_AFTER	TINYINT,
	@TYPE_NDS_AFTER INT = NULL
	)
AS
BEGIN
	DECLARE @intINV	INT,
		@intNOMEN INT,
		@intTMC INT,

		@inttrancount INT,
		@intRowCount INT,
		@intERROR INT

	IF NOT EXISTS (SELECT * FROM dbo.OUT_TABLE_ROW WHERE LINK = @LINK_UP)
	BEGIN
		RAISERROR ('Строка была удалена!', 11, 1)
		RETURN 5
	END

	IF NOT EXISTS (SELECT * FROM dbo.G_PROV WHERE LINK = @DOC_LINK)
	BEGIN
		RAISERROR ('Документ отсутсвует!', 11, 1)
		RETURN 5
	END

	IF EXISTS (SELECT 1 FROM dbo.OUT_TABLE_INVOICE_COR
			WHERE LINK_UP = @LINK_UP
				AND DOC_LINK = @DOC_LINK
				AND LINK <> @intLINK)
		RETURN 8

	--- Вычисляем правильные значения ---
	SELECT	@QTY_AFTER = ISNULL (@QTY_AFTER, 0),
		@PRICE_AFTER = ISNULL (@PRICE_AFTER, 0),
		@SUM_AFTER = ISNULL (@SUM_AFTER, 0),
		@AKCIZ_AFTER = ISNULL (@AKCIZ_AFTER, 0),
		@SUM_NDS_AFTER = ISNULL (@SUM_NDS_AFTER, 0),
		@SUM_ALL_AFTER = ISNULL (@SUM_ALL_AFTER, 0),
		@STAVKA_NDS_AFTER = ISNULL (@STAVKA_NDS_AFTER, 0),
		@NO_NDS_AFTER = ISNULL (@NO_NDS_AFTER, 0)

	SET @TYPE_NDS_AFTER = (SELECT LINK
				FROM dbo.TYPE_OPER_NDS WITH (NOLOCK)
				WHERE @TYPE_NDS_AFTER = LINK)

	SET LOCK_TIMEOUT 30000
	SET @inttrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	UPDATE dbo.OUT_TABLE_INVOICE_COR
	SET	DOC_LINK = @DOC_LINK,
		LINK_UP = @LINK_UP,
		QTY_AFTER = @QTY_AFTER, 
		PRICE_AFTER = @PRICE_AFTER, 
		SUM_AFTER = @SUM_AFTER, 
		AKCIZ_AFTER = @AKCIZ_AFTER, 
		SUM_NDS_AFTER = @SUM_NDS_AFTER, 
		SUM_ALL_AFTER = @SUM_ALL_AFTER,
		STAVKA_NDS_AFTER = @STAVKA_NDS_AFTER,
		NO_NDS_AFTER = @NO_NDS_AFTER,
		TYPE_NDS_AFTER = @TYPE_NDS_AFTER
	WHERE LINK = @intLINK

	SELECT @intRowCount = @@ROWCOUNT,
		@intERROR = @@ERROR
	IF @intERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 1
	END

	IF @intRowCount = 0
	BEGIN
		INSERT INTO dbo.OUT_TABLE_INVOICE_COR (
			DOC_LINK,
			LINK_UP,
			QTY_AFTER,
			PRICE_AFTER,
			SUM_AFTER,
			AKCIZ_AFTER,
			SUM_NDS_AFTER,
			SUM_ALL_AFTER,
			STAVKA_NDS_AFTER,
			NO_NDS_AFTER,
			TYPE_NDS_AFTER)

		VALUES (@DOC_LINK,
			@LINK_UP,
			@QTY_AFTER, 
			@PRICE_AFTER, 
			@SUM_AFTER, 
			@AKCIZ_AFTER, 
			@SUM_NDS_AFTER, 
			@SUM_ALL_AFTER,
			@STAVKA_NDS_AFTER,
			@NO_NDS_AFTER,
			@TYPE_NDS_AFTER)

		SELECT @intRowCount = @@ROWCOUNT,
			@intERROR = @@ERROR,
			@intLINK = @@IDENTITY

		IF @intERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 1
		END
	END

	IF @@TRANCOUNT > @inttrancount
		COMMIT TRAN
	RETURN 0

END








GO


GRANT EXECUTE ON dbo.[BK_UPDATE_OUT_TABLE_INVOICE_COR] 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')

	----
	CREATE TABLE #T1 (SUBDIV VARCHAR(254), link_face INT, link_pays INT, name_pays VARCHAR(254), code_pays VARCHAR(10), typ_oper TINYINT, 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, NAME_VKR, CODE_EKR, SUMMA, [HOURS], [DAYS])
	SELECT 
		s_j_c.NAME_SUBDIV AS SUBDIV, LINK_FACE, LINK_PAYS, NAME_PAYS, CODE_PAYS, TYP_OPER, NAME_VKR, 
		CODE_EKR = CASE WHEN TYP_OPER = 3 THEN
							CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
									CASE WHEN ISNULL(CODE_EKR,'213') = '211' THEN '213' ELSE ISNULL(CODE_EKR,'213') END
								ELSE 
									CASE WHEN ISNULL(CODE_EKR,'213') IN ('211', '212') THEN '213' ELSE ISNULL(CODE_EKR,'213') END
							END
						ELSE CODE_EKR
					END, 
		SUMMA, [HOURS], [DAYS] 
	FROM 
		dbo.SALARY_JURNAL_CALCULAT 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 LINK_VKR in (select LINK_VKR from #VKR) or LEN(@varKScVal1) = 0 )
		and (LEN(@varKScVal2) <> 0 and 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 LINK_KATEG 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)
						
	----
	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
	from #T1
	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 ',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 = 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)
		FROM #T1
		GROUP BY typ_oper, name_vkr, code_ekr
		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)
		FROM #T1
		GROUP BY typ_oper, name_vkr
		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)
		FROM #T1
		GROUP BY typ_oper, code_ekr
		ORDER BY typ_oper, code_ekr

	IF coalesce(@detailed_SFIN,0) = 0 and coalesce(@detailed_EKR,0) = 0
		SELECT DISTINCT '' as TITLE, typ_oper, name_vkr = '', code_ekr = '', summa = 0 FROM #T1 GROUP BY typ_oper 

end






GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD] 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_MAKE_ALL_SVOD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_MAKE_ALL_SVOD]
GO



/*
© Кейсистемс (Keysystems), 2005
*/

CREATE         PROCEDURE dbo.RN_MAKE_ALL_SVOD
	@varKSLinkF		int,
	@varKSBDAte		datetime,
	@varKSpTYPE		tinyint,
	@varKSPNomber		tinyint,
	@varKSLinkTreeSvod	int = NULL,
	@varKSLinkSF		int = NULL,
	@varKSiSvod		tinyint = 0,
    @cTable varchar(30)='',
    @cProgressTable varchar(50)='',
	@cLinkTable varchar(50)='', --таблица с выбранными узлами
   @cTableAtr varchar(254)= ''
AS

declare @strProgressExec varchar(1000)
if @cProgressTable <>'' begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Инициализация'', percents = 1'
    execute(@strProgressExec)
end

CREATE TABLE #table_atr_global (ATR VARCHAR (250),ATR_RUS VARCHAR(250))
if isnull(@cTableAtr, '') <> ''
   execute('insert #table_atr_global (atr, atr_rus) select atr, atr_rus from ' + @cTableAtr + ' drop table ' + @cTableAtr)

--получим список всех узлов дерева где надо пересобрать свод
declare @level int,@count int,@link_tree int,@nastr int,@i int,@link int

create table #tree_org (link int,level int)

if @cLinkTable =''
begin
	insert #tree_org
	    select @varKSLinkTreeSvod,0
	set @level=1
	set @count=0
	While (select count(*) from #tree_org)<>@count
	    begin
			print @level
			select @count=count(*) from #tree_org
			insert #tree_org
			select link,@level from report_svod_tree where link_self in (select link from #tree_org where level=@level-1)
			set @level=@level+1
		end
	delete #tree_org where not exists(select * from report_svod_tree B where B.link_self=#tree_org.link)
end
else
	begin
		execute('insert #tree_org (link,level) select link,0 from '+@cLinkTable)
		--установка level
		while exists(select * from  #tree_org where level=0)
			begin
				select top 1 @link_tree=link,@link=link from #tree_org where level=0
				set @i=1
				while exists(select * from report_svod_tree where link=@link_tree) and @i<100
					begin	
						set @i=@i+1
						select @link_tree=link_self from report_svod_tree where link=@link_tree
					end
				update #tree_org set level=@i where link=@link
			end
	end

create table  #t_budg  (code varchar(20), name varchar(254))

--сбросим настройку
select top 1 @nastr=NEW_REPORT from dbo.I_REPORT_OPTIONS_COMMON 
--UPDATE REPORT_OPTIONS SET val_int=0  WHERE code='NEW_REPORT' 

       declare @Periodic tinyint
        DECLARE	@varKSLinkOrg	int,
            	@varKSBYear		int,
            	@varKSLinkTypeSvod	int
        
--select * from #tree_org
declare @icount int,@imax int,@cName varchar(50)
select @imax=count(*) from #tree_org
set @icount=1


while exists(select * from #tree_org)
    begin
        select top 1 @link_tree=link from #tree_org order  by level desc
        select @cname=RTRIM(left(name,50)) from  ro_svod_tree where link=@link_tree

        if @cProgressTable <>'' begin
            set @strProgressExec = 'update '+@cProgressTable+' set msg = '''+@cname+''', percents = '+LTRIM(str(round(@icount*100/@imax,0)))
            execute(@strProgressExec)
        end
        set @icount=@icount+1
        --если @nastr=1, то удалим все сводные отчеты.
        IF @nastr=1
          begin
            select @varKSLinkOrg = dbo.RO_SVOD_ORG(@link_tree) -- Для организации, на уровне, котором мы стоим
            select @varKSLinkTypeSvod = dbo.RO_SVOD_BUDG(@link_tree)
            -- период будет установлен такой, какой может принимать форма
            select @Periodic = Periodic from I_Report_Forms RF left outer join DEPARTMENTS DD on DD.link = @varKSLinkOrg where link_form = @varKSLinkF
            if @varKSpTYPE & @Periodic <> @varKSpTYPE
            	set @varKSpTYPE = case when @Periodic & 1 = 1 then 1 when @Periodic & 2 = 2 then 2 else 4 end
            SET @varKSPNomber = case @varKSpTYPE when 1 then 1 when 2 then convert(int, month(@varKSBDAte))/3 else month(@varKSBDAte) end

            UPDATE report_saved_forms 
            SET del = 1,
                modify_date = GETDATE()             
            where Link_Form = @varKSLinkF and Period_Number = @varKSPNomber and Period_Type = @varKSpTYPE and Begin_Date = @varKSBDAte and Link_Organization = @varKSLinkOrg and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)
                        and (atr_code in (select atr from #table_atr_global) or not exists(select top 1 * from #table_atr_global)
                              or (atr_code = 'REPORTS_ATR_ADM=000' and exists(select top 1 * from #table_atr_global where atr = 'Свести все в одну с АДМ=000')))
                              
	         update SO
	         set sid = SUSER_SID(),
		         hostname = HOST_NAME(),
		         date = GETDATE()
            from report_saved_form_owner SO
                  JOIN report_saved_forms RSF ON SO.[LSF] = rsf.[Link_Saved_Form] 
	         where RSF.Link_Form = @varKSLinkF and RSF.Period_Number = @varKSPNomber and RSF.Period_Type = @varKSpTYPE and RSF.Begin_Date = @varKSBDAte and RSF.Link_Organization = @varKSLinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)
                        and (RSF.atr_code in (select RSF.atr from #table_atr_global) or not exists(select top 1 * from #table_atr_global)
                              or (RSF.atr_code = 'REPORTS_ATR_ADM=000' and exists(select top 1 * from #table_atr_global where RSF.atr = 'Свести все в одну с АДМ=000')))

            insert report_saved_form_owner (LSF, sid, hostname, date)
		      SELECT RSF.link_saved_form, SUSER_SID(), HOST_NAME(),GETDATE()
            from report_saved_forms RSF 
                  left join report_saved_form_owner SO ON SO.[LSF] = rsf.[Link_Saved_Form] 
	         where RSF.Link_Form = @varKSLinkF and RSF.Period_Number = @varKSPNomber and RSF.Period_Type = @varKSpTYPE and RSF.Begin_Date = @varKSBDAte and RSF.Link_Organization = @varKSLinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)
                        and (RSF.atr_code in (select RSF.atr from #table_atr_global) or not exists(select top 1 * from #table_atr_global)
                              or (RSF.atr_code = 'REPORTS_ATR_ADM=000' and exists(select top 1 * from #table_atr_global where RSF.atr = 'Свести все в одну с АДМ=000')))
                  AND SO.[LSF] IS NULL 
                              
            
--            DELETE FROM report_saved_forms where Link_Form = @varKSLinkF and Period_Number = @varKSPNomber and Period_Type = @varKSpTYPE and Begin_Date = @varKSBDAte and Link_Organization = @varKSLinkOrg and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)
--                        and (atr_code in (select atr from #table_atr_global) or not exists(select top 1 * from #table_atr_global)
--                              or (atr_code = 'REPORTS_ATR_ADM=000' and exists(select top 1 * from #table_atr_global where atr = 'Свести все в одну с АДМ=000')))
          end
        print @varKSLinkF
        print @varKSBDAte
        print @varKSpTYPE
        print @varKSPNomber
        print @link_tree
        print @varKSBDAte
        print @varKSiSvod
        insert #t_budg (code,name)
		select '','Расчет свода для: '+@cname

      if not exists(select top 1 * from #table_atr_global)
      begin
            exec dbo.rn_svod_with_atributs
	               @varKSLinkF,
	               @varKSBDAte,
	               @varKSpTYPE,
	               @varKSPNomber,
	               @link_tree,
	               @varKSLinkSF	output,
	               @varKSiSvod	,
	               '', --таблица с атрибутами
                  '#t_budg'
      end
      else begin
         CREATE TABLE #table_atr (ATR VARCHAR (250),ATR_RUS VARCHAR(250))
         insert #table_atr (atr, atr_rus) select atr, atr_rus from #table_atr_global

         exec dbo.rn_svod_with_atributs
	            @varKSLinkF,
	            @varKSBDAte,
	            @varKSpTYPE,
	            @varKSPNomber,
	            @link_tree,
	            @varKSLinkSF	output,
	            @varKSiSvod	,
	            '#table_atr', --таблица с атрибутами
               '#t_budg'

         exec dbo.DropTempTable '#table_atr'
      end

          delete #tree_org where link=@link_tree
--        select * from report_dinamics where link_sf=@varKSLinkSF
--        select @link_tree
	    insert #t_budg (code,name)
		select '',''
		set @varKSLinkSF = NULL
   end

--UPDATE REPORT_OPTIONS SET val_int=@nastr  WHERE code='NEW_REPORT' 

declare @cstr varchar(1000)
IF @cTable<>''
    begin
     set @cstr='insert '+@cTable+'       select * from #t_budg'
     execute(@cstr)   
    end
else    
    select * from #t_budg


      exec dbo.DropTempTable '#table_atr_global'

GO
GRANT ALL ON dbo.[RN_MAKE_ALL_SVOD] 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.[EXECUTE_STR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[EXECUTE_STR]

GO

CREATE PROCEDURE [dbo].EXECUTE_STR
	@PUNKT_POSTANOV VARCHAR(1600),
	@ORDER_LINK INT,
	@PRIK_TYPE INT		
AS
	DECLARE @SCRIPT VARCHAR(8000), @SCRIPT1 VARCHAR(4000)
	SET @SCRIPT1 =LEFT(ISNULL(( SELECT [dbo].REPLACE_VALUES_IN_STR(@PUNKT_POSTANOV) ),''),4000)

	-- @PRIK_TYPE = 1 - "Прием сотрудников на работу"
	-- @PRIK_TYPE = 2 - "Перевод сотрудников на другую работу"
	IF (@PRIK_TYPE = 1)
		SET @SCRIPT =  'SELECT LINK, P1 = ' + @SCRIPT1 + ' FROM dbo.NEW_FACE WHERE ORDER_LINK = ' + CONVERT(VARCHAR(20),@ORDER_LINK)
	IF (@PRIK_TYPE = 2)
		SET @SCRIPT =  'SELECT LINK, P1 = ' + @SCRIPT1 + ' FROM dbo.MOVES WHERE ORDER_LINK = ' + CONVERT(VARCHAR(20),@ORDER_LINK)
	
	EXECUTE  (@SCRIPT)

GO


GRANT EXECUTE ON dbo.[EXECUTE_STR] 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 (20))
	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.[RA_EXPORT_FORM_GET_CODEPAGE]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_GET_CODEPAGE]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2010

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_GET_CODEPAGE]
	@iLINK_SAVED_FORM INT,	         -- Линк выгружаемой формы
   @tMode            INT,           -- 1 - внутренний формат, 2 - формат МФ.
	@tCodePage        TINYINT OUTPUT -- 1 - Windows-1251, 0 - DOS, 2 - UTF-8
AS

DECLARE @vcCode VARCHAR(1000), @dStartDAte DATETIME 

SET @tCodePage = CASE @tMode
                    WHEN 1 THEN 0
                    ELSE 1
                 END

SELECT @vcCode = [B].[CODE],
      @dStartDate = b.[Start_Date]
FROM dbo.[REPORT_SAVED_FORMS] [A]
JOIN dbo.[REPORT_FORMS]       [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM

IF @vcCode IN ('0521441G','0503152M','0503152G','(281)422','585','(20н)568','(158н)570','(36н)580','591','592','593','594','(127н)598','(139н)599','(19н)621','621','(93н)582','(90н)581')
BEGIN
   SET @tCodePage = 0
END

IF @vcCode IN ('(86н)001','(86н)002','(86н)003','(86н)004','(86н)005') AND @tMode = 2
BEGIN
   SET @tCodePage = 2
END

IF @vcCode = '426' AND @dStartDate = '20120101' AND @tMode = 2
BEGIN
   SET @tCodePage = 2
END 
/*
IF @vcCode IN ('0503160M','0503160G','0503360M','0503360G')
BEGIN
   SET @tCodePage = 1
END*/
/*
IF @tMode = 2
BEGIN
   IF @vcCode IN ('015')
   BEGIN
      SET @tCodePage = 2
   END
END
*/
GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_GET_CODEPAGE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_kbk where code= 'send'

select * from report_kbk where link_self in (168972,210085)
sp_helptext ra_script_send

select *
FROM dbo.[REPORT_KBK]
WHERE [CODE_FORM] = 'SEND'

exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RJ_AUTOFILL_1T_GMS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RJ_AUTOFILL_1T_GMS]

GO


/*
© Кейсистемс (Keysystems), 2010 
*/
CREATE PROCEDURE dbo.[RJ_AUTOFILL_1T_GMS]
	@varKSsFLink	int				-- экземпляр формы, для которой используется автозаполнение
AS

--//--
declare @link_form int	
declare @date_begin datetime		-- дата формирования
declare @dep_link int				-- ссылка на организацию
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),
		@dep_link = link_organization
from	report_saved_forms	
where	link_saved_form =  @varKSsFLink

declare @begin_kvart datetime
declare @end_kvart datetime
set @end_kvart = @date_begin
set @begin_kvart = dateadd(month, -3, dateadd(day, 1, @end_kvart))

-------------------------------------------------------------------------
-- ТИПЫ ДОЛЖНОСТЕЙ: select * from post_types
-------------------------------------------------------------------------
-- временные таблицы данных
-- УТВЕРЖДЕННЫЕ ШТАТНЫЕ ЕДИНИЦЫ
select	convert(numeric(3,1),isnull(num_stake,0)) as num_stake,
		gossl
into	#staff_oficial
from	dictionary_staff_fn(@date_begin) d_st
where	d_st.dep_link = @dep_link
		and d_st.deleted = 0
		and isnull(d_st.del_subdiv,1) = 0

-- Сведения о начисленной зарплате
CREATE TABLE #SALARY (LINK_EMPL INT, SUMMA_ALL NUMERIC(18,2), SUMMA_FSS NUMERIC(18,2))
INSERT INTO #SALARY (LINK_EMPL, SUMMA_ALL, SUMMA_FSS)
SELECT 
	LINK_EMPL, 
	SUMMA_ALL = SUM(case when p.stat_otchet = 1 then SUMMA else 0 end)/1000,
	SUMMA_FSS = SUM(CASE WHEN /*P.F4FSS > 1 and*/ p.stat_otchet = 2 THEN SUMMA ELSE 0 END)/1000
FROM
	dbo.PAYS P 
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
WHERE
	P.[OBJECT] = 1 
	AND --Другие начисления по дате расчёта
	(	P.WAY_CALC <> 15 AND YEAR(J.PERIOD_BEGIN)=  YEAR(@end_kvart) AND MONTH(J.PERIOD_BEGIN) <= MONTH(@end_kvart) AND J.PERIOD_END <= dbo.DateEndOfMonth(@end_kvart)
		OR --Отпуск по периоду расчёта
		P.WAY_CALC = 15 AND YEAR(J.DATE_BEGIN)=  YEAR(@end_kvart) AND MONTH(J.DATE_BEGIN) <= MONTH(@end_kvart) AND J.DATE_END <= dbo.DateEndOfMonth(@end_kvart)
	)	
	and J.LINK_DEP = @DEP_LINK

GROUP BY
	LINK_EMPL
--	

-- ФАКТИЧЕСКАЯ ЧИСЛЕННОСТЬ РАБОТНИКОВ
select	kep.link,
		case when isnull(kep.num_stake,0) > 0 then 1 else 0 end as num_stake,
		d_st.gossl
into	#staff_real
from	ku_empl_placing_fn(@date_begin) kep left join dictionary_staff_fn(@date_begin) d_st
		on kep.staff_head = d_st.link
where	kep.dep_link = @dep_link
		and isnull(kep.date_begin,0) != 0
		and kep.sack = 0
		and kep.status = 1
		and kep.notwork = 0			-- TODO: возможно надо поменять условие в соответствии с указаниями по заполнению формы
	
--------------------------------------------------------------------------
--------------------------------------------------------------------------
-- заполнение данных
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
-- 01
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 isnull(sum(num_stake),0) from #staff_oficial where GOSSL in (2,4))
-- 02
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 isnull(sum(num_stake),0) from #staff_oficial where GOSSL in (1,3))
-- 03
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 isnull(sum(num_stake),0) from #staff_oficial where GOSSL in (6))
-- 04
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 isnull(sum(num_stake),0) from #staff_oficial where GOSSL in (0))
-- 05
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 isnull(sum(num_stake),0) from #staff_oficial where GOSSL in (7))

-- ГРАФА №4
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 4
-- 01
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 isnull(sum(num_stake),0) from #staff_real where GOSSL in (2,4))
-- 02
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 isnull(sum(num_stake),0) from #staff_real where GOSSL in (1,3))
-- 03
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 isnull(sum(num_stake),0) from #staff_real where GOSSL in (6))
-- 04
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 isnull(sum(num_stake),0) from #staff_real where GOSSL in (0))
-- 05
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 isnull(sum(num_stake),0) from #staff_real where GOSSL in (7))

-- ГРАФА №5
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 5
-- 01
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,dbo.kj_ssch_empls_for_1T_GMS(@begin_kvart, @end_kvart, @dep_link, 1)
-- 02
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,dbo.kj_ssch_empls_for_1T_GMS(@begin_kvart, @end_kvart, @dep_link, 2)
-- 03
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,dbo.kj_ssch_empls_for_1T_GMS(@begin_kvart, @end_kvart, @dep_link, 3)
-- 04
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,dbo.kj_ssch_empls_for_1T_GMS(@begin_kvart, @end_kvart, @dep_link, 4)
-- 05
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,dbo.kj_ssch_empls_for_1T_GMS(@begin_kvart, @end_kvart, @dep_link, 5)

-- ГРАФА №6
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 6
-- 01
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 isnull(sum(s.summa_all),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (2,4))
-- 02
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 isnull(sum(s.summa_all),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (1,3))
-- 03
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 isnull(sum(s.summa_all),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (6))
-- 04
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 isnull(sum(s.summa_all),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (0))
-- 05
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 isnull(sum(s.summa_all),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (7))


-- ГРАФА №7
select @link_col = link_col from report_coloumns where link_table = @link_table and orders = 7
-- 01
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 isnull(sum(s.summa_fss),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (2,4))
-- 02
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 isnull(sum(s.summa_fss),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (1,3))
-- 03
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 isnull(sum(s.summa_fss),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (6))
-- 04
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 isnull(sum(s.summa_fss),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl where sr.GOSSL in (0))
-- 05
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 isnull(sum(s.summa_fss),0)
from #staff_real sr left join #SALARY s on sr.link = s.link_empl  where sr.GOSSL in (7))

--------------------------------------------------------------------------
drop table #staff_oficial
drop table #staff_real

select '' as Val


GO


GRANT EXECUTE ON dbo.[RJ_AUTOFILL_1T_GMS] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON  
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_387]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_387]
GO

/*
© Кейсистемс (Keysystems), 2012
*/

CREATE PROCEDURE dbo.[RO_PRINT_387]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
	declare @table varchar(100), @RunStr varchar(8000)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = ' ALTER TABLE #WEB_C_NASTR ADD COLNN4 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN5 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN6 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN7 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN8 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN9 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN10 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN11 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN12 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN13 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN14 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN15 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN16 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN17 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN18 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN19 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN20 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN21 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN22 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN23 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN24 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN25 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN26 INT'
                + ' ALTER TABLE #WEB_C_NASTR ADD COLNN27 INT'

   execute(@RunStr)
	set @RunStr = ' UPDATE #WEB_C_NASTR '  
                + ' SET COLNN4 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL4 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN5 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL5 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN6 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL6 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN7 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL7 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN8 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL8 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN9 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL9 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN10 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL10 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN11 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL11 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN12 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL12 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN13 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL13 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN14 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL14 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN15 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL15 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN16 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL16 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN17 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL17 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN18 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL18 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN19 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL19 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN20 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL20 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN21 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL21 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN22 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL22 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN23 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL23 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN24 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL24 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN25 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL25 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN26 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL26 <> 0) THEN 0 ELSE 1 END,'
                + ' COLNN27 = CASE WHEN EXISTS(SELECT * FROM ' + @table + ' WHERE COL26 <> 0) THEN 0 ELSE 1 END'
   

   execute(@RunStr)                   
	set @RunStr = 'SELECT * from ' + @table + '  where code <= ''08302''' 
	execute(@RunStr)

	set @RunStr = 'SELECT * from ' + @table + '  where code > ''08302''' 
	execute(@RunStr)

GO
GRANT ALL ON dbo.[RO_PRINT_387] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2010

*******************************************************************************/
-- Процедура анализа импортируемой формы (получения ее параметров).
-- Вход: таблица #IMPORT_TABLE с загруженными данными формы.
-- Коды ошибок
-- -1  - Неправильный формат даты				
-- -2  - Отсутствует раздел кода вида бюджета (ВБ или ВИД)   
-- -3  - Отсутствует раздел кода бюджетополучателя (БП, КБП или ИСТ)
-- -4  - Отсутствует раздел периодичности формы (ПРД)
-- -5  - Неправильная дата. Число должно быть 01
-- -6  - Неправильная дата. Месяц квартальной формы должен быть 01,04,07 или 10
-- -7  - Неправильная дата. Неправильная дата. Месяц для годовой формы должен быть 01
-- -9  - Организации с таким кодом бюджетополучателя не существует
-- -10 - В отчете отсутствует код бюджета
-- -11 - Выгружаемый код бюджета не уникален
-- -12 - Выгружаемый код бюджета не найден
-- -13 - Ошибка в dbo.[RA_IMPORT_FORM_GET_LINK_FORM]
-- -14 - Неверное значение в разделе периодичности формы (ПРД)
-- -15 - Неуникальный КБП в базе данных
-- -16 - Отсутствует лицензия на использование Свод-EXCEL.

CREATE PROCEDURE dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C]
   @cCODE_FORM       CHAR(20)       OUTPUT,   
   @vcKBP            VARCHAR(100)   OUTPUT,
   @vcVB             VARCHAR(10)    OUTPUT,
   @dDT              DATETIME       OUTPUT,
   @vcSOFT           VARCHAR(500)   OUTPUT,
   @vbVF0            BIT            OUTPUT,
   @tPRD             TINYINT = NULL OUTPUT,
   @iXML_DOC_HANDLE  INT,
   @txtXML           TEXT = ''
AS

SET NOCOUNT ON
SET DATEFORMAT ymd

print 'dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C]'

declare @Code    VARCHAR(100), 
        @LinkOrg INT

select top 1 @Code = Code
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/key/value',1) with (Code varchar(100) 'text()', ID VARCHAR(250) '../@about')
WHERE id LIKE '%/formCode%' 

select top 1 @dDT = CONVERT(DATETIME, [DATE], 126)
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/key/value',1) with ([DATE] VARCHAR(100) '@startDate')

IF SUBSTRING(CONVERT(VARCHAR(100), @dDT, 112), 5, 4) = '0101' AND @Code = '0503125'
BEGIN 
	set @cCODE_FORM = '0503125G'
   SET @dDT = CAST(YEAR(@dDT) + 1 AS VARCHAR(50)) + '0101'
   SET @tPRD = 1
END    

IF SUBSTRING(CONVERT(VARCHAR(100), @dDT, 112), 5, 4) <> '0101' AND @Code = '0503125'
BEGIN 
	set @cCODE_FORM = '0503125M'   
   SET @tPRD = ISNULL(MONTH(@dDT),1)   
END    

-------------------------------------------------------------------------------
-- Определение КБП (@vcKBP)
-------------------------------------------------------------------------------
DECLARE @vcINN  VARCHAR(8000),
        @vcKPP  VARCHAR(8000),
        @vcKUBP VARCHAR(8000)

SET @vcKBP = NULL
        
-- Поиск по ИНН
SELECT TOP 1 @vcINN = [INN]
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/key/value/ИНН',1) with ([INN] VARCHAR(8000) 'text()', ID VARCHAR(250) '../../@about')
WHERE id = 'http://purl.org/dc/terms/source'

IF LEN(@vcINN) > 0
BEGIN
   SELECT TOP 1 @vcKBP = [BUDG]
   FROM dbo.[DEPARTMENTS]
   WHERE [INN] = @vcINN AND
         LEN([BUDG]) > 0
END

-- Поиск по KPP
IF @vcKBP IS NULL
BEGIN
   SELECT TOP 1 @vcKPP = [KPP]
   from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/key/value/КПП',1) with ([KPP] VARCHAR(8000) 'text()', ID VARCHAR(250) '../../@about')
   WHERE id = 'http://purl.org/dc/terms/source'

   IF LEN(@vcKPP) > 0
   BEGIN
      SELECT TOP 1 @vcKBP = [BUDG]
      FROM dbo.[DEPARTMENTS]
      WHERE [KPP] = @vcKPP AND
            LEN([BUDG]) > 0
   END
END   

-- Поиск по KUBP
IF @vcKUBP IS NULL
BEGIN
   SELECT TOP 1 @vcKUBP = [KUBP]
   from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/key/value/КодУБП',1) with ([KUBP] VARCHAR(8000) 'text()', ID VARCHAR(250) '../../@about')
   WHERE id = 'http://purl.org/dc/terms/source'

   IF LEN(@vcKUBP) > 0
   BEGIN
      SELECT TOP 1 @vcKBP = [BUDG]
      FROM dbo.[DEPARTMENTS]
      WHERE [CODE_UBP] = @vcKUBP AND
            LEN([BUDG]) > 0
   END
END   

/*
SELECT inn=@vcInn
SELECT kpp=@vcKpp
SELECT KUBP=@vcKUBP
SELECT KBP=@vcKBP
*/

-------------------------------------------------------------------------------
-- Определение ВБ (@vcVB)
-------------------------------------------------------------------------------
SELECT @vcVB = [VAL_STR]
FROM dbo.[REPORT_OPTIONS] 
WHERE [RAZDEL] = 'FORM_125' AND
      [CODE] = 'IMPORT_VB_125'
-------------------------------------------------------------------------------
-- Определение выгружающего софта (@vcSOFT)
-------------------------------------------------------------------------------
SET @vcSOFT = '1C'
-------------------------------------------------------------------------------
-- Определение вида формата (@vbVF0)
-------------------------------------------------------------------------------
SET @vbVF0 = 1


select @vcKBP = Code, @vcVB = ClassCode
from OPENXML (@iXML_DOC_HANDLE, '/RootXml/Report/Period/Source',1) with (Code varchar(100), ClassCode varchar(100))

select @LinkOrg = Link from dbo.departments where budg = @vcKBP

--select @vcVB = outcode 
--from dbo.kl_budg_type
--where link in (select top 1 link_report_budg from dbo.report_svod_tree where link_report_org = @LinkOrg)

select @dDT = dateadd(month, 1, Date)
from OPENXML (@iXML_DOC_HANDLE, '/RootXml/Report/Period',1) with (Date datetime)

select @vcSOFT = [Application]
from OPENXML (@iXML_DOC_HANDLE, '/RootXml/SchemaVersion',2) with (Application varchar(100) '@Application')
set @vbVF0 = 1




GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_ANALYZE_XML_125_1C] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select @@datalength
sp_help RA_IMPORT_FORM_ANALYZE_XML
*/	

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_CHANGE_STATUS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_CHANGE_STATUS]
GO




/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.RO_CHANGE_STATUS
	@varKSiStatus	tinyint,
	@varKSsFLink	varchar(8000),
	@WEB		bit = 0 -- вызов с тонкого, 0 - с толстого, 1 - с тонкого
AS 
	DECLARE @varKSS	VARCHAR (10),
			@varKSI	INT, 
			@LinkTypeSvod int, 
			@LinkOrg int,
			@access_change tinyint,
			@EMail varchar(254),
			@Subject varchar(254),
			@Body varchar(254),
			@Template varchar(8000),
			@status tinyint
	declare @t_LSF table (LinkSF INT)
	declare @t_LSF_not_access table (LinkSF INT) -- отчеты к которым нет доступа
	declare @t_LSF_not_access_status table (LinkSF INT) -- отчеты у которых не можем поставить статус
	declare @t_info table (res varchar(1000))

	exec dbo.X_GET_OPTION 'RO_MAIL_NASTR_TEMPLATE',0,@Template output
	
	SET @varKSsFLink = ltrim(@varKSsFLink) + ' #'
	WHILE ltrim(@varKSsFLink)<>'#'
	BEGIN	
		SET @varKSI = PATINDEX ('% %',@varKSsFLink)
		SET @varKSS = LEFT(@varKSsFLink,@varKSI)
		SET @varKSsFLink = LTRIM(RIGHT(@varKSsFLink,LEN(@varKSsFLink)-@varKSI))
		INSERT INTO @t_LSF VALUES (convert(int,@varKSS)) 
	END
	-- проверяем, есть ли права на установку данного статуса
	IF IS_MEMBER('Свод-КС - ограниченый доступ к организациям')=1
		 set @WEB=1
	
	if @WEB = 1 -- с тонкого
	begin -- смотрим дерево
		select top 1 @LinkTypeSvod = Link_Type_Svod, @LinkOrg = Link_Organization from @t_LSF L inner join report_saved_forms RSF on L.LinkSF = RSF.Link_Saved_Form

    	if not exists(SELECT * FROM dbo.REPORT_STATUS WHERE access_change = 1 and Status = @varKSiStatus or IS_MEMBER('db_owner')=1 or IS_MEMBER('Главный бухгалтер')=1 or isnull(IS_MEMBER('Начальник отдела кадров'),0)=1 or (IS_MEMBER('Свод-КС')=1 and dbo.RO_SVOD_STATUS_ACCESS_MASK_ISRO (@LinkTypeSvod, @LinkOrg) = 255))
		begin
			select 'У вас нет прав на установку статуса ' + Status_Name as res from dbo.REPORT_STATUS where Status = @varKSiStatus
			select 0 as Link_Saved_Form, 0 as IsRO
			return -1
		END
      
	end


	-- теперь еще права на статус	
	SELECT @access_change = access_change FROM dbo.REPORT_STATUS WHERE Status = @varKSiStatus

	insert into @t_LSF_not_access_status
	select Link_Saved_Form from report_saved_forms where link_saved_form in (select LinkSF from @t_LSF) and
			dbo.Ro_AccessStatus(dbo.RO_AccessStatusByLink(link_form), @varKSiStatus, 1)  = 0


	delete @t_LSF
	where LinkSF in (select LinkSF from @t_LSF_not_access_status)

	-- проверяем, а есть ли права на отчет, чтобы менять его статус
	if @WEB = 1 
	begin
		insert into @t_LSF_not_access
		select Link_Saved_Form from report_saved_forms where link_saved_form in (select LinkSF from @t_LSF) 
				and (dbo.RO_ACCESS_SAVED_FORM (Link_Saved_Form, @WEB) & 2 = 0 or dbo.Ro_AccessStatus(dbo.RO_AccessStatusByLink(link_form), IsRO, 0) = 0)
	end
	else begin
		insert @t_LSF_not_access (LinkSF)
		select Link_Saved_Form from report_saved_forms where link_saved_form in (select LinkSF from @t_LSF) 
			and (dbo.Ro_AccessStatus(dbo.RO_AccessStatusByLink(link_form), IsRO, 0)  = 0 or dbo.ReportObjectAccessByLink(Link_Form) & 2 = 0 )
	end

	delete @t_LSF
	where LinkSF in (select LinkSF from @t_LSF_not_access)

	declare @varKSintLINK int
	DECLARE @lcOrgEvent VARCHAR(60),@varKSLink_Task int,@varKSEventStr varchar(254)

	declare cur_LSF cursor local static for select LinkSF from @t_LSF

	open cur_LSF

	fetch next from cur_LSF into @varKSintLINK

	while @@fetch_status = 0
	begin
		Set @lcOrgEvent = ''
	
		select @varKSLink_Task = link_task from user_info
		select @varKSEventStr = '"' + SO.Status_Name + '" на "' + SN.Status_Name + '" для Отчета: ' + rtrim(RF.code) + ' ' + atr + ' Период: ' + 
			convert(char(4),year(BEGIN_DATE)) + ' год ' + 
			case period_Type when 2 then convert(char(1),period_number) + ' квартал'
				when 4 then convert(char(2),period_number) + ' месяц'
			ELSE '' end + ' Версия:' +  convert(char(3),RSF.version) + ' Организация: ' + D.Code + ' Бюджет: ' + B.Name,
			@EMail = EMail, @Subject = 'У отчета ' + rtrim(RF.code) + ' стал статус "' + SN.Status_Name + '"',@status = RSF.IsRO,
			@Template = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Template,'[Код формы]', RTRIM(RF.code)),
																								'[Наименование формы]', RTRIM(RF.Name)),
																								'[Атрибут]', RTRIM(atr)),
																								'[Период]', 			case period_Type when 2 then convert(char(1),period_number) + ' квартал '
																															when 4 then convert(char(2),period_number) + ' месяц '
																														ELSE '' end + convert(char(4),year(BEGIN_DATE)) + ' год '),
																								'[Организация]', RTRIM(dbo.GetDepName(RSF.Link_Organization, RSF.begin_date))),
																								'[Бюджет]', RTRIM(B.Name)), 
																								'[Версия]', convert(char(3),RSF.version)),
																								'[Старый статус]', SO.Status_Name),
																								'[Новый статус]', SN.Status_Name),
																								'[Время]', convert(varchar(20), getdate(), 113)),
																								'[Комментарий формы]', '[Комментарий формы]~' + LTRIM(STR(rsf.[Link_Saved_Form])) + '~'),
																								'[Пользователь]', SUSER_SNAME(SUSER_SID()) + ' ' + isnull(dbo.AdminGetUserFIO(dbo.AdminGetUidBySID(SUSER_SID())),''))																					
		from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
			left join departments D on D.link = RSF.link_organization 
			left join kl_budg_type B on B.link = RSF.link_type_svod
			left join report_status SO on RSF.IsRO = SO.status
			left join report_status SN on SN.status = @varKSiStatus
		where link_saved_form = @varKSintLINK

		exec WF_GENERATEEVENT 'Смена статуса', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSintLINK

		if isnull(@EMail, '') <> '' and @varKSiStatus in (2, 3, 5) and @status <> @varKSiStatus
			exec dbo.RO_MAIL_SEND @EMail, @Subject, @Template 

		fetch next from cur_LSF into @varKSintLINK
	end
	
	-- непосредственно меняем статус
	update report_saved_forms
	set IsRO = @varKSiStatus, [IsRO_Set] = @varKSiStatus
	where link_saved_form in (select LinkSF from @t_LSF)

	if exists(select top 1 * from @t_LSF_not_access_status)
	begin
		insert @t_info (res)
		select 'У вас НЕТ ПРАВ на установку статуса следующих отчетов:' as res
		union all
		select Code + ' ' + RTRIM(Name) + '. Период: ' + case Period_Type when 2 then LTRIM(STR(Period_Number)) + ' квартал '
									when 4 then LTRIM(STR(Period_Number)) + ' месяц '
									else ''
							end  + LTRIM(STR(YEAR(Begin_Date))) + 'г. Версия: ' + LTRIM(STR(RSF.Version)) as res
		from @t_LSF_not_access_status A inner join report_saved_forms RSF on A.LinkSF = RSF.Link_Saved_Form
			inner join report_forms RF on RF.Link_Form = RSF.Link_Form
		union all 
		select ''
	end
	if exists(select top 1 * from @t_LSF_not_access)
	begin
		insert @t_info (res)
		select 'У вас НЕТ ПРАВ на изменение статуса следующих отчетов:' as res
		union all
		select Code + ' ' + RTRIM(Name) + '. Период: ' + case Period_Type when 2 then LTRIM(STR(Period_Number)) + ' квартал '
									when 4 then LTRIM(STR(Period_Number)) + ' месяц '
									else ''
							end  + LTRIM(STR(YEAR(Begin_Date))) + 'г. Версия: ' + LTRIM(STR(RSF.Version)) as res
		from @t_LSF_not_access A inner join report_saved_forms RSF on A.LinkSF = RSF.Link_Saved_Form
			inner join report_forms RF on RF.Link_Form = RSF.Link_Form
		union all
		select ''
	end
	if exists(select top 1 * from @t_LSF)
	begin
		insert @t_info (res)
		select 'У следующих отчетов статус стал "' +  + Status_Name + '":' as res from dbo.REPORT_STATUS where Status = @varKSiStatus
		union all
		select Code + ' ' + RTRIM(Name) + '. Период: ' + case Period_Type when 2 then LTRIM(STR(Period_Number)) + ' квартал '
									when 4 then LTRIM(STR(Period_Number)) + ' месяц '
									else ''
							end  + LTRIM(STR(YEAR(Begin_Date))) + 'г. Версия: ' + LTRIM(STR(RSF.Version)) as res
		from @t_LSF A inner join report_saved_forms RSF on A.LinkSF = RSF.Link_Saved_Form
			inner join report_forms RF on RF.Link_Form = RSF.Link_Form
         
      INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
      SELECT A.LinkSF, SUSER_SID(), (SELECT 'Смена статуса на "' + RTRIM(Status_Name) + '"'  from dbo.REPORT_STATUS where Status = @varKSiStatus)
		from @t_LSF A inner join report_saved_forms RSF on A.LinkSF = RSF.Link_Saved_Form
			inner join report_forms RF on RF.Link_Form = RSF.Link_Form
         		
	end

	select * from @t_info

	select Link_Saved_Form, IsRO
	from report_saved_forms RSF inner join @t_LSF A  on A.LinkSF = RSF.Link_Saved_Form
	

GO
GRANT ALL ON [dbo].[RO_CHANGE_STATUS] TO PUBLIC
			

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_ONE_ATR_COL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_ONE_ATR_COL]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_ONE_ATR_COL]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS
	if isnull(@WEB_excel, 0) <> 1
		select '' col1 
	declare  @atr varchar(254), @atr_value varchar(254), @iLF INT, @iLT INT, @tOT TINYINT, @vcTableName VARCHAR(100) , @vcExecStr VARCHAR(8000), @vcCol VARCHAR(800), @vcCol1 VARCHAR(800), @vcTableNameAll VARCHAR(100),
         @vcColAdd VARCHAR(8000), @iNumCol INT , @vcColUpd VARCHAR(8000)
   
   SELECT @iLF = link_form FROM dbo.[REPORT_SAVED_FORMS] rsf WHERE rsf.[Link_Saved_Form] = @LSF
   
   SELECT @atr = rf.[atributs]
   FROM dbo.[REPORT_FORMS] rf WHERE rf.[Link_Form] = @iLF
      
	set @atr_value = dbo.RN_GET_ATR_Value(@LSF, @atr)
   
   
   DECLARE cur CURSOR LOCAL STATIC FOR
      SELECT link_table, orders 
      FROM dbo.[REPORT_TABLES] rt 
      WHERE rt.[Link_Form] = @iLF
      
   OPEN [cur]
   
   FETCH NEXT FROM cur INTO @iLT, @tOT
   
   WHILE @@fetch_status = 0
   BEGIN
      SET @vcTableName = ''
      exec dbo.ro_get_all_atr_table @LSF, @tOT, @bDeleteEmptyRows, @AtrInOnePage, @atr, 1, @vcTableName OUTPUT
      
--         SET @vcExecStr = 'select * from ' + @vcTableName 
--         EXEC (@vcExecStr)
      
     
      IF COL_LENGTH('tempdb..' + @vcTableName, 'itog') IS NULL
      BEGIN
            SET @vcExecStr = 'ALTER TABLE ' + @vcTableName + ' ADD itog tinyint'
            EXECUTE( @vcExecStr)
      END          

      IF ISNULL(@vcTableNameAll, '') = ''
      BEGIN
         SET @vcTableNameAll = @vcTableName
         SELECT @iNumCol = COUNT(*)
         FROM [dbo].[REPORT_COLOUMNS] rc
         WHERE rc.[Link_Table] = @iLT 
      END          
      ELSE BEGIN
         
         

         SET @vcCol = 'atr, DEL, CODE, checked, upd, link_row, orders, calc_orders, print_null, itog'
         SET @vcCol1 = 'atr, DEL, CODE, checked, upd, link_row, orders, calc_orders, print_null, 0 '
         SET @vcColAdd = ''
         SET @vcColUpd = ''

         SELECT @vcCol = @vcCol + ',COL' + LTRIM(RTRIM(STR(RC.orders + @iNumCol))), @vcCol1 = @vcCol1 + ',COL' + LTRIM(RTRIM(STR(RC.orders))),
               @vcColUpd = @vcColUpd + 'COL' + LTRIM(RTRIM(STR(RC.orders + @iNumCol))) + ' = A.COL' + LTRIM(RTRIM(STR(RC.orders))) + ',',
               @vcColAdd = @vcColAdd + 'ALTER TABLE ' + @vcTableNameAll + ' ADD COL' + LTRIM(RTRIM(STR(RC.orders + @iNumCol))) 
                           + CASE WHEN rc.[Col_Type] = 0 THEN ' NUMERIC(20,2) ' ELSE ' varchar(8000) ' END                     
         
         FROM dbo.[REPORT_COLOUMNS] rc JOIN dbo.[REPORT_TABLES] rt ON rc.[Link_Table] = rt.[Link_Table]
         WHERE rt.[Link_Table]= @iLT

         SELECT @iNumCol = @iNumCol + COUNT(*)
         FROM [dbo].[REPORT_COLOUMNS] rc
         WHERE rc.[Link_Table] = @iLT 

         EXEC (@vcColAdd)                    
         SET @vcExecStr = 'UPDATE B SET ' + SUBSTRING(@vcColUpd, 1, LEN(@vcColUpd)-1) + ' from ' +  @vcTableNameAll + ' B JOIN ' + @vcTableName + ' A ON  A.CODE = B.Code'
      PRINT @vcExecStr         
         EXEC (@vcExecStr)
         SET @vcExecStr = 'insert ' + @vcTableNameAll + ' (' + @vcCol + ') select ' + @vcCol1 + ' from ' + @vcTableName + ' A where not exists(select * from ' + @vcTableNameAll + ' B where A.CODE = B.Code)  drop table ' + @vcTableName
         EXEC (@vcExecStr)
      END        
      

        
       
      FETCH NEXT FROM cur INTO @iLT, @tOT
   END      
   
   close [cur]
   DEALLOCATE [cur]
   

   
   SET @vcExecStr = 'select atr as colatr, * from ' + @vcTableNameAll + ' order by atr, code' 
   EXEC (@vcExecStr)

	if isnull(@WEB_excel, 0) <> 1
	select cells as style,style as value from report_print_style where 1=0 order by cells


GO
GRANT ALL ON dbo.[RO_PRINT_ONE_ATR_COL] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_CHILD_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_CHILD_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SA_N_CHILD_SAVE
	@varKSparLINK		int	OUTPUT,
	@varKSparNumber	varchar(15) = null,
	@varKSparDate		datetime = null,
	@varKSparDateS		datetime = null,
	@varKSparComments	varchar(100) = '',
	@varKSparFlag		tinyint	= 0,
	@varKSparSumma	numeric(12,2) = 0.0,
	@LINK_KBK INT = NULL,
	@LINK_DEP INT = NULL,
	@LINK_PAY1 INT = NULL,
	@LINK_PAY2 INT = NULL	
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	varchar(7000), @varKStrancount	int, 	@varKSsoLink int, @varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


IF @varKSparNumber IS NULL OR @varKSparNumber = ''  or @varKSparDate IS NULL OR @varKSparDateS IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'DOCUMENTS_ADD_CHILD'
EXECUTE @varKSERROR = SALARY_UPD_SDOC @varKSparLINK OUTPUT, @varKSsoLink, @varKSparNumber,@varKSparDate,@varKSparComments,@varKSparFlag,@varKSparDateS,@varKSparSumma, @LINK_DEP
IF @varKSERROR <> 0
	RETURN @varKSERROR


IF not exists(select link_up from dbo.SDOC_ACHILD  where link_up =@varKSparLINK)
	BEGIN
		INSERT INTO dbo.SDOC_ACHILD WITH (ROWLOCK) (LINK_UP, LINK_SFIN, LINK_PAY1, LINK_PAY2) 
			VALUES (@varKSparLINK, @LINK_KBK, @LINK_PAY1, @LINK_PAY2)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE dbo.SDOC_ACHILD WITH (ROWLOCK) 
		SET 	LINK_SFIN = @LINK_KBK, LINK_PAY1 = @LINK_PAY1, @LINK_PAY2 = LINK_PAY2
		WHERE LINK_UP=@varKSparLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

DELETE FROM dbo.SDOC_ACHILD_TABLE  WHERE LINK_UP = @varKSparLINK


declare @varKSEventText varchar(200)
SET @varKSEventText = 'Начисление по уходу за ребёнком № ' + RTRIM(LTRIM(convert(varchar(10),@varKSparNumber))) + ' от ' + CONVERT(VARCHAR(10),@varKSparDate,104)
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SDOC',@varKSparLINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_N_CHILD_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].[RO_SELECT_KS_INSIDE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_SELECT_KS_INSIDE]
GO

/*
c Кейсистемс (Keysystems), 2006
	Вызов проверки КС на тонком
*/

CREATE                         PROCEDURE dbo.RO_SELECT_KS_INSIDE
	@varKSiLSF INT
AS

	IF EXISTS(SELECT TOP 1 * FROM dbo.REPORT_CONTROL_RULES Ru JOIN dbo.REPORT_SAVED_FORMS RSF ON Ru.Link_Form = RSF.Link_Form AND RSF.Link_Saved_Form = @varKSiLSF AND Ru.IsOutside = 0 AND Ru.IsDoschet & 4 = 4)
	BEGIN 
		SELECT 1 as checked, 'Проверка внутридокументных КС' AS NAME, 0 AS link
		UNION
		SELECT 1 AS checked, 'Проверка консолидации' AS NAME, 4 AS link
	END 
	ELSE	 	
	BEGIN 
		SELECT 1 as checked, 0 AS link, 'Проверка внутридокументных КС' AS NAME
	END 
GO
GRANT ALL ON dbo.[RO_SELECT_KS_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.[RSA_4FSS_28022011_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_4FSS_28022011_PREPARE]

GO

CREATE PROCEDURE dbo.RSA_4FSS_28022011_PREPARE 
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

EXEC dbo.BufferClear

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT

select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF
set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(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)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) WHERE WAY_CALC = 2

---Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, P.WAY_CALC, GT.PERS_LINK,
	KATEG = (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)
FROM 
	dbo.SDOC G
	INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
	INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
	LEFT JOIN dbo.pers_invalid I ON GT.PERS_LINK = I.PERS_LINK 
	AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(G.[DATE]),@nYEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
WHERE
	G.[OBJECT] =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
	AND GT.[OBJECT] = 3
	AND FLAG_JC = 1
	AND P.WAY_CALC = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK

/*РАЗДЕЛ 2.1*/
CREATE TABLE #RES2(CODE_STR VARCHAR(10), BASE_FSS NUMERIC(20,2), CNT_FSS INT, CNT_FEM INT)

/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность работающих инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2
SELECT '3', 0, @NAvgCount, 0

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
INSERT INTO #RES2
SELECT '1', 0, @NAvgCount, 0

/* Среднесписочная численность женщин */
INSERT INTO #RES2
SELECT '2', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 2, 1, 0, DEFAULT)), 0

/* Среднесписочная численность работающих во вредных условиях */
INSERT INTO #RES2
SELECT '4', 0, convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 2, DEFAULT)), 0

--Р1.ТАБЛИЦА 1
--Начислено ЕСН. На НАч квартала
INSERT INTO #RES2 --код=табл. 02, строка 3_1
SELECT '0121', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE < @nMONTH1 

--Начислено ЕСН. 1 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_3
SELECT '0123', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH1

--Начислено ЕСН. 2 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_4
SELECT '0124', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH2
--
--Начислено ЕСН. 3 мес
INSERT INTO #RES2 --код=табл. 02, строка 3_5
SELECT '0125', ISNULL(SUM(SUMMA),0), 0, 0 FROM #SPR_ESN WHERE MONTH_BASE = @nMONTH3

--Р1.ТАБЛИЦА 2

DECLARE 
	@P02010 INT, --Количество больничных
	@P02013 NUMERIC(18,2),  --Количество больничных дней 
	@P02014 NUMERIC(18,2), --Сумма по больничным за счет ФСС

	@P02020 INT, --Количество больничных по внешнему совместительству
	@P02023 NUMERIC(18,2),  --Количество больничных дней по внешнему совместительству
	@P02024 NUMERIC(18,2), --Сумма по больничным за счет ФСС по внешнему совместительству

	@P02033 NUMERIC(18,2),  --Количество По беременности и родам дней
	@P02034 NUMERIC(18,2), --Сумма По беременности и родам за счет ФСС

	@P02040 INT, -- Количество больничных по беременности и родам по внешнему совместительству
	@P02043 NUMERIC(18,2),  --Количество дней по беременности и родам по внешнему совместительству
	@P02044 NUMERIC(18,2),  --Сумма по беременности и родам за счет ФСС по внешнему совместительству

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за первым
	@P02080 INT, --количество получателей
	@P02083 NUMERIC(18,2),  -- количество произведенных выплат
	@P02084 NUMERIC(18,2), -- сумма расходов

	-- Ежемесячное пособие по уходу за ребенком по основному месту работы за вторым и последующим
	@P02090 INT, --количество получателей
	@P02093 NUMERIC(18,2),  -- количество произведенных выплат
	@P02094 NUMERIC(18,2) -- сумма расходов

---	
SELECT 
	@P02010 = COUNT(DISTINCT (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN NULL ELSE A.LINK END) ),
	@P02020 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 0 THEN A.LINK ELSE NULL END), 
	@P02040 = COUNT( DISTINCT CASE WHEN STATUS_EMPL = 3 AND COALESCE(A.DEKRET,0) = 1 THEN A.LINK ELSE NULL END) 
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK
	INNER JOIN DBO.SDOC_ADIS_TABLE1 T ON T.LINK_UP = A.LINK AND T.PAYER = 0
WHERE 
	LINK_DEP = @DEP_LINK 
	AND FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(A.[DATE]) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(A.[DATE]) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ

---	
SELECT 
	@P02013 = SUM( (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END) * ISNULL(A.FSS_DAYS,0)), --(DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	@P02023 = SUM( (CASE WHEN STATUS_EMPL = 3 THEN 1 ELSE 0 END) * (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02033 = SUM(  COALESCE(A.DEKRET,0)  * ISNULL(A.FSS_DAYS,0)),--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	@P02043 = SUM( (CASE WHEN STATUS_EMPL = 3  AND COALESCE(A.DEKRET,0) = 1 THEN 1 ELSE 0 END)  * ISNULL(A.FSS_DAYS,0))--* (DATEDIFF(DAY,T.DATE1, T.DATE2)+1) )	
FROM 
	DBO.DOCUMENTS_ADD_ARCHE A INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK 
WHERE 
	LINK_DEP = @DEP_LINK 
	AND FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(DATE) = YEAR(@BYearDate) --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(DATE) <= MONTH(@END_DATE) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ

SELECT P.F4FSS, E.[STATUS], CNT_EMPL = COUNT(DISTINCT J.LINK_EMPL), CNT = COUNT(J.LINK_EMPL),SUMMA = SUM(SUMMA), CNT_DAYS = SUM([DAYS])
INTO #ATR_4FSS
FROM 
	dbo.ATRIBUT_F4FSS A
	INNER JOIN dbo.PAYS P ON A.LINK = P.F4FSS
	INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
	INNER JOIN DBO.SA_EMPLS_INFO(@END_DATE, DEFAULT) E ON E.EMPL_LINK = J.LINK_EMPL 	
WHERE
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3
	and J.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1	
	and P.F4FSS > 1
	AND J.LINK_EKR = (SELECT LINK FROM KOSGU WHERE CODE = '213')	
GROUP BY 	
	P.F4FSS, E.[STATUS]

--ВЫПЛАТА ПОСОБИЙ По временной нетрудоспособности
-----Число дней на больничном
INSERT INTO #RES2 --код=табл. 02, строка 01
SELECT '0201', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2),0), --ISNULL(@P02014,0), 
	@P02013, @P02010

-----Число дней на больничном по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 02
SELECT '0202', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 2 AND [STATUS] = 3),0),--ISNULL(@P02024,0), 
	@P02023, @P02020

-----Число дней по берем и родам
INSERT INTO #RES2 --код=табл. 02, строка 03
SELECT '0203', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3),0),--@P02034, 
	@P02033, 0

-----Число дней по берем и родам по внешнему совместительству
INSERT INTO #RES2 --код=табл. 02, строка 04
SELECT '0204', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 3 AND [STATUS] = 3),0),--@P02044, 
	@P02043, @P02040

INSERT INTO #RES2
SELECT '0205', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 4),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 4),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 4),0)	

INSERT INTO #RES2
SELECT '0206', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 5),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 5),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 5),0)	

---- Ежемесячное пособие по уходу за ребенком по основному месту работы
INSERT INTO #RES2
SELECT '0208',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 6),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 6),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 6),0)	

INSERT INTO #RES2
SELECT '0209',
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 7),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 7),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 7),0)	

INSERT INTO #RES2
SELECT '0210', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 8),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 8),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 8),0)	

INSERT INTO #RES2
SELECT '0211', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 9),0),
	ISNULL((SELECT SUM(CNT) FROM #ATR_4FSS WHERE F4FSS = 9),0),	
	ISNULL((SELECT SUM(CNT_EMPL) FROM #ATR_4FSS WHERE F4FSS = 9),0)		

--Р1.ТАБЛИЦА 3

Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 2)

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM 
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY GT.PERS_LINK, MONTH(G.[DATE])

CREATE TABLE #DGH_CJ (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA NUMERIC(18,2))
INSERT INTO #DGH_CJ (PERS_LINK, PERIOD_BEGIN, SUMMA)
SELECT PERS_LINK, PERIOD_BEGIN, SUM(SUMMA)
FROM dbo.CALCULATE_JURNAL CJ
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	INNER JOIN DBO.PAYS P ON P.LINK = CJ.LINK_PAYS
WHERE
	yEAR(CJ.period_begin) = @nYEAR
	AND CJ.LINK_DEP = @DEP_LINK
	AND P.[OBJECT] = 1
GROUP BY
	PERS_LINK, PERIOD_BEGIN

---------
SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO)
INTO #SALARY_SUM2
FROM 
(
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END) --на которые не начисляются страховые взносы
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B.SUMMA_BASE,0)) --на которые не начисляются страховые взносы
from 
	#DGH_CJ CJ
	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
	
--Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2 SELECT '030103', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2
INSERT INTO #RES2 SELECT '030104', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '030105', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '030106', SUM(SUMMA_ALL), 0, 0 FROM #SALARY_SUM2 WHERE MON = @nMONTH3

DECLARE @TMP_VAL NUMERIC(18,2)
--Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ
--INV_M теперь содержит только льготы (100 тыс инвалидам теперь нет)
SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN ) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2),0)
INSERT INTO #RES2 VALUES('030203', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030204', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030205', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030206', @TMP_VAL, 0, 0)


DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @LIMIT = ISNULL(@LIMIT,0)

SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
WHERE
	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0
	
--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24 
INSERT INTO #RES2 SELECT '030303', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M <= @nMONTH3
INSERT INTO #RES2 SELECT '030304', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH1
INSERT INTO #RES2 SELECT '030305', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH2
INSERT INTO #RES2 SELECT '030306', SUM(SUMMA), 0, 0 FROM #SPR_ESN2 WHERE M = @nMONTH3

--из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы
SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1KATEG3 FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2KATEG3
FROM 
	#SPR_ESN1KATEG3 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1KATEG3 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1KATEG3 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
WHERE
	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3),0)
INSERT INTO #RES2 VALUES('030503', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030504', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030505', @TMP_VAL, 0, 0)

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030506', @TMP_VAL, 0, 0)

-- Тоже выводим по физлицу в таблицу 3.1
CREATE TABLE #RAZD31 (LINK INT, COL5 NUMERIC(18,2), COL6 NUMERIC(18,2), COL7 NUMERIC(18,2), COL8 NUMERIC(18,2))

INSERT INTO #RAZD31 (LINK, COL5, COL6, COL7, COL8)
SELECT DISTINCT 
	P.REF_PHYS_PERS,
	S5 = ISNULL(S51.SUMMA,0) - ISNULL(S52.SUMMA,0),
	S6 = ISNULL(S61.SUMMA,0) - ISNULL(S62.SUMMA,0),
	S7 = ISNULL(S71.SUMMA,0) - ISNULL(S72.SUMMA,0),
	S8 = ISNULL(S81.SUMMA,0) - ISNULL(S82.SUMMA,0)
FROM 
	#SPR_ESN P

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 GROUP BY REF_PHYS_PERS) S51 ON S51.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3 GROUP BY REF_PHYS_PERS) S52 ON S52.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1 GROUP BY REF_PHYS_PERS) S61 ON S61.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1 GROUP BY REF_PHYS_PERS) S62 ON S62.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2 GROUP BY REF_PHYS_PERS) S71 ON S71.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2 GROUP BY REF_PHYS_PERS) S72 ON S72.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3 GROUP BY REF_PHYS_PERS) S81 ON S81.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3 GROUP BY REF_PHYS_PERS) S82 ON S82.REF_PHYS_PERS = P.REF_PHYS_PERS
	
WHERE KATEG = 3

DECLARE @Table_Razd31 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd31 OUTPUT
EXEC ('select * INTO ' + @Table_Razd31 + ' from #RAZD31')
EXEC dbo.BufferPush -116, @Table_Razd31

--Используется в хранимке SA_4FSS_28022011_PREPARE_INV

--Р3.ТАБЛИЦА 9

Declare @StBase5 table (link int)
Insert into @StBase5 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 5)

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(CASE WHEN GT.WAY_CALC  = 5 THEN GT.SUMMA_BASE ELSE 0 END)
INTO #DGH_FAKT_BASE2
FROM 
	dbo.DOCUMENTS_DGH G 
	INNER JOIN dbo.DOCUMENTS_DGH_T1 T1 ON T1.LINK = G.LINK
	INNER JOIN dbo.REESTR_DGH R ON R.LINK = T1.LINK_DOG-- AND FLAG_TRAVMA = 1	
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON T1.LINK = GT.LINK AND T1.PERS_LINK = GT.PERS_LINK
WHERE 
	G.LINK_DEP = @DEP_LINK
	AND FLAG_JC = 1
	--AND GT.WAY_CALC  = 5
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY GT.PERS_LINK, MONTH(G.[DATE])

SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I)
INTO #SALARY_SUM
FROM 
(
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) AND I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase5 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN DBO.PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK 
			AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
			--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END)
from 
	#DGH_CJ CJ
	INNER JOIN #DGH_FAKT_BASE2 B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK 
		AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
		--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
	
--Льготы по травматизму
DECLARE @LINK_S_OBJ INT
SET @LINK_S_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')

CREATE TABLE #TRAVM_LGOTY (I TINYINT, M TINYINT, SUMMA NUMERIC(18,2))
--скидки по травматизму
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_SKIDKI S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])
	
----Вычеты по травматизму	
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_VYCHET S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])	

--Данные для таблицы 6
CREATE TABLE #TABLE6 (MON TINYINT, SUMMA3 NUMERIC(18), SUMMA4 NUMERIC(18), SUMMA5 NUMERIC(18) )
INSERT INTO #TABLE6 (MON, SUMMA3, SUMMA4, SUMMA5)
SELECT 
	M.NUM, 
	SUMMA3 = ROUND( ISNULL( (SELECT SUM(SUMMA_ALL)-SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) ,0),
	SUMMA4 = ROUND( ISNULL( (SELECT SUM(SUMMA_ALL_I)-SUM(SUMMA_NO_I) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE I = 1 AND M = M.NUM),0) ,0),
	SUMMA5 = ROUND( ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) + ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) ,0)
FROM
	dbo.MONTHS M

INSERT INTO #RES2 SELECT '060103', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060104', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6) ,0), 0, 0
INSERT INTO #RES2 SELECT '060105', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060303', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH1) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060304', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
INSERT INTO #RES2 SELECT '060305', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060403', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH2) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060404', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
INSERT INTO #RES2 SELECT '060405', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0
---
INSERT INTO #RES2 SELECT '060503', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH3) ,0) , 0, 0
INSERT INTO #RES2 SELECT '060504', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0
INSERT INTO #RES2 SELECT '060505', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0

--Р3.ТАБЛИЦА 10
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA = SUM(SUMMA)
INTO 
	#SALARY_SUM1
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and CJ.LINK_PAYS = (select top 1 link from pays where object = 3 and way_calc = 5)
GROUP BY
	Month(CJ.PERIOD_BEGIN)

INSERT INTO #RES2 SELECT '1021', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON < @nMONTH1
INSERT INTO #RES2 SELECT '1023', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '1024', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '1025', SUM(SUMMA), 0, 0 FROM #SALARY_SUM1 WHERE MON = @nMONTH3

INSERT INTO #RES2
SELECT '1101', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10),0),	
	0

INSERT INTO #RES2
SELECT '1102', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),	
	0	
	
INSERT INTO #RES2
SELECT '1104', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11),0),	
	0

INSERT INTO #RES2
SELECT '1105', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),	
	0		

INSERT INTO #RES2
SELECT '1107', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 12),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 12),0),	
	0
	

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferPush -115, @Table_Razd1

DROP TABLE #RES2
DROP TABLE #SPR_ESN
DROP TABLE #ATR_4FSS
DROP TABLE #DGH_FAKT_BASE
DROP TABLE #SALARY_SUM2
DROP TABLE #SPR_ESN1
DROP TABLE #SPR_ESN2
DROP TABLE #SPR_ESN1KATEG3
DROP TABLE #SPR_ESN2KATEG3
DROP TABLE #RAZD31
DROP TABLE #DGH_FAKT_BASE2
DROP TABLE #SALARY_SUM
DROP TABLE #SALARY_SUM1
DROP TABLE #TRAVM_LGOTY
DROP TABLE #TABLE6


GO


GRANT EXECUTE ON dbo.[RSA_4FSS_28022011_PREPARE] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].BB_SAVE_ZAYAVKA_KR_TABLE') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].BB_SAVE_ZAYAVKA_KR_TABLE
GO







CREATE PROCEDURE BB_SAVE_ZAYAVKA_KR_TABLE
	@iLink		int	OUTPUT,
	@iLinkUp	int,
	@iSource	int,
	@iVydSr		tinyint,
	@iKBK		int,
	@iEKR		int,
	@iDCL		int,
	@iDtAcc		int,
	@iKBKD		int,
	@iEKRD		int,
	@iDCLD		int,
	@nSumma		numeric(18,2),
	@cTarget	varchar(254),
	@cTitle		varchar(254)

AS
Declare
	@iERROR		int,
	@iRowCount	int,
	@iTrancount	int
	
	

SET @iTrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
IF @iLink is null OR @iLink = 0
BEGIN
	INSERT INTO dbo.ZAYAVKA_KR_TABLE(LINK_UP, VYD_SR, [SOURCE], LINK_KBK, LINK_SGU, LINK_DCL, LINK_DT_ACC, LINK_KBK_D, LINK_SGU_D, LINK_DCL_D, SUMMA, TARGET, TITLE)
		VALUES (@iLinkUp, @iVydSr, @iSource, @iKBK, @iEKR, @iDCL, @iDtAcc, @iKBKD, @iEKRD, @iDCLD, @nSumma, @cTarget, @cTitle)
	SELECT @iERROR = @@ERROR, @iLink = @@IDENTITY
	IF @iERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END
ELSE
BEGIN
	UPDATE dbo.ZAYAVKA_KR_TABLE
		SET LINK_UP	= @iLinkUp,
		    VYD_SR	= @iVydSr,
		    [SOURCE] = @iSource,
		    LINK_KBK	= @iKBK,
		    LINK_SGU	= @iEKR,
		    LINK_DCL	= @iDCL,
		    LINK_DT_ACC = @iDtAcc,
		    LINK_KBK_D	= @iKBKD,
		    LINK_SGU_D  = @iEKRD,
		    LINK_DCL_D	= @iDCLD,
		    SUMMA	= @nSumma,
		    TARGET	= @cTarget,
		    TITLE	= @cTitle
	WHERE LINK = @iLink
	SELECT @iERROR = @@ERROR, @iRowCount = @@ROWCOUNT
	IF @iERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @iRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
END


IF @@TRANCOUNT > @iTrancount
	COMMIT TRAN


RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BV_SELECT_INV_FROM_REST]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_SELECT_INV_FROM_REST]
GO




/*
© Кейсистемс (Keysystems), 2007
*/

CREATE             PROCEDURE dbo.BV_SELECT_INV_FROM_REST
	@varKSDate		DateTime	= null,
	@varKSDepLink		INT		= null,
	@varKSAccount		char(100)	= null,
	@varKSKBK		char(100)	= null,
	@varKSEKR		char(100)	= null,
	@varKSDEP		char(100)	= null,
	@varKSSUB		char(100)	= null,
	@varKSEMP		char(100)	= null,
	@varKSNOMEN		char(100)	= null,
	@varKSINV		char(100)	= null,
	@varKSKAU		char(100)	= null,
	@varKSDEP_ACC		char(100)	= null,
	@varKSINDATE		DateTime	= null,
	@intAdded_Nomen		TINYINT		= 0
AS

IF @varKSAccount IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSAccount)
	SET @varKSAccount = NULL

IF @varKSAccount IS NULL  
  BEGIN
	DECLARE ACC CURSOR LOCAL STATIC READ_ONLY FOR 
	SELECT LINK FROM S_ACCOUNTS WHERE cSinth IN ('101','102','103','105', '108', '200', '21')
	DECLARE @varKSACC_DEF INT

	SET @varKSAccount = 'ACCOUNTS_BUFFER'
	OPEN ACC
	FETCH NEXT FROM ACC INTO @varKSACC_DEF
	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		INSERT INTO BUFFER(LINK, ID)
		SELECT DISTINCT LINK, @varKSAccount AS ID
		FROM dbo.AccountsSubtreeByRoot(@varKSACC_DEF)
		
		FETCH NEXT FROM ACC INTO @varKSACC_DEF
	END
	
	CLOSE ACC
	DEALLOCATE ACC

  END

IF @varKSKBK IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSKBK)
	SET @varKSKBK = NULL

IF @varKSEKR IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSEKR)
	SET @varKSEKR = NULL

IF @varKSDEP IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSDEP)
	SET @varKSDEP = NULL

IF @varKSSUB IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSSUB)
	SET @varKSSUB = NULL

IF @varKSEMP IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSEMP)
	SET @varKSEMP = NULL

IF @varKSNOMEN IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSNOMEN)
	SET @varKSNOMEN = NULL

IF @varKSINV IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSINV)
	SET @varKSINV = NULL

IF @varKSKAU IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSKAU)
	SET @varKSKAU = NULL

IF @varKSDEP_ACC IS NOT NULL  AND NOT EXISTS(SELECT * FROM BUFFER WHERE ID = @varKSDEP_ACC)
	SET @varKSDEP_ACC = NULL

DECLARE @DEPRE_TABLE TABLE
	(
	DEPRE_LINK INT,
	[DEPRE_SUM] [NUMERIC] (20,2),
	[INV] [INT]
	)
INSERT INTO @DEPRE_TABLE
SELECT ARTC.ACCOUNT,
	SUM(ARTC.K_SUMMA),
	ARTC.INV
FROM dbo.ARestTableByConditions(@varKSDate, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ARTC
	, dbo.S_ACCOUNTS SA
WHERE ARTC.ACCOUNT = SA.LINK AND SA.cSinth = '104'
	AND (@varKSDepLink IS NULL OR ARTC.DEP_LINK = @varKSDepLink)
GROUP BY ARTC.ACCOUNT,
	ARTC.INV

--SELECT * FROM @DEPRE_TABLE

DECLARE @TABLE_RES TABLE (UPD INT, INV_TYPE VARCHAR (30), ACC_LINK INT, ACC_CODE VARCHAR (15),
	BALANCE NUMERIC (28,4), DEPRE_SUM NUMERIC (28,4), LAST_COST NUMERIC (28,4),
	DEPRE_LINK INT, DEPRE_CODE VARCHAR (15), K_SUMMA NUMERIC (28,4), R_SUMMA NUMERIC (28,4),
	QTY NUMERIC (28,4), K_QUANTITY NUMERIC (28,4), KBK INT, EKR INT, DEP INT,
	SUB INT, EMP INT, INV_LINK INT, INV_CODE VARCHAR (30), INV_NAME VARCHAR (254),
	GRP_CODE VARCHAR (7), TMC_LINK INT, TMC_CODE VARCHAR (20), TMC_NAME VARCHAR (254),
	KAU INT, INDATE DATETIME, SOU_LINK INT, SOU_CODE VARCHAR (1), SOU_NAME VARCHAR (254), 
	SOU_LINK1 INT, SOU_CODE1 VARCHAR (1), SOU_NAME1 VARCHAR (254))

INSERT INTO @TABLE_RES
SELECT	[UPD] = CONVERT(TINYINT,1),
	INV_TYPE = 'INVENTORY_CARD',
	[ACC_LINK] = ART.ACCOUNT,
	[ACC_CODE] = SA.CODE,
	[BALANCE] = CASE WHEN ART.D_QUANTITY <> 0 THEN ISNULL(ART.D_SUMMA,0)/ISNULL(ART.D_QUANTITY,1) ELSE ISNULL(ART.D_SUMMA,0) END,
	[DEPRE_SUM] = CASE WHEN ART.D_QUANTITY <> 0 THEN ISNULL(DT.DEPRE_SUM,0)/ISNULL(ART.D_QUANTITY,1) ELSE ISNULL(DT.DEPRE_SUM,0) END,
	[LAST_COST] = CASE WHEN ART.D_QUANTITY <> 0 THEN ISNULL(ART.D_SUMMA,0)/ISNULL(ART.D_QUANTITY,1) ELSE ISNULL(ART.D_SUMMA,0) END
			- CASE WHEN ART.D_QUANTITY <> 0 THEN ISNULL(DT.DEPRE_SUM,0)/ISNULL(ART.D_QUANTITY,1) ELSE ISNULL(DT.DEPRE_SUM,0) END,

	[DEPRE_LINK] = SA_AM.LINK, 
	[DEPRE_CODE] = SA_AM.CODE, 

	ART.K_SUMMA,
	ART.R_SUMMA,
	[QTY] = ART.D_QUANTITY,
	ART.K_QUANTITY,
	ART.KBK,
	ART.EKR,
	ART.DEP,
	ART.SUB,
	ART.EMP,

	[INV_LINK] = ART.INV,
	[INV_CODE] = INV.CODE,
	[INV_NAME] = INV.[NAME],

	[GRP_CODE] = CONVERT(CHAR(7), GR_I.CODE),

	[TMC_LINK] = ART.TMC,
	[TMC_CODE] = CONVERT(CHAR(20), TMC.CODE),
	[TMC_NAME] = CONVERT(VARCHAR(80), TMC.[NAME]),

	ART.KAU,
	ART.INDATE,
	
	[SOU_LINK] = DFS.LINK, 
	[SOU_CODE] = ISNULL (DFS.CODE, '0'),
	[SOU_NAME] = DFS.[NAME],
	[SOU_LINK1] = BFS.LINK,
	SOU_CODE1 = BFS.CODE, 
	SOU_NAME1 = BFS.[NAME]

FROM dbo.ARestGroupedTableByBufferConditions(@varKSDate, @varKSAccount, 0xFFFFEFFF, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB, @varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC, default, default, @varKSINDATE, default, default, default) ART
INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = ART.ACCOUNT)
LEFT JOIN dbo.INVENTORY INV ON (INV.LINK = ART.INV)
LEFT JOIN dbo.NOMENCLATURE N ON (N.LINK = INV.NOMENCLATURE)
LEFT JOIN dbo.GROUP_INV GR_I ON (GR_I.LINK = N.GROUP_INV)
LEFT JOIN dbo.S_ACCOUNTS SA_AM1 ON (SA_AM1.LINK = GR_I.ACCOUNT_AM)
LEFT JOIN dbo.DICTION TMC ON (TMC.LINK = ART.TMC)

LEFT JOIN dbo.DICTIONARY_FINANCE_SOURCE DFS ON (DFS.CODE = SA.cSOURCE)
LEFT JOIN dbo.BB_FIN_SOURCE BFS ON (BFS.CODE = SA.cSOURCE)

LEFT JOIN  @DEPRE_TABLE DT ON (DT.INV = ART.INV)

LEFT JOIN dbo.S_ACCOUNTS SA_AM ON (SA_AM.LINK = DT.DEPRE_LINK
	OR SA_AM.cSINTH = SA_AM1.cSINTH
		AND SA_AM.cANALIT = SA_AM1.cANALIT
		AND SA_AM.cSOURCE = ISNULL (BFS.CODE, '0')
		AND SA_AM.cUSER = '')
WHERE ART.INV IS NOT NULL
	AND (@varKSDepLink IS NULL OR ART.DEP_LINK = @varKSDepLink)

IF @intAdded_Nomen = 1
	INSERT INTO @TABLE_RES
	SELECT	[UPD] = CONVERT(TINYINT,1),
		INV_TYPE = 'BV_NOMENCLATURE',
		[ACC_LINK] = ART.ACCOUNT,
		[ACC_CODE] = SA.CODE,
		[BALANCE] = CASE WHEN ART.D_QUANTITY <> 0 THEN ISNULL(ART.D_SUMMA,0)/ISNULL(ART.D_QUANTITY,1) ELSE ISNULL(ART.D_SUMMA,0) END,
		[DEPRE_SUM] = 0,
		[LAST_COST] = 0,
		[DEPRE_LINK] = 0, 
		[DEPRE_CODE] = '', 
		ART.K_SUMMA,
		ART.R_SUMMA,
		[QTY] = ART.D_QUANTITY,
		ART.K_QUANTITY,
		ART.KBK,
		ART.EKR,
		ART.DEP,
		ART.SUB,
		ART.EMP,
	
		[INV_LINK] = ART.NOMEN,
		[INV_CODE] = N.CODE,
		[INV_NAME] = N.[NAME],
	
		[GRP_CODE] = CONVERT(CHAR(7), GR_I.CODE),
	
		[TMC_LINK] = ART.TMC,
		[TMC_CODE] = CONVERT(CHAR(20), TMC.CODE),
		[TMC_NAME] = CONVERT(VARCHAR(80), TMC.[NAME]),
	
		ART.KAU,
		ART.INDATE,
		
		[SOU_LINK] = DFS.LINK, 
		[SOU_CODE] = ISNULL (DFS.CODE, '0'),
		[SOU_NAME] = DFS.[NAME],
		[SOU_LINK1] = BFS.LINK,
		SOU_CODE1 = BFS.CODE, 
		SOU_NAME1 = BFS.[NAME]

	FROM dbo.ARestGroupedTableByBufferConditions(@varKSDate, @varKSAccount, 0xFFFFEFFF, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB, @varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC, default, default, @varKSINDATE, default, default, default) ART
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = ART.ACCOUNT)
	LEFT JOIN dbo.NOMENCLATURE N ON (N.LINK = ART.NOMEN)
	LEFT JOIN dbo.GROUP_INV GR_I ON (GR_I.LINK = N.GROUP_INV)
	LEFT JOIN dbo.DICTION TMC ON (TMC.LINK = ART.TMC)
	
	LEFT JOIN dbo.DICTIONARY_FINANCE_SOURCE DFS ON (DFS.CODE = SA.cSOURCE)
	LEFT JOIN dbo.BB_FIN_SOURCE BFS ON (BFS.CODE = SA.cSOURCE)
	
	WHERE ART.NOMEN IS NOT NULL
		AND (@varKSDepLink IS NULL OR ART.DEP_LINK = @varKSDepLink)

SELECT * FROM @TABLE_RES

EXECUTE dbo.BufferClear @varKSAccount
EXECUTE dbo.BufferClear @varKSKBK
EXECUTE dbo.BufferClear @varKSEKR
EXECUTE dbo.BufferClear @varKSDEP
EXECUTE dbo.BufferClear @varKSSUB
EXECUTE dbo.BufferClear @varKSEMP
EXECUTE dbo.BufferClear @varKSNOMEN
EXECUTE dbo.BufferClear @varKSINV
EXECUTE dbo.BufferClear @varKSKAU
EXECUTE dbo.BufferClear @varKSDEP_ACC

RETURN 1




GO

GRANT EXECUTE ON dbo.[BV_SELECT_INV_FROM_REST] 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.[SALARY_BASE_SUM_PAY_EMPL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_BASE_SUM_PAY_EMPL]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE       procedure [dbo].SALARY_BASE_SUM_PAY_EMPL

 @varKSlinkEmpl	 int,
 @varKSRefPay 	int,
 @varKSdDate1	datetime,
 @varKSdDate2	datetime,
 @varKSLinkVKR  int = null,
 @varKSbGroup tinyint = 0
AS
declare @varKScSTR varchar(7000), @varKSObject int
select @varKSObject = object from pays where link =@varKSRefPay

set @varKScSTR = 
'	
DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE(''DOCUMENTS_RECALC_OPT1'')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

SELECT sj.CODE_PAYS, sj.NAME_PAYS,sj.LINK_PAYS, sj.LINK, sj.SUMMA,[NAME_VKR] = COALESCE(F.Code,''''), MON = [MONTH_BEGIN], YEAR = [YEAR_BEGIN], MON1 = MONTH(SJ.DATE1), YEAR1 = YEAR(SJ.DATE1)
	FROM 
		S_J_C_Short SJ 
		INNER JOIN dbo.group_'+(case when @varKSObject = 1 then 'pays' else 'tax' end)+'('+str(@varKSRefPay)+') T  ON SJ.link_PAYS=T.' + (case when @varKSObject = 1 then 'PAY' else 'TAX' end)+'_LINK
		LEFT JOIN dbo.SAL_SFIN F ON SJ.Link_VKR = F.LINK
		--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
		LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
	WHERE 
		SJ.LINK_EMPL ='+str( @varKSlinkEmpl)+'
	AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_BEGIN ELSE SJ.DATE1 END) >='''+ convert(varchar(8),@varKSdDate1,112) + ''' 
		AND 
		(CASE WHEN COALESCE(R.LINK_UP,0) = 0 OR @DOCUMENTS_RECALC_OPT1 = 2 THEN SJ.PERIOD_END ELSE SJ.DATE2 END) <='''+ convert(varchar(8),@varKSdDate2,112) + ''''
	
if @varKSLinkVKR<>0 and not @varKSLinkVKR is null
	set @varKScSTR = @varKScSTR + '
	and LINK_VKR = '+ str(@varKSLinkVKR)

SET  @varKScSTR = @varKScSTR + ' ORDER BY [YEAR_BEGIN], [MONTH_BEGIN], sj.CODE_PAYS'

EXEC (@varKScSTR)


GO


GRANT EXECUTE ON dbo.[SALARY_BASE_SUM_PAY_EMPL] 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_MAKE_FULL_SVOD_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[I_REPORT_MAKE_FULL_SVOD_NEW]
GO



/*
© Кейсистемс (Keysystems), 2005
2009.08.04 - Olga не только расчет,но и перерасчет (вызов с I_REPORT_MAKE_FULL_SVOD_AGAIN)
*/

CREATE         PROCEDURE dbo.I_REPORT_MAKE_FULL_SVOD_NEW
	@varKSLinkF		int,
	@varKSBDAte		datetime,
	@varKSpTYPE		tinyint,
	@varKSPNomber		tinyint,
	@varKSLinkTreeSvod	int = NULL,
	@varKSLinkSF		int = NULL output,
	@varKSiSvod		tinyint = 0,
   @atribut varchar(250)='',
	@iLinkTable	int = 0
AS
DECLARE	@varKSCode		char(20),
	@varKSLinkOrg	int,
	@varKSBYear		int,
	@varKSLinkTypeSvod	int,
	@iRes 			int,
    @cSvodProc        varchar(254),
    @cSqlString        varchar(1000),
	@bMode				bit,	-- 0 - расчет свода, 1 - перерасчет свода
	@varKSLink_last_event INT,
   @atribut1 varchar(250)
    
SET @atribut1 = @atribut    

if @varKSLinkSF is NULL or @varKSLinkSF = 0
	set @bMode = 0
else
	set @bMode = 1

SET @varKSBYear = year(@varKSBDAte)


IF ltrim(rtrim(@atribut))='Свести все в одну с АДМ=000' or ltrim(rtrim(@atribut))='Свести все в одну с пустой КБК' 
begin
	set @atribut = REPLACE(@atribut, 'Свести все в одну с АДМ=000', '')
   SET @atribut1 = REPLACE(@atribut, 'Свести все в одну с АДМ=000', 'REPORTS_ATR_ADM=000')
END 

IF  @atribut LIKE '%Свести все в Вид бюджета=00%'
BEGIN
   SET @atribut1 = REPLACE(@atribut, 'Свести все в Вид бюджета=00', 'REPORTS_ATR_VID_BUDGET=00')
	set @atribut=REPLACE(REPLACE(REPLACE(@atribut, 'Свести все в Вид бюджета=00,', ''), ',Свести все в Вид бюджета=00', ''), 'Свести все в Вид бюджета=00', '')
END
   
IF ltrim(rtrim(@atribut)) LIKE 'Свести все в одну с Тип=Сводный%'
begin 
	set @atribut = REPLACE(REPLACE(@atribut, 'Свести все в одну с Тип=Сводный,', ''), 'Свести все в одну с Тип=Сводный', '')
   SET @atribut1 = 'REPORTS_ATR_TYPE_ORG=Сводный' + CASE WHEN @atribut = '' THEN '' ELSE ',' END  + @atribut
  
END  

IF ltrim(rtrim(@atribut)) LIKE '%REPORTS_FILTER_KBK%'
begin
	set @atribut = LEFT(@atribut, CHARINDEX('REPORTS_FILTER_KBK', @atribut)-1)
   if RIGHT(RTRIM(@atribut), 1) = ','
      set @atribut = LEFT(@atribut, LEN(@atribut) - 1)
   SET @atribut1 = @atribut + ',REPORTS_FILTER_KBK=Не отобрано'
end 

IF ltrim(rtrim(@atribut)) LIKE '%REPORTS_ATR_VID_NAME%'
begin
	set @atribut = LEFT(@atribut, CHARINDEX('REPORTS_ATR_VID_NAME', @atribut)-1)
   if RIGHT(RTRIM(@atribut), 1) = ','
      set @atribut = LEFT(@atribut, LEN(@atribut) - 1)
   IF @atribut LIKE '%REPORTS_ATR_VID_773%'
   BEGIN
      SELECT @atribut1 = LEFT(@atribut1, CHARINDEX('REPORTS_ATR_VID_NAME_773', @atribut1) - 1)  + 'REPORTS_ATR_VID_NAME_773=' + RTRIM(NAME)
      FROM R_SPR_ATR_VID_773
      WHERE Code = SUBSTRING(@atribut, CHARINDEX('REPORTS_ATR_VID_773', @atribut) + 20, 1) 
   END
   ELSE 
   BEGIN          
      SELECT @atribut1 =LEFT(@atribut1, CHARINDEX('REPORTS_ATR_VID_NAME', @atribut1) - 1) + 'REPORTS_ATR_VID_NAME=' + RTRIM(NAME)
      FROM R_SPR_ATR_VID
      WHERE Code = SUBSTRING(@atribut, CHARINDEX('REPORTS_ATR_VID', @atribut) + 16, 1) 
   END       
end 

select @varKSCode = code from report_forms where link_form = @varKSLinkF
if @@ROWCOUNT <> 1
	return -1  

exec dbo.RO_REPORT_MODIFY @varKSLinkSF

select @varKSLinkOrg = dbo.RO_SVOD_ORG(@varKSLinkTreeSvod) -- Для организации, на уровне, котором мы стоим
select @varKSLinkTypeSvod = dbo.RO_SVOD_BUDG(@varKSLinkTreeSvod)

-- исправлено Васильевой О.Б.
-- период будет установлен такой, какой может принимать форма
declare @Periodic tinyint, @ExecStr nvarchar(1000)
select @Periodic = Periodic from I_Report_Forms RF left outer join DEPARTMENTS DD on DD.link = @varKSLinkOrg where link_form = @varKSLinkF

if @varKSpTYPE & @Periodic <> @varKSpTYPE
	set @varKSpTYPE = case when @Periodic & 1 = 1 then 1 when @Periodic & 2 = 2 then 2 else 4 end

SET @varKSPNomber = case @varKSpTYPE when 1 then 1 when 2 then convert(int, month(@varKSBDAte))/3 else month(@varKSBDAte) end

-- Сводных форм нет, создадим форму с заданным атрибутом
DECLARE @i INT, @iCount INT, @cAtr VARCHAR(100), @cAtrValue VARCHAR(100), @atr_form VARCHAR(200), @atr VARCHAR(100), @str_val VARCHAR(7000),@atribut_rus VARCHAR(1000)
CREATE TABLE #ATR (CODE VARCHAR(100), VALUE VARCHAR(100))

IF LEFT(@atribut,1)='#'
   BEGIN
      -- формируем атрибут
    SET @atribut = SUBSTRING(@atribut, 2, 1000)
    SET @iCount = dbo.RN_GETWORDCOUNT(@atribut, '#')
    SET @i = 1
    WHILE @i <= @iCount
      BEGIN
         INSERT #ATR (CODE, VALUE)
         SELECT dbo.RN_GETWORDNUM(dbo.RN_GETWORDNUM(@atribut, @i, '#'), 1, '='), dbo.RN_GETWORDNUM(dbo.RN_GETWORDNUM(@atribut, @i, '#'), 2, '=')
         SET @i = @i + 1
      END
    select @atr_form=rtrim(atributs) from report_forms where link_form=@varKSLinkF
    set @i=1
    SET @atribut =''
    IF @atr_form<>''
       begin 
        WHILE dbo.RN_GETWORDNUM(@atr_form,@i,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atr_form, @i, ',')
                SET @str_val= ISNULL((SELECT VALUE FROM #ATR WHERE CODE = @atr), dbo.get_val(@atr,'DEFAULT_VALUE',0))
                SET @atribut = @atribut + case when @atribut<>'' then ',' else '' END + @atr +'=' + @str_val 
                set @i=@i+1
            end
       END
     SET @atribut1 = @atribut  
   END

if @bMode = 0 
begin
	exec @iRes = I_REPORT_SAVE_FORM @varKSLinkSF output, @varKSLinkF, 0, @varKSBDAte, @varKSpTYPE, @varKSPNomber, @varKSLinkOrg, 1, default, default, default, default, default, default, default, @varKSLinkTypeSvod, 0,0,0,@atribut1
	if @iRes <> 0
		BEGIN
			select '' as code,'Внимание! Свод уже существует.' as name
    		return @iRes
		end
end

declare @LINK_REPORT_ORG int,@LINK_REPORT_BUDG int

set @LINK_REPORT_ORG=@varKSLinkOrg
set @LINK_REPORT_BUDG=@varKSLinkTypeSvod
	

CREATE TABLE #A (LinkSF INT PRIMARY KEY) -- по каким формам собирается свод
INSERT INTO #A (LinkSF)
	Select max(RSF.link_saved_form)
	from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.link_form
	where RF.code = @varKSCode
		and year(RSF.begin_date) = @varKSBYear 
		and RSF.period_type=@varKSpTYPE 
		and RSF.period_number=@varKSPNomber
		and RSF.IsChangeAnalit = 0
      AND rsf.del = 0
		and ((--RSF.IsSvod = 0
--			and 
        exists(select * from dbo.RO_SVOD_TREE T 
				where Link_Self = @varKSLinkTreeSvod -- потомки
					and T.Link_Report_Org = RSF.Link_Organization
					and isnull(T.Link_Report_Budg, 0) = isnull(RSF.Link_Type_Svod, 0)
               AND T.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](@varKSBDAte)
					and T.[CHILDRENS] = 1)) -- лист
   --					and (dbo.RO_SVOD_ORG(@varKSLinkTreeSvod) <> RSF.Link_Organization or dbo.RO_SVOD_BUDG(@varKSLinkTreeSvod) <> RSF.Link_Type_Svod))) -- чтоб не брать сам свод
			or (--RSF.IsSvod = 1 and
         exists(select * from dbo.RO_SVOD_TREE T 
				where Link_Self = @varKSLinkTreeSvod -- потомки
					and T.Link_Report_Org = RSF.Link_Organization
					and isnull(T.Link_Report_Budg,0) = isnull(RSF.Link_Type_Svod,0)
               AND T.[Link_History] = dbo.[RO_SVOD_TREE_Link_History](@varKSBDAte)
					and T.[CHILDRENS] = 0 -- не лист
					and (@LINK_REPORT_ORG <> RSF.Link_Organization or isnull(@LINK_REPORT_BUDG,0) <> isnull(RSF.Link_Type_Svod,0))))) -- чтоб не брать сам свод
		and RSF.version = (Select max(RSF2.Version) 
				from report_saved_forms RSF2
				where RSF2.link_form = RSF.link_form
               AND rsf2.del = 0
					And RSF2.Link_Organization = RSF.Link_Organization
					And isnull(RSF2.Link_Type_Svod,0) = isnull(RSF.Link_Type_Svod,0)
					and year(RSF2.begin_date) = @varKSBYear 
					and RSF2.period_type=@varKSpTYPE 
					and RSF2.period_number=@varKSPNomber
					and RSF2.IsChangeAnalit = 0
--					and RSF2.IsSvod = RSF.IsSvod
--                   and dbo.rn_get_atr_val(RSF2.link_saved_form,0,1)=dbo.rn_get_atr_val(RSF.link_saved_form,0,1))                        
--                   AND dbo.rn_get_atr_svod_val(RSF.link_saved_form,0,1)=  case when @atribut<>'' then @ATRIBUT else dbo.rn_get_atr_val(RSF.link_saved_form,0,1) end
                    and isnull(RSF2.atr_code,'')=isnull(RSF.atr_code,''))                        
                    AND case when @varKSCode='425G' then dbo.rn_get_atr_svod_val(RSF.link_saved_form,0,1) else  
					isnull(RSF.atr_code,'') end like '%' + RTRIM(@ATRIBUT) + '%'
					group by Link_Organization, Link_Type_Svod,atr_code

--скопируем атрибуты
--пока все, потом будем копировать только сводные атрибуты
if @bMode = 0
begin
	IF @atribut<>''
	BEGIN
      SET @atribut = @atribut1 
/*	   IF NOT EXISTS(SELECT * FROM #ATR)
		   INSERT report_atribut_values (code_atr,link_saved_form,str_val)
		   SELECT code_atr,@varKSLinkSF,str_val from report_atribut_values where
			   link_saved_form=(select top 1 LinkSF from #A)
      ELSE			   
		   INSERT report_atribut_values (code_atr,link_saved_form,str_val)
		   SELECT CODE,@varKSLinkSF,VALUE from #ATR
      
		if @@rowcount = 0 --and (@varKSCode in ('0503125M', '425M', '0503125G', '425G') OR LEFT(@varKSCode,7) IN ('0503737','0503738', '0503779', '0503725', '0503737'))
		begin*/
         SET @ATRIBUT = REPLACE(@ATRIBUT, ',REP', '~REP')
         SET @ATRIBUT = REPLACE(@ATRIBUT, ',YA_ATR','~YA_ATR') 
			set @ExecStr = 'INSERT report_atribut_values (code_atr,link_saved_form,str_val) values(''' + 
				REPLACE(REPLACE(@ATRIBUT,'~', ''') INSERT report_atribut_values (code_atr,link_saved_form,str_val) values('''), '=', ''', @varKSLinkSF, ''') + ''')'

			exec sp_executesql @ExecStr, N'@varKSLinkSF int', @varKSLinkSF = @varKSLinkSF
	--	end		
	end
end

--обновим atr
declare @cstr varchar(250),@cstr2 varchar(250)
set @cstr=left(dbo.rn_get_atr_val(@varKSLinkSF,0,0),250) 
set @cstr2=left(dbo.rn_get_atr_val(@varKSLinkSF,0,1),250) 
update report_saved_forms
set atr =@cstr,atr_code=@cstr2
where link_saved_form=@varKSLinkSF

CREATE TABLE #B (Code_Table smallint, Code_Row varchar(50), Code_Col smallint, Summa float)
INSERT INTO  #B (Code_Table, Code_Row, Code_Col, Summa)
	SELECT CodeTable, RR.Code, CodeCol, sum(Summa) 
	from i_report_summa RS left join i_report_rows RR on RS.link_Row = RR.Link_Row 
	where link_saved_form in (select LinkSF from #A)
	group by CodeTable, RR.Code, CodeCol

set @cSvodProc = ''                                                                                   ----
select @cSvodProc = SvodProc from dbo.report_forms where Link_Form = @varKSLinkF                        --
if len(@cSvodProc) > 0 begin                                                                            -- в этом условии проверяется, заполнено - ли поле SvodProc для текущей формы
    set @cSqlString = 'exec '+replace(@cSvodProc,'#LSF',cast(@varKSLinkSF as varchar(20)))              -- и если заполнено, то выполняется прописанная хранимка. можно использовать
    execute(@cSqlString)                                                                             -- параметр #LSF вместо которого будет подставлен линк сохраненной формы       
end                                                                                                   ----
else
-----------------------------------------------------------------------------------------
begin
	CREATE TABLE #Link_col (link_col int,val_len int,dilim varchar(100))
	CREATE TABLE #str_val (link int identity (1,1), link_col int,str_val varchar(8000),link_row int)

--    SET NOCOUNT ON
--    SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
--    SET LOCK_TIMEOUT 3000 -- Время ожидания разблокировки ресурсов 3 сек.


--    BEGIN TRANSACTION -- Начало новой транзакции.
--    SAVE TRANSACTION SaveTran -- Создание точки сохранения.
	
	if @iLinkTable = 0
	begin
/*		INSERT INTO REPORT_SUMMA (link_saved_form, link_col, link_row, summa)
		select @varKSLinkSF, RC.Link_Col, RR.link_row, 
				coalesce((select sum(summa) from #B TB where TB.Code_Table = RT.orders and TB.Code_Row = RR.code and TB.Code_Col = RC.export_order),0)
				from i_report_rows RR, report_coloumns RC, report_Tables RT
				where RT.Link_Form = @varKSLinkF
					and RC.Col_Type = 0
					and RC.IsEdited = 1
					and Rc.link_table = Rt.link_Table
					and RR.link_table = RT.Link_Table*/

--		INSERT INTO REPORT_SUMMA (link_saved_form, link_col, link_row, summa)
--		select @varKSLinkSF, RC.Link_Col, RR.link_row, sum(TB.Summa)
--		from #B TB join report_tables RT on TB.Code_Table = RT.orders 
--				join i_report_rows RR on TB.Code_Row = RR.code and RR.link_table = RT.Link_Table
--				join report_coloumns RC on TB.Code_Col = RC.export_order and Rc.link_table = Rt.link_Table and RC.Col_Type = 0 and RC.IsEdited = 1
--		where RT.Link_Form = @varKSLinkF and isnull(TB.Summa,0) <> 0 and RC.Link_Col is NOT NULL and RR.link_row is NOT NULL
--		group by RC.Link_Col, RR.link_row
		INSERT INTO REPORT_SUMMA (link_saved_form, link_col, link_row, summa)
		select @varKSLinkSF, Link_Col, link_row, sum(Summa)
		from dbo.report_summa RS 
		where link_saved_form in (select LinkSF from #A)
		group by Link_Col, link_row
		
	end
	else begin
	/*	INSERT INTO REPORT_SUMMA (link_saved_form, link_col, link_row, summa)
		select @varKSLinkSF, RC.Link_Col, RR.link_row, 
				coalesce((select sum(summa) from #B TB where TB.Code_Table = RT.orders and TB.Code_Row = RR.code and TB.Code_Col = RC.export_order),0)
				from i_report_rows RR, report_coloumns RC, report_Tables RT
				where RT.Link_Form = @varKSLinkF
					and RC.Col_Type = 0
					and RC.IsEdited = 1
					and Rc.link_table = Rt.link_Table
					and RR.link_table = RT.Link_Table
					and RT.Link_Table = @iLinkTable*/

		INSERT INTO REPORT_SUMMA (link_saved_form, link_col, link_row, summa)
		select @varKSLinkSF, RC.Link_Col, RR.link_row, sum(TB.Summa)
		from #B TB join report_tables RT on TB.Code_Table = RT.orders 
				 join i_report_rows RR on TB.Code_Row = RR.code and RR.link_table = RT.Link_Table
				join report_coloumns RC on TB.Code_Col = RC.export_order and Rc.link_table = Rt.link_Table and RC.Col_Type = 0 and RC.IsEdited = 1
		where RT.Link_Table = @iLinkTable and RT.Link_Form = @varKSLinkF and isnull(TB.Summa,0) <> 0 and RC.Link_Col is NOT NULL and RR.link_row is NOT NULL
		group by RC.Link_Col, RR.link_row



	end

--обычный свод
    insert #link_col (link_col,val_len)
	select link_col,val_len from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
	and isnull(property,0)&16=0 and isnull(property,0)&32=0
print 'save_o'
	if @iLinkTable = 0
	begin
		INSERT INTO REPORT_STRING (link_saved_form, link_col, link_row, str_val)
		select @varKSLinkSF, RS.Link_Col, RS.link_row, max(str_val) 
			FROM REPORT_STRING_ALL RS
			WHERE link_Saved_form in (select LinkSF from #A)
			and link_col in (select link_col from #link_col)
			GROUP BY link_col, link_row
	end
	else begin
		INSERT INTO REPORT_STRING (link_saved_form, link_col, link_row, str_val)
		select @varKSLinkSF, RS.Link_Col, RS.link_row, max(str_val) 
			FROM REPORT_STRING_ALL RS left join report_coloumns RC on RS.Link_Col = RC.Link_Col
			WHERE link_Saved_form in (select LinkSF from #A)
			and RS.link_col in (select link_col from #link_col)
			and RC.Link_Table = @iLinkTable
			GROUP BY RS.link_col, link_row
	end

--свод c конкатенацией
	delete #link_col
    if @iLinkTable = 0
	begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
		and isnull(property,0)&16>0
	end 
	else begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table = @iLinkTable
		and isnull(property,0)&16>0
	end
	
	declare @link_row_table table (link int identity(1,1),link_row int)
	declare @str_table table (link int identity(1,1),str_val varchar(8000))
	declare @str_table_duble table (link int identity(1,1),str_val varchar(8000))
	declare @link_col_table table (link_col int)
	declare @link_row int,@link_col int,@link int
	declare @svod_str_val varchar(8000),@val_len int,@dilim varchar(100),@i_max int,@str_val_word varchar(8000)
	
	IF (select count(*) from #link_col)>0
		begin
			if @iLinkTable = 0
			begin
				insert @link_row_table (link_row)
				select link_row from i_report_rows  where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
			end
			else begin
				insert @link_row_table (link_row)
				select link_row from i_report_rows  where link_table = @iLinkTable
			end
			--идем по строкам
			while exists(select * from @link_row_table)
				begin

					select top 1 @link_row=link_row from @link_row_table
					delete @str_table	
					delete @link_col_table
					insert @link_col_table 
					select link_col from #link_col
					--по столбцам
					while exists(select * from @link_col_table)
						begin	
							select top 1 @link_col=link_col from  @link_col_table	
							select @val_len=val_len,@dilim=rtrim(ltrim(isnull(dilim,''))) from #link_col where link_col=@link_col
							if @dilim=''
								set @dilim=';'

							insert @str_table (str_val)
							select str_val from report_string_all where link_Saved_form in (select LinkSF from #A)
							and link_col=@link_col and link_row=@link_row order by str_val 
							set @svod_str_val=''
						IF exists(select * from @str_table)
						begin
							while exists(select * from @str_table)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table order by link
									if len(@svod_str_val+@str_val)<8000 and @str_val<>''
										set @svod_str_val=@svod_str_val+case when @svod_str_val='' then '' else  @dilim end +rtrim(ltrim(@str_val))
										
									delete @str_table where link=@link
								end
							--сохраним данные
							set @svod_str_val=left(@svod_str_val,@val_len)

							if @svod_str_val<>'' and  not exists(select * from report_string_all where link_saved_form=@varKSLinkSF and link_col=@link_col and link_row=@link_row)
								begin
									insert report_string (link_saved_form,link_col,link_row,str_val)
									select @varKSLinkSF, @Link_Col, @link_row, @svod_str_val
								end
						end	
							delete @link_col_table where link_col=@link_col
						end

					delete @link_row_table where link_row=@link_row
				end
		end


--свод c конкатенацией и удалением дублей
	delete #link_col
	if @iLinkTable = 0
	begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
		and isnull(property,0)&32>0
	end
	else begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table = @iLinkTable and isnull(property,0)&32>0
	end
	IF (select count(*) from #link_col)>0
		begin
			if @iLinkTable = 0
			begin
				insert @link_row_table (link_row)
				select link_row from i_report_rows  where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
			end
			else begin
				insert @link_row_table (link_row)
				select link_row from i_report_rows  where link_table = @iLinkTable
			end
			--идем по строкам
			while exists(select * from @link_row_table)
				begin
					select top 1 @link_row=link_row from @link_row_table
					delete @str_table	
					delete @str_table_duble
					delete @link_col_table
					insert @link_col_table 
					select link_col from #link_col
					--по столбцам
					while exists(select * from @link_col_table)
						begin	
							select top 1 @link_col=link_col from  @link_col_table	
							select @val_len=val_len,@dilim=rtrim(ltrim(isnull(dilim,''))) from #link_col where link_col=@link_col
							if @dilim=''
								set @dilim=';'

							insert @str_table_duble (str_val)
							select str_val from report_string_all where link_Saved_form in (select LinkSF from #A)
							and link_col=@link_col and link_row=@link_row order by str_val 
							set @svod_str_val=''
						IF exists(select * from @str_table_duble)
						begin

							while exists(select * from @str_table_duble)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table_duble order by link
									set @i_max=dbo.rn_getwordcount(@str_val,@dilim)		
									set @i=0
									while @i<@i_max	
										begin
											set @i=@i+1
											set @str_val_word=rtrim(ltrim(dbo.rn_getwordnum(@str_val,@i,@dilim)))

											if not exists(select * from @str_table where str_val=@str_val_word)
												insert 	@str_table (str_val)
												select 	@str_val_word
										end
									delete @str_table_duble where link=@link
								end
							while exists(select * from @str_table)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table order by str_val
									if len(@svod_str_val+@str_val)<8000 and @str_val<>''
										set @svod_str_val=@svod_str_val+case when @svod_str_val='' then '' else  @dilim end +rtrim(ltrim(@str_val))
										
									delete @str_table where link=@link
								end
							--сохраним данные
							set @svod_str_val=left(@svod_str_val,@val_len)
							if @svod_str_val<>'' and not exists(select * from report_string_all where link_saved_form=@varKSLinkSF and link_col=@link_col and link_row=@link_row)
								begin
									insert report_string (link_saved_form,link_col,link_row,str_val)
									select @varKSLinkSF, @Link_Col, @link_row, @svod_str_val
								end
						end	
							delete @link_col_table where link_col=@link_col
						end

					delete @link_row_table where link_row=@link_row
				end
		end



/*
    IF @@ERROR <> 0
    BEGIN
      ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
      RETURN 7 -- Возврат кода ошибки.
    END
    COMMIT TRANSACTION -- Фиксация транзакции.
*/
	DROP TABLE #B
	--Обычный Свод  динамических таблиц
   DECLARE @iLT_KS INT, @iLC_KS INT, @vcSplit VARCHAR(8000), @vcOrders_KS VARCHAR(1000), @vcKey VARCHAR(8000) , @nvExecStr NVARCHAR(4000)
   
   CREATE TABLE #t_table_ks (link_table INT)
   CREATE TABLE #t_Data (LSF int, link_col INT, Code_Row VARCHAR(8000), Float_Val NUMERIC(20,4), Str_Val VARCHAR(8000), Code_Row1 VARCHAR(50)) 
   CREATE TABLE #t_Data1 (link_col INT, Code_Row VARCHAR(8000), Float_Val NUMERIC(20,4), Str_Val VARCHAR(8000))

   
   DECLARE cur CURSOR LOCAL STATIC FOR 
      SELECT rt.Link_Table, dbo.[rn_get_formula_code_row_f](rt.[Link_Table], 'SPLIT='), dbo.[rn_get_formula_code_row_f](rt.[Link_Table], 'KEY_SVOD_KS='), dbo.[rn_get_formula_code_row_f](rt.[Link_Table], 'KEY_SVOD=')
      FROM dbo.[REPORT_TABLES] rt
      WHERE ((rt.[Link_Form] = @varKSLinkF AND @iLinkTable = 0) OR rt.[Link_Table] = @iLinkTable) AND isnull(dbo.[rn_get_formula_code_row_f](rt.[Link_Table], 'KEY_SVOD='), '') <> ''

   OPEN cur
   
   FETCH NEXT FROM cur INTO  @iLT_KS, @vcSplit, @vcOrders_KS, @vcKey
   
   WHILE @@fetch_status = 0
   BEGIN
      INSERT #t_DATA(LSF, Link_Col, Code_Row, Float_Val, Str_val, Code_Row1)
	   SELECT RD.Link_SF, link_col, code_row, sum(float_val), str_val, Code_Row
	   FROM REPORT_DINAMICS_ALL RD 
	   WHERE link_SF in (select LinkSF from #A) and link_col in (select link_col from dbo.report_coloumns WHERE link_TABLE = @iLT_KS)
	   GROUP BY RD.Link_SF, link_col, code_row, str_val
      
      set @nvExecStr = 'UPDATE #t_Data SET Code_Row = ' 
                        + REPLACE(@vcKey, 'COL(' ,'''###'' + (select str_val from  #t_Data D join dbo.report_coloumns rc on D.link_col = rc.link_col where D.LSF = #t_DATa.LSF and  D.Code_Row = #t_Data.Code_Row and rc.orders = ')
                                           
      
--      PRINT @nvExecStr
      EXEC sp_executesql @nvExecStr

      UPDATE #t_Data
      SET Code_Row = 'zzz' + Code_Row1
      WHERE SUBSTRING(Code_Row1, CHARINDEX('xxx', Code_Row), 3) IN ( '888', '000', '777', '999')
            OR Code_Row1 IN (SELECT CD FROM dbo.[RA_SELECT_FORM_TOTALS](0,@varKSLinkF,1) rsft WHERE rsft.[LINK_TABLE] = @iLT_KS)
     
      INSERT #t_DATA1 (Link_Col, Code_Row, Float_Val, Str_val)
      SELECT Link_Col, Code_Row, sum(Float_Val), MAX(Str_Val)
      FROM #t_DATA
      GROUP BY Link_Col, Code_Row
      
      UPDATE #t_Data1
      SET Code_Row = REPLACE(case when CHARINDEX('###', Code_Row)>0 then LEFT(Code_Row, CHARINDEX('###', Code_Row) - 1) ELSE Code_Row END , 'xxx', RIGHT('000' + LTRIM(RTRIM(STR((SELECT COUNT(DISTINCT D.Code_Row) FROM #t_Data1 D WHERE D.[Code_Row] <= #t_Data1.Code_Row)))),3))

      UPDATE #t_Data1
      SET Code_Row = SUBSTRING(Code_Row,4,50)
      WHERE Code_Row LIKE 'zzz%'      

      IF isnull(@vcOrders_KS, '') <> ''
      BEGIN 
         SET @vcSplit = SUBSTRING(@vcSplit, CHARINDEX('=', @vcSplit, CHARINDEX('COL' + LTRIM(RTRIM(@vcOrders_KS)), @vcSplit)) + 1, 
                                    case when CHARINDEX('#', @vcSplit, CHARINDEX('COL' + LTRIM(RTRIM(@vcOrders_KS)), @vcSplit)) = 0 THEN 100
                                       ELSE CHARINDEX('#', @vcSplit, CHARINDEX('COL' + LTRIM(RTRIM(@vcOrders_KS)), @vcSplit)) -  CHARINDEX('=', @vcSplit, CHARINDEX('COL' + LTRIM(RTRIM(@vcOrders_KS)), @vcSplit)) -1 END  ) 
 
         IF isnull(@vcSplit, '') <> ''
         BEGIN             
            set @nvExecStr = 'UPDATE #t_Data1 SET Str_Val = ' + @vcSplit + ' WHERE Link_Col = @iLC_KS'
            EXEC sp_executesql @nvExecStr, N'@iLC_KS int', @iLC_KS = @iLC_KS                              
         END
      END               

      INSERT   #t_table_ks (Link_Table) VALUES (@iLT_KS)
      
      INSERT dbo.report_dinamics ([Link_SF],[Link_Col],[Code_Row], [Float_Val], [Str_Val])
      SELECT @varKSLinkSF, link_col, code_row, float_val, str_val 
      FROM #t_Data1
      
      TRUNCATE TABLE #t_Data
      TRUNCATE TABLE #t_Data1
      
      FETCH NEXT FROM cur INTO  @iLT_KS, @vcSplit, @vcOrders_KS, @vcKey
   END 

	delete #link_col
   
	if @iLinkTable = 0
	begin
		insert #link_col (link_col,val_len)
		select link_col,val_len from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&16=0 and isnull(property,0)&32=0
	end
	else begin
		insert #link_col (link_col,val_len)
		select link_col,val_len from report_coloumns where link_table = @iLinkTable
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&16=0 and isnull(property,0)&32=0
	end

	INSERT INTO REPORT_DINAMICS (link_sf, link_col, code_row, float_val, str_val)
	SELECT @varKSLinkSF, link_col, code_row, sum(float_val), max(str_val) 
		FROM REPORT_DINAMICS_ALL RD 
		WHERE link_SF in (select LinkSF from #A) and link_col in (select link_col from #link_col)
		GROUP BY link_col, code_row

--свод c конкатенацией
	delete #link_col
	if @iLinkTable = 0
	begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&16>0
	end
	else begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table = @iLinkTable
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&16>0
	end
	
	declare @link_code_table table (link int identity(1,1),code varchar(50))
	declare @code varchar(8000)

	IF (select count(*) from #link_col)>0
		begin
			if @iLinkTable = 0
			begin
				insert @link_code_table (code)
				select distinct code_row from i_report_dinamic_rows  where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
				and link_SF in (select LinkSF from #A)
			end
			else begin
				insert @link_code_table (code)
				select distinct code_row from i_report_dinamic_rows  where link_table = @iLinkTable
				and link_SF in (select LinkSF from #A)
			end
			--идем по строкам
			while exists(select * from @link_code_table)
				begin
					select top 1 @code=code from @link_code_table
					delete @str_table	
					delete @link_col_table
					insert @link_col_table 
					select link_col from #link_col
					--по столбцам
					while exists(select * from @link_col_table)
						begin	
							select top 1 @link_col=link_col from  @link_col_table	
							select @val_len=val_len,@dilim=rtrim(ltrim(isnull(dilim,''))) from #link_col where link_col=@link_col
							if @dilim=''
								set @dilim=';'

							insert @str_table (str_val)
							select str_val from report_dinamics_all where link_SF in (select LinkSF from #A)
							and link_col=@link_col and code_row=@code order by str_val 


							set @svod_str_val=''
						IF exists(select * from @str_table)
						begin
							while exists(select * from @str_table)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table order by link
									if len(@svod_str_val+@str_val)<8000 and @str_val<>''
										set @svod_str_val=@svod_str_val+case when @svod_str_val='' then '' else  @dilim end +rtrim(ltrim(@str_val))
									delete @str_table where link=@link
								end

							--сохраним данные
							set @svod_str_val=left(@svod_str_val,@val_len)
							if @svod_str_val<>'' and  not exists(select * from report_dinamics_all where link_sf=@varKSLinkSF and link_col=@link_col and code_row=@code)
								begin

									insert report_dinamics (link_sf,link_col,code_row,str_val)
									select @varKSLinkSF, @Link_Col, @code, @svod_str_val

								end
						end
							delete @link_col_table where link_col=@link_col
						end

					delete @link_code_table where code=@code
				end
		end


--свод c конкатенацией c удалением дублей
	delete #link_col
	if @iLinkTable = 0
	begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&32>0
	end
	else begin
		insert #link_col (link_col,val_len,dilim)
		select link_col,val_len,str_property from report_coloumns where link_table = @iLinkTable
      AND link_table NOT IN (SELECT link_table FROM #t_table_ks)
		and isnull(property,0)&32>0
	end
	
--	declare @link_code_table table (link int identity(1,1),code varchar(50))
--	declare @code varchar(8000)
	IF (select count(*) from #link_col)>0
		begin
			if @iLinkTable = 0
			begin
				insert @link_code_table (code)
				select distinct code_row from i_report_dinamic_rows  where link_table in (select link_table from report_tables where link_form=@varKSLinkF)
			end
			else begin
				insert @link_code_table (code)
				select distinct code_row from i_report_dinamic_rows  where link_table = @iLinkTable
			end
			--идем по строкам
			while exists(select * from @link_code_table)
				begin
					select top 1 @code=code from @link_code_table
					delete @str_table	
					delete @link_col_table
					insert @link_col_table 
					select link_col from #link_col
					--по столбцам
					while exists(select * from @link_col_table)
						begin	
							select top 1 @link_col=link_col from  @link_col_table	
							select @val_len=val_len,@dilim=rtrim(ltrim(isnull(dilim,''))) from #link_col where link_col=@link_col
							if @dilim=''
								set @dilim=';'

							insert @str_table_duble (str_val)
							select str_val from report_dinamics_all where link_Sf in (select LinkSF from #A)
							and link_col=@link_col and code_row=@code order by str_val 
							set @svod_str_val=''
						IF exists(select * from @str_table_duble)
						begin
							while exists(select * from @str_table_duble)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table_duble order by link
									set @i_max=dbo.rn_getwordcount(@str_val,@dilim)		
									set @i=0
									while @i<@i_max	
										begin
											set @i=@i+1
											set @str_val_word=rtrim(ltrim(dbo.rn_getwordnum(@str_val,@i,@dilim)))

											if not exists(select * from @str_table where str_val=@str_val_word)
												insert 	@str_table (str_val)
												select 	@str_val_word
										end
									delete @str_table_duble where link=@link
								end

							set @svod_str_val=''
							while exists(select * from @str_table)
								begin
									select top 1 @str_val=rtrim(ltrim(isnull(str_val,''))),@link=link from @str_table order by link
									if len(@svod_str_val+@str_val)<8000 and @str_val<>''
										set @svod_str_val=@svod_str_val+case when @svod_str_val='' then '' else  @dilim end +rtrim(ltrim(@str_val))
										
									delete @str_table where link=@link
								end
							--сохраним данные
							set @svod_str_val=left(@svod_str_val,@val_len)
							if @svod_str_val<>'' and not exists(select * from report_dinamics_all where link_sf=@varKSLinkSF and link_col=@link_col and code_row=@code)
								BEGIN
									insert report_dinamics (link_sf,link_col,code_row,str_val)
									select @varKSLinkSF, @Link_Col, @code, @svod_str_val
								end
						 end 
							delete @link_col_table where link_col=@link_col
						end

					delete @link_code_table where code=@code
				end
		end

END
-------------------------
	-- Добавлено 19.03.2006: утвердить формы (запретить редактирование)
	-- Исправлено 13.10.2009: в зависимости от настройки проставлять статус "Включен в свод"
	declare @t_org_budg table (orders int, code varchar(100), name varchar(1000))
	if exists(select * from Report_Saved_Forms where Link_Saved_Form in (select LinkSF from #A) and IsRO = 0)
	begin
		insert @t_org_budg (orders, code, name)
			values(5, '        ', '                  ')

		insert @t_org_budg (orders, code, name)
			select 6, '       ', 'У следующих отчетов статус "' + status_name + '": '
			from report_status
			where status = 0

		insert @t_org_budg (orders, code, name)
			select 7, RF.Code, 'Для организации: ' + dbo.GetDepName(RSF.Link_Organization, RSF.Begin_Date) + ' Для бюджета: ' + ISNULL((select top 1 Name from kl_budg_type K where K.Link = RSF.Link_Type_Svod),'') as name
			from Report_Saved_Forms RSF left join report_forms RF on RSF.Link_Form = RF.Link_Form
			where Link_Saved_Form in (select LinkSF from #A) and IsRO = 0
			order by name
	end

	if exists(select * from Report_Saved_Forms where Link_Saved_Form in (select LinkSF from #A) and IsRO = 1)
	begin
		insert @t_org_budg (orders, code, name)
			values(8, '        ', '                  ')

		insert @t_org_budg (orders, code, name)
			select 9, '       ', 'У следующих отчетов статус "' + status_name + '": '
			from report_status
			where status = 1

		insert @t_org_budg (orders, code, name)
			select 10, RF.Code, 'Для организации: ' + dbo.GetDepName(RSF.Link_Organization, RSF.Begin_Date) + ' Для бюджета: ' + ISNULL((select top 1 Name from kl_budg_type K where K.Link = RSF.Link_Type_Svod),'') as name
			from Report_Saved_Forms RSF left join report_forms RF on RSF.Link_Form = RF.Link_Form
			where Link_Saved_Form in (select LinkSF from #A) and IsRO = 1
			order by name
	end

	if exists(select * from Report_Saved_Forms where Link_Saved_Form in (select LinkSF from #A) and IsRO = 3)
	begin
		insert @t_org_budg (orders, code, name)
			values(11, '        ', '                  ')

		insert @t_org_budg (orders, code, name)
			select 12, '       ', 'У следующих отчетов статус "' + status_name + '": '
			from report_status
			where status = 3

		insert @t_org_budg (orders, code, name)
			select 13, RF.Code, 'Для организации: ' + dbo.GetDepName(RSF.Link_Organization, RSF.Begin_Date) + ' Для бюджета: ' + ISNULL((select top 1 Name from kl_budg_type K where K.Link = RSF.Link_Type_Svod),'') as name
			from Report_Saved_Forms RSF left join report_forms RF on RSF.Link_Form = RF.Link_Form
			where Link_Saved_Form in (select LinkSF from #A) and IsRO = 3
			order by name
	end

	declare @t_LSF_send_mail table (LSF int, St tinyint)
	declare @LSF int, @Status tinyint, @EMail varchar(254), @Subject varchar(254), @Body varchar(8000), @Template varchar(8000)

	if (select top 1 Not_vkl_v_svod from dbo.I_REPORT_OPTIONS_COMMON) = 1 -- устанавливать статус "включать в свод"
	begin
		insert @t_LSF_send_mail (LSF, St)
		select Link_Saved_Form, IsRO
		from dbo.report_saved_forms RSF join #A A on RSF.Link_Saved_Form = A.LinkSF
		where IsRO not in (2, 4) and RSF.Link_Organization <> @varKSLinkOrg

		update Report_Saved_Forms
		set IsRO = 2
		where Link_Saved_Form in (select LinkSF from #A) --and IsRO = 1 -- еще должен быть готовым ко своду
		and IsRO <> 4

	end
	if (select top 1 Not_vkl_v_svod from dbo.I_REPORT_OPTIONS_COMMON) = 2 -- устанавливать статус "включать в свод", если все отчеты "проверены"
	begin
		if not exists(select * from Report_Saved_Forms where Link_Saved_Form in (select LinkSF from #A) and (IsRO = 0 or IsRO = 1 or IsRO = 3))
		begin
			insert @t_LSF_send_mail (LSF, St)
			select Link_Saved_Form, IsRO
			from dbo.report_saved_forms RSF join #A A on RSF.Link_Saved_Form = A.LinkSF
			where IsRO not in (2, 4) and RSF.Link_Organization <> @varKSLinkOrg

			update Report_Saved_Forms
			set IsRO = 2
			where Link_Saved_Form in (select LinkSF from #A) --and IsRO = 1 -- еще должен быть готовым ко своду
			and IsRO <> 4
		end
	end

	-- отправляем письма о смене статуса
	exec dbo.X_GET_OPTION 'RO_MAIL_NASTR_TEMPLATE',0,@Template output

	declare cur_LSF_sent_email cursor local static
	for select LSF, St from @t_LSF_send_mail

	open cur_LSF_sent_email

	fetch next from cur_LSF_sent_email
	into @LSF, @Status

	while @@fetch_status = 0
	begin
		select @EMail = '',  @Subject = '', @Body = ''
		select	@EMail = EMail, @Subject = 'У отчета ' + rtrim(RF.code) + ' стал статус "' + SN.Status_Name + '"',
			@Body = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Template,'[Код формы]', RTRIM(RF.code)),
																								'[Наименование формы]', RTRIM(RF.Name)),
																								'[Атрибут]', RTRIM(ISNULL(atr,''))),
																								'[Период]', 			case period_Type when 2 then convert(char(1),period_number) + ' квартал '
																															when 4 then convert(char(2),period_number) + ' месяц '
																														ELSE '' end + convert(char(4),year(BEGIN_DATE)) + ' год '),
																								'[Организация]', RTRIM(dbo.GetDepName(RSF.Link_Organization, RSF.begin_date))),
																								'[Бюджет]', isnull(RTRIM(B.Name),'')), 
																								'[Версия]', convert(char(3),RSF.version)),
																								'[Старый статус]', SO.Status_Name),
																								'[Новый статус]', SN.Status_Name),
																								'[Время]', convert(varchar(20), getdate(), 113)),
																								'[Комментарий формы]', '[Комментарий формы]~' + LTRIM(STR(rsf.[Link_Saved_Form])) + '~'),
																								'[Пользователь]', SUSER_SNAME(SUSER_SID()) + ' ' + isnull(dbo.AdminGetUserFIO(dbo.AdminGetUidBySID(SUSER_SID())),''))																					
		from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
				left join departments D on D.link = RSF.link_organization 
				left join kl_budg_type B on B.link = RSF.link_type_svod
				left join report_status SO on @Status = SO.status
				left join report_status SN on SN.status = RSF.IsRO
		where link_saved_form = @LSF

		if isnull(@EMail, '') <> ''
			exec dbo.RO_MAIL_SEND @EMail, @Subject, @Body 

		fetch next from cur_LSF_sent_email
		into @LSF, @Status
	end
	
	deallocate cur_LSF_sent_email

	-- теперь выводим организации и бюджеты, у которых нет отчетов
	declare @t_budg table (code varchar(20), name varchar(250))


	insert @t_org_budg (orders, code, name)
	select 1, D.code, T.name_org
	from dbo.DEPARTMENTS D join dbo.ro_svod_tree T on D.link = link_report_org and T.link_self = @varKSLinkTreeSvod
	where	(@varKSiSvod = 0 or D.link <> @LINK_REPORT_ORG)
		and D.link not in (select link_organization from report_saved_forms where link_saved_form in (select LinkSF from #A))

	IF exists(select * from @t_org_budg where orders=1)
	insert @t_org_budg (orders, code, name)
			values(0, '       ', 'Нет сохраненных отчетов для организаций:')

	insert @t_budg (code, name)
	select code, name
	from dbo.BI_DICTION_BUDG_TYPE
	where	isnull(link,0) in (select isnull(link_report_budg,0) from dbo.ro_svod_tree where link_self = @varKSLinkTreeSvod or link = @varKSLinkTreeSvod)
		and (isnull(link,0) <> isnull(@LINK_REPORT_BUDG, 0))
		and isnull(link,0) not in (select isnull(link_type_svod,0) from report_saved_forms where link_saved_form in (select LinkSF from #A))

	if exists(select * from @t_budg)
	begin

		insert @t_org_budg (orders, code, name)
		select 2, '    ', '              '

		insert @t_org_budg (orders, code, name)
		select 3, '    ', '    Бюджеты:'
		
		insert @t_org_budg (orders, code, name)
		select 4, code, name
		from @t_budg order by name
	END
   
   ---------------------------------------------------------------------
   -- в протокол свода добавляем организации и бюджеты у которых пустые отчеты
   DECLARE @t_LSF_not_data TABLE (lsf INT)
   
   INSERT @t_LSF_not_data (lsf)
   select LinkSF 
   from #A
   WHERE NOT EXISTS(SELECT TOP 1 * FROM dbo.[REPORT_SUMMA_ALL] rsa WHERE rsa.[LINK_SAVED_FORM] = #A.[LinkSF] AND rsa.[SUMMA] <> 0)
        AND NOT EXISTS(SELECT TOP 1 * FROM dbo.[REPORT_DINAMICS_ALL] rd WHERE rd.[LINK_SF] = #A.[LinkSF] AND (rd.[FLOAT_VAL] <> 0 OR rd.[STR_VAL] <> ''))
         
   IF EXISTS(SELECT TOP 1 * FROM @t_LSF_not_data)
   BEGIN
	   insert @t_org_budg (orders, code, name)
	   select 22, D.code, T.name_org
	   from dbo.DEPARTMENTS D join dbo.ro_svod_tree T on D.link = link_report_org and T.link_self = @varKSLinkTreeSvod
	   where	D.link <> @LINK_REPORT_ORG and D.link in (select link_organization from report_saved_forms rsf JOIN @t_LSF_not_data t ON rsf.[Link_Saved_Form] = t.[lsf])

      IF @@ROWCOUNT > 0
      BEGIN 
	      insert @t_org_budg (orders, code, name)
			      values(20, '', '')
	      insert @t_org_budg (orders, code, name)
			      values(21, '       ', 'Нет данных в отчетах для организаций:')
      END 

	   insert @t_org_budg (orders, code, name)
	   select 25, B.code, B.name
	   from dbo.BI_DICTION_BUDG_TYPE B
	   where	isnull(link,0) <> isnull(@LINK_REPORT_BUDG,0) and isnull(B.link,0) in (select isnull(link_type_svod, 0) from report_saved_forms rsf JOIN @t_LSF_not_data t ON rsf.[Link_Saved_Form] = t.[lsf])

      IF @@ROWCOUNT > 0
      BEGIN
	      insert @t_org_budg (orders, code, name)
			      values(23, '', '')
          
	      insert @t_org_budg (orders, code, name)
			      values(24, '       ', 'Нет данных в отчетах для бюджетов:')
      END                
      
   END         
         
   

--	select code, name from dbo.DEPARTMENTS where (type = 2 or type = 4) and link not in (select link_organization from report_saved_forms where link_saved_form in (select LinkSF from #A))

	DROP TABLE #A
	DECLARE @lcOrgEvent VARCHAR(100)
	Set @lcOrgEvent = ''
	Select @lcOrgEvent = '; Организация: ' + LTRIM(RTRIM(CODE)) + ' ' + Left(LTRIM(RTRIM(dbo.getDepName(@varKSLinkOrg,@varKSBDAte))),60) + ';'
	From Departments Where link = @varKSLinkOrg

	Set @lcOrgEvent = @lcOrgEvent + 'Бюджет: ' + 
		rtrim(isnull((select Name from kl_budg_type where link = @varKSLinkTypeSvod), '-')) + ';'
	
	DECLARE @varKSLink_Task	int,
		@varKSEventStr	varchar(8000)
	select @varKSLink_Task = link_task from user_info
	select @varKSEventStr = 'Форма: ' + rtrim(code) + @lcOrgEvent + ' Период: ' + 
		(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),RSF.version)
	from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form where link_saved_form = @varKSLinkSF
	if @bMode = 0
		exec RO_GENERATEEVENT 'Расчет сводного отчета', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSLinkSF
	else 
	begin
		exec RO_GENERATEEVENT 'Перерасчет сводного отчета', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSLinkSF
	-- сохраним ссылку на журнал в форме
		set @varKSLink_last_event = @@identity 
		update dbo.REPORT_saved_forms
		SET link_jurnal = @varKSLink_last_event
		where link_saved_form = @varKSLinkSF
	end
	
	declare @Protokol varchar(4000)
	set @Protokol = ''
	select @Protokol = left(@Protokol + RTRIM(Code) + ' ' + RTRIM(Name) + CHAR(13),3950)
	from @t_org_budg
	order by orders

	update Report_Saved_Forms
	set IsRO = 0,
		modify_date = getdate()
	where Link_Saved_Form =@varKSLinkSF
   
    INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
    VALUES (@varKSLinkSF, SUSER_SID(), 'Свод:' + CHAR(13) + @Protokol)
    
   

if not exists(select top 1 * from @t_org_budg) -- обходим глюк в WEB
begin
	insert @t_org_budg
	values (1, '', '')
end

select code, name from @t_org_budg order by orders,code,name


RETURN 0




GO
GRANT ALL ON dbo.[I_REPORT_MAKE_FULL_SVOD_NEW] 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_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 INT,
	@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 = SUMMA_BASE0, @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(20),
	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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT *
           FROM dbo.[SYSOBJECTS]
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_CALC_BKS]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_CALC_BKS]
END
GO
/*******************************************************************************

   © Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- Процедура расчета из БКС.
-- Вход: @iLINK_SAVED_FORM           - Идентификатор отчета ([R_TASK].[LINK_TASK])
--  Табличные данные:
--#R_CALC_OPTION    (LINK_OPTION INT,
--        [VALUE_TYPE] TINYINT,     - тип значения: 0 - значения нет, 1 - число, 2 - дата, 3 - строка
--        [VALUE_INT]  INT,         - числовое значение (в том числе и идентификатор отбора), заполняется когда тип значения   [VALUE_TYPE] = 1
--        [VALUE_DATE] DATETIME,    - значение даты, заполняется когда тип значения       [VALUE_TYPE] = 2
--        [VALUE_TEXT] VARCHAR(MAX))- строковое значение, заполняется когда тип значения  [VALUE_TYPE] = 3
-- Коды ошибок:  0 - Нет ошибок. Успех;
--              -1 - Нет такой формы
CREATE PROCEDURE dbo.[RO_CALC_BKS]
   @intIS_NOT_CALC	TINYINT OUTPUT,
   @iLINK_SAVED_FORM       INT
AS
SET NOCOUNT ON

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,
      @vcDEP_INN  VARCHAR(20),
      @ldBeginYear    DATETIME 

IF @iLINK_SAVED_FORM IS NULL
BEGIN
   RETURN -1
END

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, DT_MASK VARCHAR(100), KT_MASK VARCHAR(100), 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_xor table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, DT_MASK VARCHAR(100), KT_MASK VARCHAR(100), dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint, oper varchar(1000))
   
CREATE TABLE #CALC_DATA ( KBK_DT       VARCHAR(50),
                          KBK_TYPE_DT  TINYINT,
                          ACC_DT       VARCHAR(50),
                          SGU_DT       CHAR(3),
                          EKR_DT       CHAR(3),
                          KBK_KT       VARCHAR(50),
                          KBK_TYPE_KT  TINYINT,
                          ACC_KT       VARCHAR(50),
                          SGU_KT       CHAR(3),
                          EKR_KT       CHAR(3),                          
                          DATE         DATETIME,
                          SUMMA        NUMERIC(20,2),
                          OPERS        VARCHAR(1000))
                             

CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
declare @t_Col table (Link_Col int, orderCol int)

declare @filter_kbk table (kbk varchar(20))
-----------------------------------------------------------------------------------------------------------
-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
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 = @iLINK_SAVED_FORM

SET @ldBeginYear = @ldBegin

IF OBJECT_ID('tempdb..#R_CALC_OPTION') IS NOT NULL
BEGIN
   SELECT @dCALC_DATE = VALUE_DATE FROM #R_CALC_OPTION O JOIN dbo.[R_CALC_OPTION] rco ON O.LINK_OPTION = rco.[LINK_OPTION] WHERE rco.[CODE] = 'END_DATE'
   SELECT @ldBegin = VALUE_DATE FROM #R_CALC_OPTION O JOIN dbo.[R_CALC_OPTION] rco ON O.LINK_OPTION = rco.[LINK_OPTION] WHERE rco.[CODE] = 'BEGIN_DATE'
   SET @ldEnd = @dCALC_DATE + 1

END
      
SELECT @vcDEP_INN = INN
FROM   dbo.[DEPARTMENTS] d
WHERE  d.[LINK] = @iDEP_LINK

--- Поиск расчета по заданным атрибутам ---
SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLINK_SAVED_FORM, 0)


if @iLinkCalcForm is null 
BEGIN
	SET @intIS_NOT_CALC = 1
	RETURN 0
END

SET @intIS_NOT_CALC = 0

insert @t_Col (Link_Col, orderCol)
select Link_Col, Export_Order
from report_coloumns RC
join report_tables RT on RC.Link_Table = RT.Link_Table
where RT.Link_Form = @LF

--- Удаление старых записей ---
DELETE FROM dbo.REPORT_DINAMICS WHERE LINK_SF = @iLINK_SAVED_FORM

SET @ADM_CODE = dbo.rn_get_atr_value(@iLINK_SAVED_FORM,'REPORTS_ATR_ADM')
IF isnull(@ADM_CODE, '') <> ''
BEGIN 
   insert @filter_kbk (kbk)   
   Select @ADM_CODE
   set @nabor_filter = 'REPORTS_ATR_ADM'
END 
---------------------------------------------------------------------------------------------------------
----- ЧИТАЕМ ДАННЫЕ ПРОВОДОК

EXEC DBO.RO_CALC_READ_DATA @ldBeginYear, @ldEnd, @vcDEP_INN

----------------------------------------------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	CASE WHEN CR.DT_Mask = '' THEN '%' ELSE REPLACE(rtrim (CR.DT_Mask), '.', '') END, 
   CASE WHEN CR.KT_Mask = '' THEN '%' ELSE REPLACE(rtrim (CR.KT_Mask), '.', '') END , 
   dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt, cr.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	AND [sign] in (1,2)  

-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], 
	REPLACE(rtrim (CR.DT_Mask) + '%', '.', ''), 
   REPLACE(rtrim (CR.KT_Mask) + '%', '.', ''), 
      dt_ekr, kt_ekr, [type], type_kbk, dt_kt, cr.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
	AND [sign] = 3

----------------------------------------------------------------------
-- РАССЧИТЫВАЕМ
-- 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( CASE WHEN TMP.dt_kt = 0 THEN KBK_DT ELSE KBK_KT END,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(CASE WHEN TMP.dt_kt = 0 THEN ACC_DT ELSE ACC_KT END,'.',''),'') + '000000', 6)
			+ LEFT(ISNULL(case dt_kt when 0 then SGU_DT else SGU_KT END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then EKR_DT else EKR_KT END, '') + '000', 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	SUM(CASE [SIGN] WHEN 1 THEN CASE WHEN D.ACC_DT LIKE TMP.DT_MASK AND D.ACC_KT LIKE TMP.KT_MASK THEN D.SUMMA ELSE -D.SUMMA END  WHEN 2 THEN -CASE WHEN D.ACC_DT LIKE TMP.DT_MASK AND D.ACC_KT LIKE TMP.KT_MASK THEN D.SUMMA ELSE -D.SUMMA END  ELSE 0 END), 
	TMP.Calc_Order
FROM #CALC_DATA D
   INNER JOIN @TEMP_NASTR TMP ON (D.ACC_DT LIKE TMP.DT_MASK AND D.ACC_KT LIKE TMP.KT_MASK) OR (TMP.Type IN (2,3) AND D.ACC_DT LIKE TMP.KT_MASK AND D.ACC_KT LIKE TMP.DT_MASK)
	                              AND (dbo.RO_LIKE_LIST(D.SGU_DT, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
	                              AND (dbo.RO_LIKE_LIST(D.SGU_KT, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')
	                              AND (dbo.RO_LIKE_LIST(D.EKR_DT, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
                                 AND (dbo.RO_LIKE_LIST(D.EKR_KT, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')
--LEFT JOIN @filter_kbk F on KBK.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
WHERE (',' + RTRIM(LTRIM(D.OPERS)) + ',' like '%,' + LTRIM(RTRIM(TMP.OPER)) + ',%' or TMP.OPER = '') 
--( ',' + RTRIM(TMP.OPER) + ',' like '%,' + RTRIM(D.OPERS) + ',%' OR TMP.Oper = '')
       and  ((TMP.Type = 1 and D.DATE >= @ldBegin AND D.DATE < @ldEnd) OR (TMP.Type = 3  and D.DATE >= @ldBeginYear AND D.Date < @ldEnd)  OR (TMP.Type = 2  and D.DATE = @ldBeginYear))
--	AND (F.kbk IS NOT NULL
--		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & CASE WHEN TMP.dt_kt = 0 THEN D.KBK_TYPE_DT ELSE D.KBK_TYPE_KT END) / (CASE WHEN TMP.dt_kt = 0 THEN D.KBK_TYPE_DT ELSE D.KBK_TYPE_KT END) = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link
				and D.ACC_DT LIKE xor.DT_MASK AND D.ACC_KT LIKE xor.KT_MASK 
            AND ',' + RTRIM(D.OPERS) + ',' like '%,' + RTRIM(Xor.OPER) + ',%' 
				and CHARINDEX(RTRIM(SGU_DT), xor.dt_ekr) > 0					
				and CHARINDEX(RTRIM(SGU_KT),xor.kt_ekr) > 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( CASE WHEN TMP.dt_kt = 0 THEN KBK_DT ELSE KBK_KT END,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(CASE WHEN TMP.dt_kt = 0 THEN ACC_DT ELSE ACC_KT END,'.',''),'') + '000000', 6)
			+ LEFT(ISNULL(case dt_kt when 0 then SGU_DT else SGU_KT END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then EKR_DT else EKR_KT END, '') + '000', 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	TMP.Calc_Order


---------------------------------------------------------------------
-- СОХРАНЯЕМ ДАННЫЕ В ОТЧЕТ
-- динамическая таблица
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 SUMMA = 0

UPDATE #tTemp SET KBK = REPLACE (KBK, '#', '')

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 = @iLINK_SAVED_FORM 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 @iLINK_SAVED_FORM, 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 = @iLINK_SAVED_FORM 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 = @iLINK_SAVED_FORM
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 @iLINK_SAVED_FORM, 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 = @iLINK_SAVED_FORM 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 ALL ON dbo.[RO_CALC_BKS] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--EXEC dbo.[RA_ERROR_DELETE] 'RO_CALC'
--EXEC dbo.[RA_ERROR_UPDATE] 'RO_CALC',0,'Нет ошибок. Успех.',0
--EXEC dbo.[RA_ERROR_UPDATE] 'RO_CALC',-1,'Не найдена форма',0

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_PERS_CARD_ESN_10]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_PERS_CARD_ESN_10]

GO
CREATE PROC [dbo].[SA_PERS_CARD_ESN_10] (@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)

IF @LINK_EMPL IS NOT NULL
	SET @LINK_PERSON = ISNULL((SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @LINK_EMPL),0)

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)
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	 
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
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 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)
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)
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
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)
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
	T1.[OBJECT] =(select TOP 1 LINK from s_objects where code = 'DOCUMENTS_DGH_T1')
	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 '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 NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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


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( 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 '115', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '113'

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', '109', '111')

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '119',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 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 '121',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 1 AND E = 0 AND MONTH_BASE = 12) ,0)	

INSERT INTO #RES VALUES ('123', 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 '125',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 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 '129',
	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 '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)	

---<<<<<< Конец По общему тарифу >>>>>>>>>


---<<<<<< По тарифу инвалидов >>>>>>>>>
--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 '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 Федерального закона
	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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

	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( 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', '311')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '315', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '313'

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '317',
		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', '311')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '319',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 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 '321',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND I = 2 AND MONTH_BASE = 12) ,0)	

	INSERT INTO #RES VALUES ('323', 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 '325',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 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 = 4 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 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 '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 '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 Федерального закона
	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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 THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT 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

	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( 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', '511')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '515', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '513'

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '517',
		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', '511')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '519',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 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 '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 VALUES ('523', 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 '525',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 3 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 '529',
		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		
---<<<<<< Конец По общему тарифу >>>>>>>>>

	
--Суммы с начала года
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

---
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
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)
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)

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,
	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),0),
	OPS_NC = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 7),0),
	OPS_D = 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)
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_ESN2') IS NOT NULL
	DROP TABLE #SPR_ESN2

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_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..#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_10] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_725]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_725]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_725]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
DECLARE @tabHead TABLE ([TXT]   VARCHAR(1000), 
                        [ORDER] INT)                                 

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
      INSERT @tabHead (TXT)
      SELECT TXT
      FROM #IMPORT_TABLE
      WHERE [ORDER]  < (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT LIKE 'ОКАТО=%')
            AND [ORDER]  < (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT LIKE 'КСБУ=%')
      ORDER BY [ORDER]
   
      INSERT @tabImport(TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER]  >= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT LIKE 'ОКАТО=%')
            OR [ORDER]  >= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT LIKE 'КСБУ=%')
      ORDER BY [ORDER]
      
      WHILE EXISTS(SELECT * FROM @tabImport)
      BEGIN  
         TRUNCATE TABLE #IMPORT_TABLE

         INSERT #IMPORT_TABLE ([TXT])
   	   SELECT TXT
		   FROM @tabHead
		   ORDER BY [ORDER]
         
         SET @iOrder =  (SELECT MIN([ORDER]) FROM @tabImport WHERE TXT LIKE 'ОКАТО=%')
         IF @iOrder > (SELECT MIN([ORDER]) FROM @tabImport WHERE TXT LIKE 'КСБУ=%')
            SET @iOrder = (SELECT MIN([ORDER]) FROM @tabImport WHERE TXT LIKE 'КСБУ=%')

         INSERT #IMPORT_TABLE ([TXT])
   	   SELECT TXT
		   FROM @tabImport
         WHERE [ORDER] >= @iOrder
               AND ([ORDER]  < ISNULL((SELECT MIN([ORDER]) FROM @tabImport WHERE TXT = '#%' AND [ORDER] > @iOrder + 1),(SELECT MIN([ORDER]) FROM @tabImport WHERE TXT = '#&' AND [ORDER] > @iOrder + 1)))               
		   ORDER BY [ORDER]

         INSERT #IMPORT_TABLE ([TXT])
   	   SELECT TXT
		   FROM @tabImport
         WHERE [ORDER] >= (SELECT MIN([ORDER]) FROM @tabImport WHERE TXT = '#&')
         
         DELETE @tabImport
         WHERE  [ORDER] >= @iOrder
               AND [ORDER] <=  ISNULL((SELECT MIN([ORDER]) FROM @tabImport WHERE TXT = '#%' AND [ORDER] > @iOrder + 1),(SELECT MIN([ORDER]) FROM @tabImport WHERE TXT = '#&' AND [ORDER] > @iOrder + 1))
               
         UPDATE #IMPORT_TABLE
         SET TXT = REPLACE(TXT, '*****|***|**************|*|*****|***|*|*****|***|', '00000|000|00000000000000|0|00000|000|0|00000|000|')
         WHERE TXT LIKE '%*****|***|**************|*|*****|***|*|*****|***|%'

         UPDATE #IMPORT_TABLE
         SET TXT = REPLACE(TXT, '|*|*****|***|', '|0|00000|000|')
         WHERE TXT LIKE '%|*|*****|***|%'
               
         UPDATE #IMPORT_TABLE                      
         SET TXT = dbo.[RA_GETWORDNUM](TXT, 4, '|') + dbo.[RA_GETWORDNUM](TXT, 5, '|') + dbo.[RA_GETWORDNUM](TXT, 6, '|')
                     + '|' +  dbo.[RA_GETWORDNUM](TXT, 10, '|') + '|' +  dbo.[RA_GETWORDNUM](TXT, 11, '|')
                     + '|' + dbo.[RA_GETWORDNUM](TXT, 7, '|') + dbo.[RA_GETWORDNUM](TXT, 8, '|') + dbo.[RA_GETWORDNUM](TXT, 9, '|') 
                     + '|00000000' +  dbo.[RA_GETWORDNUM](TXT, 7, '|') + dbo.[RA_GETWORDNUM](TXT, 8, '|') + dbo.[RA_GETWORDNUM](TXT, 9, '|') + dbo.[RA_GETWORDNUM](TXT, 4, '|') + dbo.[RA_GETWORDNUM](TXT, 5, '|') + dbo.[RA_GETWORDNUM](TXT, 6, '|')
                     + CASE WHEN dbo.[RA_GETWORDNUM](TXT, 7, '|') + dbo.[RA_GETWORDNUM](TXT, 8, '|') + dbo.[RA_GETWORDNUM](TXT, 9, '|') = '000000000' AND dbo.[RA_GETWORDNUM](TXT, 4, '|') + dbo.[RA_GETWORDNUM](TXT, 5, '|') + dbo.[RA_GETWORDNUM](TXT, 6, '|') <> '000000000'
                                 THEN 'ИП'
                              WHEN dbo.[RA_GETWORDNUM](TXT, 8, '|') IN ('21002','30405') or dbo.[RA_GETWORDNUM](TXT, 9, '|') in ('510','610') 
                                 THEN 'ДР'
                              WHEN dbo.[RA_GETWORDNUM](TXT, 4, '|') + dbo.[RA_GETWORDNUM](TXT, 5, '|') + dbo.[RA_GETWORDNUM](TXT, 6, '|') <> '000000000'
                                 THEN 'НР'
                        ELSE ''
                      END                                                 
         WHERE TXT LIKE '%|%'
         
         IF NOT EXISTS(SELECT * FROM @tabImport WHERE TXT LIKE '%|%')
               DELETE @tabImport
               
         EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                        @liRepeatRequest,
                                                        @tIsAppend,
                                                        @bDinamicRows,
                                                        @iLINK_SELF,
                                                        @tMode
      END 

END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_725] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS OFF
GO
SET LOCK_TIMEOUT -1
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_GET_CUBE_SELECT_ANL_EKR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_GET_CUBE_SELECT_ANL_EKR]
GO

CREATE procedure [dbo].[RT_GET_CUBE_SELECT_ANL_EKR]
AS

SET NOCOUNT ON;

declare @link_cube int,
		@link_struct int,
        @type tinyint,
        @name varchar(254),
        @cSQL_body varchar(8000),
        @cSQL_list varchar(8000),
        @cSQL_join varchar(8000),
        @cSQL varchar(8000),
        @nn int,
        @nn1 int,
        @nn2 int,
        @base_period_type tinyint,
        @base_period_number tinyint,
        @base_period_date datetime,
        @period_type tinyint,
        @period_number tinyint,
        @period_date datetime,
        @col_counter int,
		@num_tab int,
		@num_col int,
        @tab_name varchar(254),
        @col_name varchar(254),
        @period_name varchar(254),
        @code_form varchar(50),
        @m1_begin int,
        @m1_end int,
        @m2_begin int,
        @m2_end int,
		@a1_sql varchar(8000),
		@a2_sql varchar(8000),
		@a3_sql varchar(8000),
		@a1_flg int,
		@a2_flg int,
		@cSQL_header varchar(8000),
		@cSQL_list_1 varchar(8000),
		@cSQL_list_2 varchar(8000),
		@cSQL_list_3 varchar(8000),
		@cSQL_list_4 varchar(8000),
		@cSQL_list_5 varchar(8000),
		@cSQL_join_1 varchar(8000),
		@cSQL_join_2 varchar(8000),
		@cSQL_join_3 varchar(8000),
		@cSQL_join_4 varchar(8000),
		@cSQL_join_5 varchar(8000),
		@cSQL_join_6 varchar(8000),
		@cSQL_join_7 varchar(8000),
		@cSQL_join_8 varchar(8000),
		@cSQL_join_9 varchar(8000),
		@cSQL_join_10 varchar(8000),
		@nCnt int,
		@is_bok_name tinyint,
		@nRowCount int

set @link_cube = -1
if exists(select * from #report_store_cube_data)begin

	exec DropTempTable '#report_store_cube_struct1'	
    create table #report_store_cube_struct1(nn int identity(1,1), link_cube int, link_col int, orders int, [type] tinyint, [name] varchar(254))
    insert into #report_store_cube_struct1(link_cube, link_col, orders, [type], [name])
    select link_cube, link_col, orders, [type], [name] from #report_store_cube_struct

    set @link_struct = isnull((select top 1 link_col from #report_store_cube_struct where [type] = 0),0)
    select top 1 @code_form = code_form from #report_store_cube_data where link_struct = @link_struct
    ------------------------------------------
	exec DropTempTable '#table'	
    create table #table (nn int identity(1,1), num_tab int)
	insert into #table (num_tab) select cast(num_tab as int) from #report_store_cube_data where link_struct = @link_struct group by num_tab order by num_tab

	exec DropTempTable '#column'	
    create table #column (nn int identity(1,1), num_tab int, num_col int)
	insert into #column (num_tab, num_col) select cast(num_tab as int), cast(num_col as int) from #report_store_cube_data where link_struct = @link_struct group by num_tab, num_col order by num_tab, num_col

	exec DropTempTable '#periodth'	
    create table #periodth (nn int identity(1,1), period_type tinyint, period_number tinyint, period_date datetime)
	insert into #periodth (period_type, period_number, period_date) select period_type, period_number, period_date from #report_store_cube_data group by period_date, period_type, period_number order by period_date, period_type, period_number

	exec DropTempTable '#merg_cell'	
    create table #merg_cell (nn int identity(1,1), RB int, CB int, RE int, CE int)
    
	exec DropTempTable '#width_col'	
    create table #width_col (nn int identity(1,1), COL int, WIDTH numeric(20,2))

	exec DropTempTable '#paint_cell'	
    create table #paint_cell (nn int identity(1,1), RB int, CB int, RE int, CE int, [TYPE] tinyint)
    
    exec DropTempTable '#SQL_Querys'
    create table #SQL_Querys (nn int identity(1,1), [type] tinyint, [sql] varchar(8000), [len] int)
    
    exec DropTempTable '#bokovig'
    create table #bokovig(nn int identity(1,1), num_tab int, code_row varchar(50), str_val varchar(8000), [name] varchar(8000))
	create nonclustered index ixz1 on #bokovig (num_tab,code_row)
    insert into #bokovig (num_tab, code_row, str_val, [name]) 
    select A.num_tab, A.code_row, A.str_val, B.name 
	from
		(select num_tab as num_tab, code_row as code_row, str_val as str_val from #report_store_cube_data where link_struct in (select link_col from #report_store_cube_struct where name = 'Боковик') group by num_tab, code_row, str_val) as A
	left join		
		(select num_tab as num_tab, right(rtrim(code_row),3) as code_row, max(str_val) as [name] from #report_store_cube_data where link_struct in (select link_col from #report_store_cube_struct where name = 'Наименование') group by num_tab, right(rtrim(code_row),3)) as B
	on A.code_row = B.code_row AND B.code_row <> '000'
	and A.num_tab = B.num_tab
	order by A.num_tab, A.code_row
   
--return

	select @nRowCount = max(nn) from #bokovig

    insert into #width_col (COL, WIDTH) select 1, case when max(len(str_val)) > 50 then 50 else max(len(str_val))+1 end from #bokovig
--	if exists(select * from #report_store_cube_data where link_struct = (select top 1 link_col from #report_store_cube_struct where [type] = 2)) begin
		set @is_bok_name = 1
	    insert into #width_col (COL, WIDTH) select 2, case when max(len([name])) > 50 then 50 else max(len([name])) end from #bokovig
--	end
--	else
--		set @is_bok_name = 0

	select @base_period_type = period_type, @base_period_number = period_number, @base_period_date = period_date from #periodth where nn = (select max(nn) from #periodth)
	set @col_counter = 0
	set @a1_sql = 'select 1 as nn, '''' as b1,'+case @is_bok_name when 0 then '' else ''''' as b2,' end
	set @a2_sql = 'select 2 as nn, ''ЭКР'' as b1,'+case @is_bok_name when 0 then '' else '''Наименование'' as b2,' end
	set @cSQL_header ='select b1,'+case @is_bok_name when 0 then '' else 'b2,' end
    set @cSQL_body = ' from #bokovig as [key] '
	set @cSQL_list = ''
	set @cSQL_join = ''

	while exists(select * from #table) and @col_counter < 251 begin
		select top 1 @nn = nn, @num_tab = num_tab from #table
	    select @tab_name = [name] from dbo.report_tables where orders = @num_tab and link_form = (select top 1 link_form from dbo.report_forms where code = @code_form and [Start_Date] <= @base_period_date and (End_Date is null or End_Date >= @base_period_date))
		set @m1_begin = @col_counter + @is_bok_name + 2
		set @a1_flg = 0
		----------------------------------------------------------------
		set @nn1 = 1
		while exists(select * from #column where num_tab = @num_tab and nn >= @nn1) and @col_counter < 251 begin
			select top 1 @nn1 = nn, @num_col = num_col from #column where num_tab = @num_tab and nn >= @nn1
		    select @col_name = [name] from dbo.report_coloumns where orders = @num_col and link_table = (select link_table from dbo.report_tables where orders = @num_tab and link_form = (select top 1 link_form from dbo.report_forms where code = @code_form and [Start_Date] <= @base_period_date and (End_Date is null or End_Date >= @base_period_date)))
			set @m2_begin = @col_counter + @is_bok_name + 2
			set @a2_flg = 0
			----------------------------------------------------------------
			set @col_counter = @col_counter + 1 
			set @cSQL_header = @cSQL_header + 'A.col'+ltrim(rtrim(str(@col_counter))) + ','
			-- формирование шапки
			set @a1_sql = @a1_sql + case @a1_flg when 0 then '''' + rtrim(@tab_name) + '''' else '''''' end + ' as col'+ltrim(rtrim(str(@col_counter))) + ','
			set @a1_flg = 1
			set @a2_sql = @a2_sql + case @a2_flg when 0 then '''' + rtrim(@col_name) + '''' else '''''' end + ' as col'+ltrim(rtrim(str(@col_counter))) + ','
			set @a2_flg = 1
			-- конец формирования шапки
			set @cSQL_list = ''
			set @cSQL_list = ',S'+ltrim(rtrim(str(@col_counter)))+'.float_val as col'+ltrim(rtrim(str(@col_counter)))
			insert into #SQL_Querys ([type], [sql], [len]) values (0,rtrim(@cSQL_list),len(@cSQL_list))
			
			set @cSQL_join = ''
			set @cSQL_join = ' left join (select num_tab, code_row, float_val from #report_store_cube_data where link_struct = '+rtrim(cast(@link_struct as varchar))+' and num_tab = '+rtrim(ltrim(str(@num_tab)))+' and num_col = '+rtrim(ltrim(str(@num_col)))+') as S'+ltrim(rtrim(str(@col_counter)))+' on [key].code_row = S'+ltrim(rtrim(str(@col_counter)))+'.code_row and [key].num_tab = S'+ltrim(rtrim(str(@col_counter)))+'.num_tab'
			insert into #SQL_Querys ([type], [sql], [len]) values (1,rtrim(@cSQL_join),len(@cSQL_join))

		    insert into #width_col (COL, WIDTH) values (@col_counter + @is_bok_name + 1, 20)
			----------------------------------------------------------------
			-- delete from #column where nn = @nn1
			set @nn1 = @nn1 + 1
			set @m2_end = @col_counter + @is_bok_name + 1
			insert into #merg_cell(RB, CB, RE, CE) values (2,@m2_begin,2,@m2_end)
		end
		----------------------------------------------------------------
		delete from #table where nn = @nn
		set @m1_end = @col_counter + @is_bok_name + 1
		insert into #merg_cell(RB, CB, RE, CE) values (1,@m1_begin,1,@m1_end)
	end
	----------------------------------------------------------------------------
	set @a1_sql = left(@a1_sql,len(@a1_sql)-1)
	set @a2_sql = left(@a2_sql,len(@a2_sql)-1)
	set @cSQL_header = left(@cSQL_header,len(@cSQL_header)-1)

	-- вывод шапки -------------------------------------------------------------
	execute(@cSQL_header+' from('+@a1_sql+' union '+@a2_sql+') as A order by A.nn')
	----------------------------------------------------------------------------
	select * from #merg_cell
	----------------------------------------------------------------------------
	set @nCnt = 0
	set @cSQL_list_1 = ''
	while exists(select * from #SQL_Querys where [type] = 0) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_list_1 = @cSQL_list_1 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 0
		delete from #SQL_Querys where nn = @nn
 	end
	set @cSQL_list_1 = 'select [key].str_val as str_val ' +case @is_bok_name when 0 then '' else ',[key].name as name ' end + rtrim(@cSQL_list_1)
	set @nCnt = 0
	set @cSQL_list_2 = ''
	while exists(select * from #SQL_Querys where [type] = 0) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_list_2 = @cSQL_list_2 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 0
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_list_3 = ''
	while exists(select * from #SQL_Querys where [type] = 0) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_list_3 = @cSQL_list_3 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 0
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_list_4 = ''
	while exists(select * from #SQL_Querys where [type] = 0) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_list_4 = @cSQL_list_4 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 0
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_list_5 = ''
	while exists(select * from #SQL_Querys where [type] = 0) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_list_5 = @cSQL_list_5 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 0
		delete from #SQL_Querys where nn = @nn
 	end
	--
	set @nCnt = 0
	set @cSQL_join_1 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_1 = @cSQL_join_1 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_2 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_2 = @cSQL_join_2 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_3 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_3 = @cSQL_join_3 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_4 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_4 = @cSQL_join_4 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_5 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_5 = @cSQL_join_5 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_6 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_6 = @cSQL_join_6 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_7 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_7 = @cSQL_join_7 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_8 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_8 = @cSQL_join_8 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_9 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_9 = @cSQL_join_9 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	set @nCnt = 0
	set @cSQL_join_10 = ''
	while exists(select * from #SQL_Querys where [type] = 1) and @nCnt < 7500 begin
		select top 1 @nn = nn, @cSQL_join_10 = @cSQL_join_10 + rtrim([sql]), @nCnt = @nCnt + [len] from #SQL_Querys where [type] = 1
		delete from #SQL_Querys where nn = @nn
 	end
	------------------------------------------------------------------------------------------------------------
	-- боковик + данные
	execute(@cSQL_list_1+@cSQL_list_2+@cSQL_list_3+@cSQL_list_4+@cSQL_list_5+@cSQL_body+@cSQL_join_1+@cSQL_join_2+@cSQL_join_3+@cSQL_join_4+@cSQL_join_5+@cSQL_join_6+@cSQL_join_7+@cSQL_join_8+@cSQL_join_9+@cSQL_join_10+' order by [key].nn')
	
	-- таблица раскраски ячеек
	select * from #paint_cell
	
	-- ширины столбцов
	select * from #width_col

	exec DropTempTable '#table'	
	exec DropTempTable '#column'	
	exec DropTempTable '#periodth'	
	exec DropTempTable '#report_store_cube_struct1'	
end

GO
grant execute on [dbo].[RT_GET_CUBE_SELECT_ANL_EKR] to public
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO
SET LOCK_TIMEOUT 30000
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_GET_DOC_FIELD_COLUMNS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_GET_DOC_FIELD_COLUMNS]
GO


-- получение child объектов
CREATE  PROCEDURE dbo.WEB_GET_DOC_FIELD_COLUMNS
	@obj_code VARCHAR(100), -- объект
	@prop_list VARCHAR(1000) = '', -- список получаемых свойств
	@cClass VARCHAR(100) = '', -- класс подобъекта
	@cOrder VARCHAR(100) = '', -- сортировка
	@nMode INT = 1, -- 1 (для контейнеров)
	@cWhere VARCHAR(200) = '', -- доп. Where
	@cTable VARCHAR(100) = '', -- таблица куда записывать (должна существовать),
    @lsf bigint=0

AS
SET NOCOUNT ON
-- Проверка для отчетности
--если передали REPORT_FORMS_TABLE, то заменим его на REPORT_SVOD

DECLARE @bSignReportReadOnly BIT
SET @bSignReportReadOnly = 0
IF EXISTS(SELECT * FROM dbo.report_sign WHERE lsf = @lsf) AND ISNULL((select val_int FROM dbo.[REPORT_OPTIONS] ro WHERE ro.[Razdel] = 'ECP' AND Code = 'ReportReadOnly'), 0) = 1
BEGIN
   SET @bSignReportReadOnly = 1
END 

IF RTRIM(@obj_code)='REPORT_FORMS_TABLES' 
        SET @obj_code='REPORT_SVOD'

set @obj_code=REPLACE(@obj_code, 'FORMRRO_EDIT', 'REPORT_SVOD')

 IF RTRIM(@obj_code)='-98'
    begin

       declare @mode int,@lf int
       create table #tmp_get_doc (code_atr varchar(50),atr_name varchar(250),str_val  varchar(250))
        IF @lsf<0 
            begin
                   set @Mode = convert(int, @lsf/4294967296)
                   set @lf= abs(@lsf - @Mode * 4294967296)
                   insert #tmp_get_doc  exec RN_GET_ATRIBUT_VALUES  0,@lf,1
            end
        else
            insert #tmp_get_doc  exec RN_GET_ATRIBUT_VALUES  @lsf,0,1

   		select  [class_name] = 'EDIT_FIELD_CLASS',
			[obj_code] = A.code_atr,
			[title] = A.atr_name,
			[visible] = isnull(dbo.get_val(A.code_atr,'VISIBLE',0),''),
			[field_data] = A.code_atr,
			0 as [orders],
			[EDITABLE] = case when @bSignReportReadOnly = 0 then 1 ELSE  0 end,
			[val_Type] = isnull(dbo.get_val(A.code_atr,'CONTROL_TYPE',0),''),
			[val_Len] = isnull(dbo.get_val(A.code_atr,'MAX_WIDTH',0),''),
			[dictionary] = isnull(dbo.get_val(A.code_atr,'DICTIONARY',0),''),
			[dictionary_columns_list] = isnull(dbo.get_val(A.code_atr,'DICTIONARY_COLUMNS_LIST',0),''),
			[dictionary_fields_list] =  isnull(dbo.get_val(A.code_atr,'DICTIONARY_FIELDS_LIST',0),''),
			[field_alias] =-98,
            [fixed] = 0
		from #tmp_get_doc A
      
    
      RETURN 1
   end 

IF (@obj_code like 'REPORT_FORMS_LIST %' and len(@obj_code) > len(rtrim('REPORT_FORMS_LIST')))
	or (@obj_code like 'REPORT_SVOD %' and len(@obj_code) > len(rtrim('REPORT_SVOD')))
	or (@obj_code like 'FORM14_EDIT %' and len(@obj_code) > len(rtrim('FORM14_EDIT')))
	or (@obj_code like 'REPORT_FORMS_TABLE_MONIT %' and len(@obj_code) > len(rtrim('REPORT_FORMS_TABLE_MONIT')))
	or (@obj_code like 'REPORT_FORMS_TABLES %' and len(@obj_code) > len(rtrim('REPORT_FORMS_TABLES ')))
BEGIN
	DECLARE @iLTable	int
	DECLARE @Fixed	    int --фиксированная колонка
    set @fixed=0
	SET @iLTable = 0
	SET @iLTable = convert(int, ltrim(right(@obj_code, len(@obj_code)-charindex(' ', @obj_code))))
IF @iLTable >0 
	BEGIN
       IF (select top 1 code from report_forms A where A.link_form=(select link_form from report_tables B where B.link_table=@iLTable)) not  in ('(72н)0503125','(72н)0503125М','(72н)425M','(72н)425')
            select @Fixed=min(orders) from report_coloumns (nolock) where link_table = @iLTable and col_type=0

		select link_col into #tmp_col from report_saved_forms_permissions where lsf=@lsf

		select  [class_name] = 'EDIT_FIELD_CLASS',
			[obj_code] = 'Col' + ltrim(convert(char(2),orders)),
			[title] = name,
			[visible] = case when Property&1=1 then 0 else 1 end,
			[field_data] = 'Col' + ltrim(convert(char(2),orders)),
			export_order as [orders],
			[EDITABLE] = case when @bSignReportReadOnly = 0 then isEdited & dbo.RO_AccessColByLink(Link_Col) & isnull((select 0 from #tmp_col A where A.link_col=B.link_col),1) ELSE 0 end, 
			[val_Type] = col_type,
			[val_Len] = val_len,
			[dictionary] = isnull(dictionary, ''),
			[dictionary_columns_list] = isnull(dictionary_columns_list, ''),
			[dictionary_fields_list] = isnull(dictionary_fields_list, ''),
         [dictionary_add_where] = '', --replace(isnull(dictionary_where, ''),'''', ''''''),
			[field_alias] = @iLTable,
         [input_mask],
         [dictionary_one_row] = convert(bit,(isnull(B.property,0)&256) /256),
            [fixed] = case when orders<@fixed then 1 else 0 end 
		from report_coloumns B (nolock)
		where link_table = @iLTable
     END
        RETURN 1
	END
	

--Виды графиков
IF @obj_code like 'KD_GRAPH_VID %' and len(@obj_code)>len('KD_GRAPH_VID')
BEGIN
	SET @obj_code = ltrim(rtrim(replace(@obj_code, 'KD_GRAPH_VID ', '')))
	exec dbo.WEB_GET_DOC_FIELD_COLUMNS 	@obj_code, @prop_list, @cClass,	@cOrder, @nMode, @cWhere, @cTable
	RETURN 1
END

-- Стандартная обработка
DECLARE @nObj INT
SELECT @nObj = dbo.obj_id(@obj_code)

IF (@cOrder = '')
BEGIN
	SET @cOrder = 'ORDERS'
	IF PATINDEX('%ORDERS%', @prop_list) = 0
	BEGIN
		IF @prop_list <> ''
			SELECT @prop_list = @prop_list + ',ORDERS'
	END
END
-- новая работа без верменных табличе:
CREATE TABLE #t1_wgdfc(object INT, obj_code VARCHAR(30), property INT, prop_code VARCHAR(30), class_name VARCHAR(30), path VARCHAR(1000), value VARCHAR(6000), orders int)
CREATE INDEX aaa ON #t1_wgdfc (obj_code, prop_code)
SET @prop_list = RTRIM(@prop_list)
IF @prop_list = ''
BEGIN 
   IF @nMode > 0
	   INSERT INTO #t1_wgdfc
	   SELECT ov.object, so.code,  ov.property, P.code, so2.[NAME], '', ov.[VALUE], SO.orders
	   FROM dbo.s_objects SO 
            JOIN dbo.s_property   P ON SO.link_self = @nObj
            JOIN dbo.object_values OV ON SO.[LINK] = OV.[OBJECT] AND P.[LINK] = OV.[PROPERTY]
            JOIN dbo.[S_OBJECTS] so2 ON so2.[LINK] = so.[LINK_CLASS] AND (@cClass like '%' + RTRIM(so2.code) + '%' OR @cClass = '')
   ELSE 
	   INSERT INTO #t1_wgdfc
	   SELECT ov.object, so.code,  ov.property, P.code, so2.[NAME], '', ov.[VALUE], SO.orders
	   FROM dbo.s_objects SO 
            JOIN dbo.s_property   P ON SO.link = @nObj
            JOIN dbo.object_values OV ON SO.[LINK] = OV.[OBJECT] AND P.[LINK] = OV.[PROPERTY]
            JOIN dbo.[S_OBJECTS] so2 ON so2.[LINK] = so.[LINK_CLASS] AND (@cClass like '%' + RTRIM(so2.code) + '%' OR @cClass = '')
END    
ELSE
BEGIN -- доработать с property:
   IF @nMode > 0
	   INSERT INTO #t1_wgdfc
	   SELECT ov.object, so.code,  ov.property, P.code, so2.[NAME], '', ov.[VALUE], SO.orders
	   FROM dbo.s_objects SO 
            JOIN dbo.s_property   P ON SO.link_self = @nObj AND @prop_list + ',' LIKE '%' +  RTRIM(P.code) + ',%'
            JOIN dbo.object_values OV ON SO.[LINK] = OV.[OBJECT] AND P.[LINK] = OV.[PROPERTY]
            JOIN dbo.[S_OBJECTS] so2 ON so2.[LINK] = so.[LINK_CLASS] AND (@cClass like '%' + RTRIM(so2.code) + '%' OR @cClass = '')
   ELSE 
	   INSERT INTO #t1_wgdfc
	   SELECT ov.object, so.code,  ov.property, P.code, so2.[NAME], '', ov.[VALUE], SO.orders
	   FROM dbo.s_objects SO 
            JOIN dbo.s_property   P ON SO.link = @nObj AND @prop_list + ',' LIKE '%' +  RTRIM(P.code) + ',%'
            JOIN dbo.object_values OV ON SO.[LINK] = OV.[OBJECT] AND P.[LINK] = OV.[PROPERTY]
            JOIN dbo.[S_OBJECTS] so2 ON so2.[LINK] = so.[LINK_CLASS] AND (@cClass like '%' + RTRIM(so2.code) + '%' OR @cClass = '')
END




--IF @cClass <> ''
--BEGIN
--	UPDATE #obj_list SET del_pr = 0 
--	FROM  #obj_list ol
--        INNER LOOP JOIN s_objects so ON (so.link = ol.link)
--        INNER HASH JOIN #Class cl ON (so.link_class = cl.link)
--  DELETE FROM #obj_list WHERE del_pr = 1
--END


IF EXISTS(SELECT * FROM #t1_wgdfc WHERE value LIKE '&&%')
BEGIN
	CREATE TABLE #tc_wgdfc(value VARCHAR(4000))
	CREATE TABLE #tc_wgdfc_cursor(ord INT DEFAULT(0), value VARCHAR(4000))
	DECLARE @cCmd NVARCHAR(4000), @cValue VARCHAR(4000), @nCnt INT, @nRowCount INT

	INSERT #tc_wgdfc_cursor (value)
	SELECT value FROM #t1_wgdfc WHERE value LIKE '&&%' GROUP BY value
	SELECT @nCnt = 0
	UPDATE #tc_wgdfc_cursor SET @nCnt = ord = @nCnt + 1
	SELECT @nRowCount = @@ROWCOUNT
	SELECT @nCnt = 1
	WHILE @nCnt <= @nRowCount
	BEGIN
		SELECT @cValue = value FROM #tc_wgdfc_cursor WHERE ord = @nCnt	
		SELECT @cCmd = SUBSTRING(@cValue, 3, 8000)			
--		PRINT (@cCmd)
		INSERT #tc_wgdfc (object, obj_code, property, prop_code, class_name, path, value)
		EXEC (@cCmd)
		SELECT @cCmd = value FROM #tc_wgdfc
		UPDATE #t1_wgdfc SET value = @cCmd WHERE value = @cValue
		TRUNCATE TABLE #tc_wgdfc
		SELECT @nCnt = @nCnt + 1
	END
END

IF @prop_list = ''
BEGIN
	SELECT object, obj_code, property, prop_code, class_name, path, value FROM #t1_wgdfc
	RETURN
END


-- Формирование колонок из выборки
DECLARE @sSql NVARCHAR(4000), @nStart INT, @nEnd INT, @cField VARCHAR(100), @cType VARCHAR(100)

SELECT @nStart = 0
SELECT @sSql = ''

WHILE CHARINDEX(',', @prop_list, @nStart) > 0
BEGIN
	SELECT @nEnd = CHARINDEX(',', @prop_list, @nStart+1)
	SELECT @cField = LTRIM(RTRIM(SUBSTRING(@prop_list, @nStart, @nEnd - @nStart)))
	SELECT @cType = UPPER(LTRIM(RTRIM(data_type))) FROM s_property WHERE code = @cField
	IF @sSql <> ''
		SET @sSql = @sSql + ','
	ELSE
		SET @sSql = 'SELECT class_name, t1.obj_code,'

	IF @cField = @cOrder AND @cType IN ('BIT','INT','SMALLINT','NUMERIC')
		SELECT @sSql = @sSql + '
(SELECT CONVERT(INT, value) FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') as ' + LTRIM(@cField)
	ELSE
--		SELECT @sSql = @sSql + '
--(SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') AS ' + LTRIM(@cField)
--
SELECT @sSql = @sSql + '
max(case when prop_code = ''' + LTRIM(@cField) + ''' then value else '''' end) AS ' + LTRIM(@cField)

	SELECT @nStart = @nEnd + 1
END

SELECT @cField = RTRIM(LTRIM(SUBSTRING(@prop_list, @nStart, len(@prop_list) - @nStart + 1)))
SELECT @cType = UPPER(LTRIM(RTRIM(data_type))) FROM s_property WHERE code = @cField

IF @cField = @cOrder AND @cType IN ('BIT','INT','SMALLINT','NUMERIC')
--SELECT @sSql = @sSql + ',
--convert(int, ISNULL((SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + '''), ORDERS)) AS ' + LTRIM(@cField)
SELECT @sSql = @sSql + ',
convert(int, ISNULL(MAX((case when prop_code = ''' + LTRIM(@cField) + ''' then value else NULL end)),ORDERS)) AS ' + LTRIM(@cField)
ELSE
SELECT @sSql = @sSql + ',
max(case when prop_code = ''' + LTRIM(@cField) + ''' then value else '''' end) AS ' + LTRIM(@cField)

--SELECT @sSql = @sSql + ',
--(SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') AS ' + LTRIM(@cField)

SELECT @sSql = @sSql + ' INTO #t2_wgdfc FROM #t1_wgdfc t1 group by class_name, t1.obj_code, orders ORDER BY orders'

IF @cTable <> ''
	SELECT @sSql = @sSql + '  INSERT ' + @cTable

SELECT @sSql = @sSql + ' SELECT * '

SELECT @sSql = @sSql + ' FROM #t2_wgdfc '

IF @cWhere <> ''
	SELECT @sSql = @sSql + 'WHERE ' + @cWhere

SELECT @sSql = @sSql + ' ORDER BY ' + @cOrder




--PRINT @sSql
EXEC sp_executesql @sSql


--SELECT * FROM #t1_wgdfc t1 ORDER BY orders SELECT *  FROM #t2_wgdfc WHERE VISIBLE & 2 > 0 OR VISIBLE & 32 > 0 ORDER BY ORDERS
select * from #t1_wgdfc
DROP TABLE #t1_wgdfc

--
--------------------------------------------------------------------------------------------------
----- старая работа со временными табличками:
--create table #Class (link int, code varchar(50))
--CREATE INDEX aaa ON #Class (link)
--create table #prop_list (link int)
--
--insert #prop_list(link)
--SELECT link FROM dbo.prop_id_m(@prop_list)
--insert #Class(link,Code)
--SELECT link, code  FROM dbo.obj_id_m(@cClass)
--
--CREATE TABLE #obj_list(link INT, del_pr INT DEFAULT 1, orders int)
--CREATE TABLE #t1_wgdfc(object INT, obj_code VARCHAR(30), property INT, prop_code VARCHAR(30), class_name VARCHAR(30), path VARCHAR(1000), value VARCHAR(6000), orders int)
--CREATE INDEX aaa ON #obj_list (link)
--CREATE INDEX aaa ON #t1_wgdfc (obj_code, prop_code)
--
--IF @nMode > 0
--	INSERT #obj_list(link, orders)
--  SELECT link, orders
--  FROM s_objects
--  WHERE link_self = @nObj
--ELSE 
--	INSERT #obj_list(link, orders)
--	select link, orders
--	from s_objects
--	where link = @nObj
--
--
--IF @cClass <> ''
--BEGIN
--	UPDATE #obj_list SET del_pr = 0 
--	FROM  #obj_list ol
--        INNER LOOP JOIN s_objects so ON (so.link = ol.link)
--        INNER HASH JOIN #Class cl ON (so.link_class = cl.link)
--  DELETE FROM #obj_list WHERE del_pr = 1
--END
--
--IF @prop_list = ''
--	INSERT INTO #t1_wgdfc
--	SELECT ov.object, '',  ov.property, '', '', '', NULL, ol.orders
--	FROM object_values ov
--		inner join #obj_list ol on ov.object = ol.link
--	--WHERE ov.object IN (SELECT link FROM #obj_list)
--ELSE
--BEGIN
--
--
--	INSERT INTO #t1_wgdfc
--	SELECT ov.object, '',  ov.property, '', '', '', NULL, ol.orders
--	FROM #obj_list ol
--		 inner join #prop_list pl on 1=1
--       INNER JOIN object_values ov ON (ov.object = ol.link) and (ov.property = pl.link)
--       --INNER JOIN #prop_list pl ON (ov.property = pl.link)
--END
--
--
--UPDATE #t1_wgdfc
--SET obj_code = so.code
--FROM #t1_wgdfc T1 INNER MERGE JOIN s_objects so ON (so.link = T1.object)
--
--UPDATE #t1_wgdfc
--SET prop_code = sp.code
--FROM #t1_wgdfc T1 INNER MERGE JOIN s_property sp ON (sp.link = T1.property)
--
--UPDATE #t1_wgdfc
--SET class_name = code
--FROM s_objects
--WHERE link = 
--  (SELECT link_class FROM s_objects WHERE link = #t1_wgdfc.object)
--
--UPDATE #t1_wgdfc
--SET value = ov.value
--FROM #t1_wgdfc
--    INNER JOIN object_values ov ON (ov.object = #t1_wgdfc.object and ov.property = #t1_wgdfc.property)
--
--IF EXISTS(SELECT * FROM #t1_wgdfc WHERE value LIKE '&&%')
--BEGIN
--	CREATE TABLE #tc_wgdfc(value VARCHAR(4000))
--	CREATE TABLE #tc_wgdfc_cursor(ord INT DEFAULT(0), value VARCHAR(4000))
--	DECLARE @cCmd NVARCHAR(4000), @cValue VARCHAR(4000), @nCnt INT, @nRowCount INT
--
--	INSERT #tc_wgdfc_cursor (value)
--	SELECT value FROM #t1_wgdfc WHERE value LIKE '&&%' GROUP BY value
--	SELECT @nCnt = 0
--	UPDATE #tc_wgdfc_cursor SET @nCnt = ord = @nCnt + 1
--	SELECT @nRowCount = @@ROWCOUNT
--	SELECT @nCnt = 1
--	WHILE @nCnt <= @nRowCount
--	BEGIN
--		SELECT @cValue = value FROM #tc_wgdfc_cursor WHERE ord = @nCnt	
--		SELECT @cCmd = SUBSTRING(@cValue, 3, 8000)			
----		PRINT (@cCmd)
--		INSERT #tc_wgdfc (object, obj_code, property, prop_code, class_name, path, value)
--		EXEC (@cCmd)
--		SELECT @cCmd = value FROM #tc_wgdfc
--		UPDATE #t1_wgdfc SET value = @cCmd WHERE value = @cValue
--		TRUNCATE TABLE #tc_wgdfc
--		SELECT @nCnt = @nCnt + 1
--	END
--END
--
--IF @prop_list = ''
--BEGIN
--	SELECT object, obj_code, property, prop_code, class_name, path, value FROM #t1_wgdfc
--	RETURN
--END
--
--
--
--
---- Формирование колонок из выборки
--DECLARE @sSql NVARCHAR(4000), @nStart INT, @nEnd INT, @cField VARCHAR(100), @cType VARCHAR(100)
--
--SELECT @nStart = 0
--SELECT @sSql = ''
--
--WHILE CHARINDEX(',', @prop_list, @nStart) > 0
--BEGIN
--	SELECT @nEnd = CHARINDEX(',', @prop_list, @nStart+1)
--	SELECT @cField = LTRIM(RTRIM(SUBSTRING(@prop_list, @nStart, @nEnd - @nStart)))
--	SELECT @cType = UPPER(LTRIM(RTRIM(data_type))) FROM s_property WHERE code = @cField
--	IF @sSql <> ''
--		SET @sSql = @sSql + ','
--	ELSE
--		SET @sSql = 'SELECT class_name, t1.obj_code,'
--
--	IF @cField = @cOrder AND @cType IN ('BIT','INT','SMALLINT','NUMERIC')
--		SELECT @sSql = @sSql + '
--(SELECT CONVERT(INT, value) FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') as ' + LTRIM(@cField)
--	ELSE
----		SELECT @sSql = @sSql + '
----(SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') AS ' + LTRIM(@cField)
----
--SELECT @sSql = @sSql + '
--max(case when prop_code = ''' + LTRIM(@cField) + ''' then value else '''' end) AS ' + LTRIM(@cField)
--
--	SELECT @nStart = @nEnd + 1
--END
--
--SELECT @cField = RTRIM(LTRIM(SUBSTRING(@prop_list, @nStart, len(@prop_list) - @nStart + 1)))
--SELECT @cType = UPPER(LTRIM(RTRIM(data_type))) FROM s_property WHERE code = @cField
--
--IF @cField = @cOrder AND @cType IN ('BIT','INT','SMALLINT','NUMERIC')
----SELECT @sSql = @sSql + ',
----convert(int, ISNULL((SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + '''), ORDERS)) AS ' + LTRIM(@cField)
--SELECT @sSql = @sSql + ',
--convert(int, ISNULL(MAX((case when prop_code = ''' + LTRIM(@cField) + ''' then value else NULL end)),ORDERS)) AS ' + LTRIM(@cField)
--ELSE
--SELECT @sSql = @sSql + ',
--max(case when prop_code = ''' + LTRIM(@cField) + ''' then value else '''' end) AS ' + LTRIM(@cField)
--
----SELECT @sSql = @sSql + ',
----(SELECT value FROM #t1_wgdfc WHERE obj_code = t1.obj_code AND prop_code = ''' + LTRIM(@cField) + ''') AS ' + LTRIM(@cField)
--
--SELECT @sSql = @sSql + ' INTO #t2_wgdfc FROM #t1_wgdfc t1 group by class_name, t1.obj_code, orders ORDER BY orders'
--
--IF @cTable <> ''
--	SELECT @sSql = @sSql + '  INSERT ' + @cTable
--
--SELECT @sSql = @sSql + ' SELECT * '
--
--SELECT @sSql = @sSql + ' FROM #t2_wgdfc '
--
--IF @cWhere <> ''
--	SELECT @sSql = @sSql + 'WHERE ' + @cWhere
--
--SELECT @sSql = @sSql + ' ORDER BY ' + @cOrder
--
--
--
--
----PRINT @sSql
--EXEC sp_executesql @sSql
--
--
----SELECT * FROM #t1_wgdfc t1 ORDER BY orders SELECT *  FROM #t2_wgdfc WHERE VISIBLE & 2 > 0 OR VISIBLE & 32 > 0 ORDER BY ORDERS
--select * from #t1_wgdfc
--DROP TABLE #t1_wgdfc

SET NOCOUNT OFF

GO
GRANT ALL ON dbo.[WEB_GET_DOC_FIELD_COLUMNS] 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.[EOS_PERMIT_SEND_DOCINFO]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[EOS_PERMIT_SEND_DOCINFO]

GO
CREATE PROCEDURE dbo.EOS_PERMIT_SEND_DOCINFO( @LINK_DOC INT, @PERMIT BIT = 0 OUTPUT )
AS


IF 
--есть корреспондены
EXISTS (
	SELECT D.LINK, D.EMAIL
	FROM
		dbo.EVENT_OUTCORR C
		INNER JOIN dbo.WF_CORR_OUT CO ON CO.LINK_UP = C.LINK
		INNER JOIN dbo.DEPARTMENTS D ON D.LINK = CO.LINK_ORG
	WHERE
		ISNULL(D.EMAIL,'') <> ''
		AND	
		C.LINK_DOC = @LINK_DOC
)
AND	--включено СЭВ
	dbo.SA_GET_OPTION_BY_CODE('DELO_OPTIONS1_OPT1') = 1
AND --д.б. зарегистрирован
	EXISTS( SELECT 1 FROM dbo.EVENT_REG where LINK_DOC = @LINK_DOC)
--AND	--должен быть завизирован
--	EXISTS( SELECT 1 FROM dbo.EVENT_VISA WHERE LINK_DOC = @LINK_DOC)	
AND --Способ доставки через СЭВ
EXISTS (SELECT 1 
		FROM
			dbo.DOCUMENTS D 
			INNER JOIN dbo.WF_DOCDOST DST ON D.DOST = DST.LINK 
		WHERE 
			D.LINK = @LINK_DOC
			AND 
			DST.NAME = 'СЭВ' )
AND --Гриф Общий
EXISTS (SELECT 1 
		FROM
			dbo.DOCUMENTS D 
			INNER JOIN dbo.WF_DOCSTAMP DST ON D.DOC_STAMP = DST.LINK 
		WHERE 
			D.LINK = @LINK_DOC
			AND 
			DST.NAME = 'Общий' )			

SET @PERMIT = 1
ELSE
	SET @PERMIT = 0		

RETURN 0	


GO


GRANT EXECUTE ON dbo.[EOS_PERMIT_SEND_DOCINFO] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_SZV61]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_SZV61]

GO

CREATE PROCEDURE dbo.SZV4_PRINT_SZV61(@Link int)
AS

DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
	@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9), @Month int, @Year int, @date datetime

SELECT
	@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
	@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP,
	@Month = month_end, @year = year_begin
	FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
	WHERE P.link = @link

Set @date = dbo.ConvertDMY2Date(1,@Month,@Year)
Set @date = dbo.DateEndOfMonth(@date)

Select
	[YEAR] = ISNULL(CASE WHEN year_begin <> 2010 THEN year_begin ELSE NULL END ,0),
	[INN] = @varKSINN,
	[KPP] = @varKSKPP,
	OKPO = @varKSOKPO,
	[CODE] = K.CODE,
	[PER] = ISNULL(CASE WHEN year_begin <> 2010 THEN PER ELSE NULL END ,0),
	[PER10] = ISNULL(CASE WHEN year_begin = 2010 THEN PER ELSE NULL END ,0),
	[TYPE] = P.vid_kor,
	[PER_EDT] = ISNULL(PER_EDT,0),
	[YEAR_EDT] = ISNULL(YEAR_EDT,0),
	[ID] = S.orders,
	[NGROUP] = S.pachka,
	[PFNUMBER] = PF_NUM,
	[FIO] = FIO2,
	[FM],
	[IM],
	[OT],
	[ADDRESS] = ADDRESS,
	[ADDRESS2] = ADDRESS2,
	[INSUR] = COALESCE(S.sum_doh,0), --Это сумма начисленных взносов на страхов. часть
	[INSUR1] = COALESCE(S.INSUR,0)+COALESCE(S.SUM_UPLATA_DOLGA_STR,0), --Это сумма уплаченных взносов на страхов. часть
	[GAIN] = COALESCE(S.GAIN,0), --Это сумма начисленных взносов на накопит. часть
	[GAIN1] = COALESCE(S.DOP,0)+COALESCE(S.SUM_UPLATA_DOLGA_NAK,0), --Это сумма уплаченных взносов на накопит. часть
	[DOP] = COALESCE(S.DOP,0),
	[ID_EX] = ST.orders,
	[DATE_BEGIN] = date1,
	[DATE_END] = date2,
	[STR_DIS] = (CASE WHEN coalesce(dper_vn_m,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(dper_vn_m,0)) + ' м.' else '' end)
	 		+ (CASE WHEN coalesce(dper_vn_d,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(dper_vn_d,0)) + ' дн.' else '' end),
	dper_vn_m = coalesce(dper_vn_m,0),
	dper_vn_d = coalesce(dper_vn_d,0),
	[STR_VAC2] = (CASE WHEN coalesce(dper_oz_m,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(dper_oz_m,0)) + ' м.' else '' end)
	 		+ (CASE WHEN coalesce(dper_oz_d,0) <> 0 THEN CONVERT(VARCHAR(4),coalesce(dper_oz_d,0)) + ' дн.' else '' end),
	dper_oz_m = coalesce(dper_oz_m,0),
	dper_oz_d = coalesce(dper_oz_d,0),
	[TU_CODE] = f_ter_usl,
	ter_usl,
	ter_koef,
	[OS_CODE] = f_osob_usl,
	osob_usl,
	osob_spis = RTRIM(LTRIM(COALESCE(osob_k1,''))) + RTRIM(LTRIM(COALESCE(osob_k2,''))) + RTRIM(LTRIM(COALESCE(osob_k3,''))),
	[EX_CODE] = is_osnov,
	is_dop_m,
	is_dop_d,
	is_dop,
	f_is_dop,
	[P_CODE] = ud_osnov,
	ud_dop_m,
	ud_dop_d,
	ud_dop_k,
	f_ud_dop,
	@varKSNOM_PF AS REG_NOM_PF,
	@varKSname AS DEP_NAME,
	DATE_CRT = @date,
	DATE_DOC = [date]
from
	dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SA_SZV4_SVEDENIA S ON P.link = S.link
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND	
	LEFT JOIN dbo.SA_SZV4_STAZH ST ON S.link1 = ST.link
where
	P.link = @Link
	and S.forma = 1
	and P.proverka = 1
order by
	S.pachka, S.orders, ST.orders


GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_SZV61] 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_GET_LINK_BY_CODE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FB_EXPORT_GET_LINK_BY_CODE]
GO





/*
© Кейсистемс (Keysystems), 2005
*/

create      procedure dbo.FB_EXPORT_GET_LINK_BY_CODE
	@iLinkKBK	int=null output,
	@iLinkEKR	int=null output,
	@iLinkDCL	int=null output,
	@cRes		varchar(8000) = '' output,
	@cCodePPP	char(3) = '',
	@cCodeRazd	char(4) = '',
	@cCodeCelSt	char(7) = '',
	@cCodeRash	char(3) = '',
	@cCodeEkr	char(6) = '',
	@cCodeKIVF	char(20) = '',
	@cCodeKIVnF	char(20) = '',
	@cCodeKD	char(20) = '',
	@cCodeDCL	char(10) = ''		
AS
declare @iRet		int,
	@iTypeKBK	tinyint,
	@iTypeKBKS	tinyint,
	@iLinkPPP	int,
	@iLinkRazd	int,
	@iLinkCSt	int,
	@iLinkRash	int,
	@iLinkKD	int,
	@iLinkKIVnF	int,
	@iLinkKIVF	int,
	@iLinkProg	int,
	@cNameKBK	varchar(50),
	@iAddKBK	tinyint, -- Добавить отсутсвущие ВКР
	@iAddVKR	tinyint

set @cRes = isnull(@cRes,'')
select @iAddKBK = isnull(convert(int,VALUE),0) 
from s_options 
where object =(select link from s_objects where code = 'IMPORT_CREATE_KBK_OPTIONS')

select @iAddVKR = isnull(convert(int,VALUE),0) 
from s_options 
where object =(select link from s_objects where code = 'IMPORT_ADD_VKR_OPTIONS')


set @iRet = 0
set @iTypeKBK = case 	when 	len(@cCodeKD) = 0 and len(@cCodeKIVF) = 0 and len(@cCodeKIVnF) = 0 and 
			  	len(@cCodePPP) <> 0 and len(@cCodeRazd) <> 0 and len(@cCodeCelSt) <> 0 and len(@cCodeRash) <> 0
			then	1
			when 	len(@cCodeKD) <> 0 and len(@cCodeKIVF) = 0 and len(@cCodeKIVnF) = 0 and 
			  	len(@cCodePPP) = 0 and len(@cCodeRazd) = 0 and len(@cCodeCelSt) = 0 and len(@cCodeRash) = 0
			then	2
			when 	len(@cCodeKD) = 0 and len(@cCodeKIVF) <> 0 and len(@cCodeKIVnF) = 0 and 
			  	len(@cCodePPP) = 0 and len(@cCodeRazd) = 0 and len(@cCodeCelSt) = 0 and len(@cCodeRash) = 0
			then	4
			when 	len(@cCodeKD) = 0 and len(@cCodeKIVF) = 0 and len(@cCodeKIVnF) <> 0 and 
			  	len(@cCodePPP) = 0 and len(@cCodeRazd) = 0 and len(@cCodeCelSt) = 0 and len(@cCodeRash) = 0
			then	8 end
if @iTypeKBK is null
begin
	set @cRes = 'Неверный код КБК'
	return -1
end
IF @cCodeEkr = ''
	set @cCodeEkr = right(rtrim(case @iTypeKBK when 2 then @cCodeKD when 4 then @cCodeKIVF when 8 then @cCodeKIVnF end),3)

if @iTypeKBK = 2
	set @cCodeKD = left(@cCodeKD,17)
if @iTypeKBK = 4
	set @cCodeKIVF = left(@cCodeKIVF,17)
if @iTypeKBK = 8
	set @cCodeKIVnF = left(@cCodeKIVnF,17)


select @iLinkEKR = LINK from dbo.KOSGU where CODE = @cCodeEkr

IF @iLinkEKR is null or @iLinkEKR = 0
begin
	set @cRes = 'Неверный код СГУ'
	return -2
end
select @iLinkDCL = LINK from dbo.DOP_CLASSIF where CODE = @cCodeDCL

select @iLinkKBK = LINK from dbo.KL_KBK where TYPE = @iTypeKBK and(
						CODE = @cCodePPP + '.' + @cCodeRazd + '.' + @cCodeCelSt + '.' + @cCodeRash or 
						REPLACE(CODE,'.','') = @cCodeKD OR
						REPLACE(CODE,'.','') = @cCodeKIVF OR
						REPLACE(CODE,'.','') = @cCodeKIVnF)

IF @iLinkKBK is null or @iLinkKBK = 0 and @iRet = 0
	if @iAddKBK = 1
	begin
		if @iTypeKBK = 1
		begin
			select @iLinkPPP  = max(LINK) from dbo.KL_ADMIN_BS    	where CODE = @cCodePPP
			select @iLinkRazd = max(LINK) from dbo.KL_DIVISION    	where CODE = @cCodeRazd
			select @iLinkCSt  = max(LINK) from dbo.KL_TARGET_ITEM 	where CODE = @cCodeCelSt
			select @iLinkRash = max(LINK) from dbo.KL_EXPEND	where CODE = @cCodeRash
			if @iLinkPPP is null or @iLinkRazd is null or @iLinkCSt is null or @iLinkRash is null
			begin
				set @cRes = 'Добавление КБК'
				if @iLinkPPP is null
					set @cRes = @cRes + ' Ненайден администратор:' + @cCodePPP
				if @iLinkRazd is null
					set @cRes = @cRes + ' Ненайден подраздел:' + @cCodeRazd
				if @iLinkCSt is null
					set @cRes = @cRes + ' Ненайдена целевая статья:' + @cCodeCelSt
				if @iLinkRash is null
					set @cRes = @cRes + ' Ненайден вид расхода:' + @cCodeRash
				return -4
			end
			set @cNameKBK = 'ВКР'
			set @iTypeKBKS = 1
		end
		if @iTypeKBK = 2
		begin
			select @iLinkPPP  = max(LINK) from dbo.KL_ADMIN_BS where CODE = left(@cCodeKD,3)
			select @iLinkKD   = max(LINK) from dbo.KL_KD where CODE = substring(rtrim(@cCodeKD),4,10)
			select @iLinkProg   = max(LINK) from dbo.KL_PROG where CODE = right(rtrim(@cCodeKD),4)
			
		
			if @iLinkPPP is null or @iLinkKD is null or @iLinkProg is null 
			begin
				set @cRes = 'Добавление КБК'
				if @iLinkPPP is null
					set @cRes = @cRes + ' Ненайден администратор:' + left(@cCodeKD,3)
				if @iLinkKD is null
					set @cRes = @cRes + ' Ненайден код дохода:' + substring(rtrim(@cCodeKD),4,10)
				if @iLinkProg is null
					set @cRes = @cRes + ' Ненайдена программа:' + right(rtrim(@cCodeKD),4)
				return -4

			end
			set @cNameKBK = 'КД'
			set @iTypeKBKS = 2
		end
		if @iTypeKBK = 4
		begin
			select @iLinkPPP  = max(LINK) from dbo.KL_ADMIN_BS    	where CODE = left(@cCodeKIVF,3)
			select @iLinkKIVF = max(LINK) from dbo.KL_IVF    	where CODE = substring(rtrim(@cCodeKIVF),4,10)
			select @iLinkProg   = max(LINK) from dbo.KL_PROG where CODE = right(rtrim(@cCodeKIVF),4)
			if @iLinkPPP is null or @iLinkKIVF is null or @iLinkProg is null
			begin
				set @cRes = 'Добавление КБК'
				if @iLinkPPP is null
					set @cRes = @cRes + ' Ненайден администратор:' + left(@cCodeKIVF,3)
				if @iLinkKIVF is null
					set @cRes = @cRes + ' Ненайден код дохода:' + substring(rtrim(@cCodeKIVF),4,10)
				if @iLinkProg is null
					set @cRes = @cRes + ' Ненайдена программа:' + right(rtrim(@cCodeKIVF),4)
				return -4
			end
			set @cNameKBK = 'КИВФ'
			set @iTypeKBKS = 3
		end
		if @iTypeKBK = 8
		begin
			select @iLinkPPP  = max(LINK) from dbo.KL_ADMIN_BS    	where CODE = left(@cCodeKIVnF,3)
			select @iLinkKIVnF = max(LINK) from dbo.KL_IVF    	where CODE = substring(rtrim(@cCodeKIVnF),4,10)
			select @iLinkProg   = max(LINK) from dbo.KL_PROG where CODE = right(rtrim(@cCodeKIVnF),4)
			if @iLinkPPP is null or @cCodeKIVnF is null or @iLinkProg is null 
			begin
				set @cRes = 'Добавление КБК'
				if @iLinkPPP is null
					set @cRes = @cRes + ' Ненайден администратор:' + left(@cCodeKIVnF,3)
				if @iLinkKIVnF is null
					set @cRes = @cRes + ' Ненайден код дохода:' + substring(rtrim(@cCodeKIVnF),4,10)
				if @iLinkProg is null
					set @cRes = @cRes + ' Ненайдена программа:' + right(rtrim(@cCodeKIVnF),4)
				return -4
			end
			set @cNameKBK = 'КИВнФ'
			set @iTypeKBKS = 4
		end
		set @cNameKBK = 'Сгенерированный ' + @cNameKBK 
		SET @iLinkKBK = 0
		--select  @iTypeKBKS, @cNameKBK, @iLinkPPP, @iLinkKD, @iLinkKIVF, @iLinkKIVnF, @iLinkRazd, @iLinkCSt, @iLinkRash
		exec @iRet = dbo.BI_SAVE_KBK @iLinkKBK output, @iTypeKBKS, @cNameKBK, @iLinkPPP, @iLinkKD, @iLinkKIVF, @iLinkProg, @iLinkRazd, @iLinkCSt, @iLinkRash  
		--select @iRet,@iLinkKIVF
		if @iRet <> 0 or @iLinkKBK = 0
		begin
			set @cRes = 'Ошибка при добавлении КБК'
			return -1
		end
	end
	else
	begin
		set @cRes = 'Добавление КБК при импорте отключено'
		return -1
	end 

if @iTypeKBK = 1
begin
	declare @iLinkDep int,
		@iLinkSpr int
	set @iLinkDep = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
	if NOT exists(select * from dbo.DEPARTMENT_KBK where DEP_LINK = @iLinkDep and KBK_LINK = @iLinkKBK)
		if @iAddVKR = 1		
		begin
			exec @iRet = XD_DEP_VKR_SAVE @iLinkSpr, @iLinkDep, @iLinkKBK
			if @iRet <> 0 
			begin
				set @cRes = 'Ошибка при добавление КБК в используемые'
				return -3
			end 
			end
		else
		begin
			set @cRes = 'Добавление КБК в используемые отключено и возможно'
			return -3
		end 
			
end

return @iRet

GO
grant all on dbo.FB_EXPORT_GET_LINK_BY_CODE 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].[RN_WEB_SAVE_TABLES_CELLS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_WEB_SAVE_TABLES_CELLS]
GO

CREATE         PROCEDURE dbo.[RN_WEB_SAVE_TABLES_CELLS]
	@iLinkSF	int output,
	@bExcess tinyint = 0 output,	-- FOR WEB only
	@cText	varchar(50) = '' output,	-- FOR WEB only
	@RepeatRequest	int = NULL	-- повторный запуск
AS

SET @bExcess = 0
SET @cText='Результат'
if @RepeatRequest = 1 -- отчет не сохраняем
begin
	SET @bExcess = 1
	select '' as res
	return 0
end

create table #Res_save (orders int, resCode varchar(50), res varchar(8000))
create table #Res (orders int,ord int IDENTITY (1, 1) NOT NULL, res varchar(8000),cKod varchar(100),cDoc varchar(254),cTable varchar(100),cCol varchar(100),cValue varchar(100))
create table #TMP_STR_VAL (str_val varchar(250))
create table #REPORT_DINAMICS (link_sf int,link_col int,CODE_ROW varchar(50),str_val varchar(8000))

-- Проверяем существование врем. таблицы с описанием

IF object_id('tempdb..#REP_HEAD')  is null 
	return -1
-- Сохраняем заголовок
DECLARE	
   @liLINK_SAVED_FORM   INT,
   @varKSintLINK	int,   
	@varKSLinkF	int,
	@varKSVers	smallint,
	@varKSBDAte	datetime,
	@varKSpTYPE	tinyint,
	@varKSPNomber	tinyint,
	@varKSLinkOrg	int,
	@varKSisSvod	tinyint,
	@iRes	INT,
	@varKSisCalcItog INT,
	@varKSIsRO	tinyint,
	@varKSNote	varchar(500),
	@varKSLinkTypeSvod int,
	@varKSNewCountSave int,
	@varKSOldCountSave int,
	@varKSFIO varchar(500),
	@varKSLogin varchar(500),
	@varKSHostName varchar(500),
	@varKSDate varchar(500),
	@varKSEvent varchar(500),
	@varKSText varchar(500),
	@varKSWarMessage varchar(800),
        @lcPERIOD_YEAR CHAR(4),
        @isExistsREP_TABLE bit,
		@oldIsRO	tinyint,
		@access_status tinyint
        SET @isExistsREP_TABLE=0

        IF object_id('tempdb..#REP_TABLE_1') is not null 
           SET @isExistsREP_TABLE=1

SET @iRes = 0
SELECT  @varKSintLINK=link, @varKSLinkF=link_form, @varKSVers=Version,
	@varKSBDAte = case period_type when 1 then LTRIM(STR(period_year)) + '1231' 
	when 2 then dateadd(quarter, period_number, LTRIM(STR(period_year)) + '0101') -1
	else dateadd(month, period_number, LTRIM(STR(period_year)) + '0101') - 1 end,
	@varKSpTYPE = period_type, @varKSPNomber = period_number,
	@varKSLinkOrg = link_organization, @varKSisSvod = IsSvod, @varKSisCalcItog = isCalcItog,
	@varKSIsRO = IsRO, @varKSNote = Note, @varKSLinkTypeSvod = Link_Type_Svod, @varKSNewCountSave = CountSave,
   @lcPERIOD_YEAR     = LTRIM(STR([PERIOD_YEAR]))
FROM #REP_HEAD

select @oldIsRO = IsRO from report_saved_forms where link_saved_form = @varKSintLINK


if dbo.Ro_AccessStatus(dbo.Ro_AccessStatusByLink(ABS(@varKSLinkF)), @oldIsRO, 0) = 0 OR (dbo.RO_SVOD_STATUS_ACCESS_MASK_ISRO (@varKSLinkTypeSvod, @varKSLinkOrg) < 255 AND IS_MEMBER('Свод-КС')=1 AND @oldIsRO IN (select Status from dbo.Report_Status where access <> 255))
begin
		SET @bExcess = 1
		Insert into #Res (orders, res)
		values (0, 'Ошибка сохранения документа: НЕТ ДОСТУПА К СТАТУСУ')
		select res from #Res order by orders
		drop table #Res
		RETURN -1 --Ошибка сохранения заголовка формы
end                                

EXEC dbo.[RA_WEB_DECODE_PERIOD] @varKSpTYPE   OUTPUT,
                                @varKSPNomber OUTPUT,
                                @varKSBDAte   OUTPUT,
                                @lcPERIOD_YEAR  

-- доступно ли поменять статус Olga 2009.07.30
if @varKSintLINK > 0 -- для сохраненных отчетов
begin
	set @access_status = dbo.Ro_AccessStatus(dbo.Ro_AccessStatusByLink(@varKSLinkF), @oldIsRO, 0)
	if (@access_status = 0 OR dbo.Ro_AccessStatus(dbo.Ro_AccessStatusByLink(@varKSLinkF), @varKSIsRO, 0) = 0) and @varKSIsRO <> @oldIsRO
	BEGIN
		SET @bExcess = 1
		Insert into #Res (orders, res)
		values (0, 'Ошибка сохранения документа: НЕЛЬЗЯ ПОМЕНЯТЬ СТАТУС')
		select res from #Res order by orders
		drop table #Res
		RETURN -1 --Ошибка сохранения заголовка формы
	end
	else begin
		if @access_status = 0 and (select access from report_status where status = @oldIsRO) <> 255
		begin
			SET @bExcess = 1
			Insert into #Res (orders, res)
			values (0, 'Ошибка сохранения документа: НЕЛЬЗЯ РЕДАКТИРОВАТЬ ОТЧЕТ В ЭТОМ СТАТУСЕ')
			select res from #Res order by orders
			drop table #Res
			RETURN -1 --Ошибка сохранения заголовка формы
		END
	end
end	

IF @varKSLinkOrg is null or @varKSLinkOrg = 0
begin
SET @iLinkSF = @varKSintLINK
SET @bExcess = 1
Insert into #Res_save (orders, res)
values (0, 'Ошибка сохранения документа: НЕ УКАЗАНА ОРГАНИЗАЦИЯ')
select res from #Res_save order by orders
drop table #Res_save
RETURN -1 --Ошибка сохранения заголовка формы
end

if (select count(*) from report_saved_forms where link_saved_form = @varKSintLINK) = 0
begin
	set  @varKSintLINK = 0
end

declare @catr_val varchar(250),@atr varchar(250),@atributs varchar(250),@li int,@str_val varchar(250),@cexec varchar(4000)
set @atributs=''
set @catr_val=''

IF object_id('tempdb..#REP_ATR') is not null 
    begin
    select @atributs=rtrim(atributs) from report_forms where link_form= @varKSLinkF
    set @li=1
    set @catr_val=''
    IF @atributs<>''
       begin 
        WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
                delete #TMP_STR_VAL                  
                set @cexec='INSERT #TMP_STR_VAL SELECT TOP 1 '+@atr+' FROM #REP_ATR'
                print @cexec
                execute(@cexec)
                select @str_val=ISNULL((select str_val from #TMP_STR_VAL),ISNULL(dbo.get_val(@atr,'DEFAULT_VALUE',0),'')) 
                set @catr_val=@catr_val+case when @catr_val<>'' then ',' else '' end+ RTRIM(@atr)+'='+rtrim(@str_val)
                set @li=@li+1
            end
        END
    end

if not exists(select * from dbo.RO_SVOD_TREE where LINK_REPORT_ORG = @varKSLinkOrg and LINK_REPORT_BUDG = @varKSLinkTypeSvod)
	set @varKSLinkTypeSvod = dbo.RO_SVOD_BUDG_FOR_ORG(@varKSLinkOrg)

/*
if IS_MEMBER('Свод-КС') = 1 and dbo.RO_SVOD_STATUS_ACCESS_WITH_ATR(@varKSLinkTypeSvod, @varKSLinkOrg, @varKSisSvod, @varKSLinkF, @varKSpTYPE, @varKSPNomber, @varKSBDAte,@catr_val) < 255
begin
	if @varKSISRO = 2
	begin
		Insert into #Res_save (orders, res)
		 select 0, 'Ошибка сохранения документа: НЕ ДОСТУПЕН СТАТУС ''' + Status_Name + ''''
			from report_status where Status = @varKSISRO
	end
	else begin
		Insert into #Res_save (orders, res)
		 select 0, 'Ошибка сохранения документа: ОТЧЕТ ДАННОЙ ФОРМЫ ОТЧЕТНОСТИ НЕ МОЖЕТ БЫТЬ ИЗМЕНЕН, ТАК КАК ОН УЖЕ ВКЛЮЧЕН В СВОД'
	end
	SET @iLinkSF = @varKSintLINK
	SET @bExcess = 1
	select res from #Res_save order by orders
	drop table #Res_save
	RETURN -1 --Ошибка сохранения заголовка формы
end
*/
if @RepeatRequest = 0 -- отчет перезаписываем
begin
	if exists(select top 1 * from report_saved_forms where Link_Form = @varKSLinkF and Begin_Date = @varKSBDAte and period_type = @varKSpTYPE and period_number = @varKSPNomber and Link_Organization = @varKSLinkOrg and IsSvod = @varKSisSvod and Link_Type_Svod = @varKSLinkTypeSvod and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 = 0  
       and isnull(atr_code,'')=@catr_val)
              
	begin -- нет прав удалить отчеты
		SET @bExcess = 1
		SET @cText='Результат'
		Insert into #Res_save (orders, res)
		 select 0, 'Невозможно перезаписать отчет! Нет доступа!'
		select res from #Res_save order by orders
		drop table #Res_save
		RETURN 0 --Ошибка сохранения заголовка формы
	end
	delete report_saved_forms
	where Link_Form = @varKSLinkF and Begin_Date = @varKSBDAte and period_type = @varKSpTYPE and period_number = @varKSPNomber 
	and Link_Organization = @varKSLinkOrg and IsSvod = @varKSisSvod and Link_Type_Svod = @varKSLinkTypeSvod 
	and isnull(atr_code,'')=@catr_val and dbo.RO_ACCESS_SAVED_FORM (Link_saved_form, 1) & 2 > 0
	and link_saved_form<>@varKSintLINK
end


EXEC @iRes = I_REPORT_SAVE_FORM @varKSintLINK output, @varKSLinkF, @varKSVers, @varKSBDAte, @varKSpTYPE, @varKSPNomber, @varKSLinkOrg, @varKSisSvod, default, default, default, default, @varKSIsRO, @varKSNote, 0, @varKSLinkTypeSvod, @varKSNewCountSave,0,0,@catr_val

declare @code_atr varchar(250), @Check int

IF object_id('tempdb..#REP_ATR') is not null 
    begin
    select @atributs=rtrim(atributs) from report_forms where link_form= @varKSLinkF
    set @li=1
    set @catr_val=''
    IF @atributs<>''
       begin 
        WHILE dbo.RN_GETWORDNUM(@atributs,@li,',')>''
            begin
                set @atr=dbo.RN_GETWORDNUM(@atributs,@li,',')
                delete #TMP_STR_VAL                  
                set @cexec='INSERT #TMP_STR_VAL SELECT TOP 1 '+@atr+' FROM #REP_ATR'
                print @cexec
                execute(@cexec)
                select @str_val=ISNULL((select str_val from #TMP_STR_VAL),ISNULL(dbo.get_val(@atr,'DEFAULT_VALUE',0),'')) 

				-- провека атрибутов на наличие в справочнике
				exec @Check = dbo.RO_CHECK_ATR_FROM_DICT @atr,@str_val
				if @Check <> 0
				begin
					SET @bExcess = 1
					Insert into #Res (orders, res)
					values (0, 'Ошибка сохранения документа: ЗНАЧЕНИЕ АТРИБУТА ОТСУТСТВУЕТ В СПРАВОЧНИКЕ')
					select res from #Res order by orders
					drop table #Res
					RETURN -1 --Ошибка сохранения заголовка формы
				end
				-- ---------

                exec dbo.RN_SAVE_ATRIBUT_VALUES    @varKSintLINK,@atr,@str_val
                set @li=@li+1
            end
        END
    end


if @iRes = 11000 -- возникает только тогда когда стоит настройка
begin
	SET @bExcess = 2
	SET @cText='Результат @ 0 - Да @ 1 - Нет'
	Insert into #Res_save (orders, res)
	 select 0, 'Такой отчет уже существует! Перезаписать существующий отчет на этот (ДАННЫЕ СУЩЕСТВУЮЩЕГО ОТЧЕТА ПОТЕРЯЮТСЯ) ?'
	select res from #Res_save order by orders
	drop table #Res_save
	RETURN 0 --Ошибка сохранения заголовка формы
end
if @iRes = 11001 -- возникает только тогда когда стоит настройка
begin
	Insert into #Res_save (orders, res)
	 select 0, 'Ошибка сохранения документа: Срок действия формы не входит в сохраняемый период'
	select res from #Res_save order by orders
	drop table #Res_save
	RETURN 0 --Ошибка сохранения заголовка формы
end



IF @iRes<>0 or @varKSintLINK<=0
	RETURN -1 --Ошибка сохранения заголовка формы

IF COL_LENGTH('tempdb..#REP_HEAD','IsCopy') IS NOT NULL
BEGIN     
   IF EXISTS(SELECT * 
             FROM tempdb..#REP_HEAD
             WHERE [IsCopy] = 1)
   BEGIN      
      SELECT @liLINK_SAVED_FORM = [LINK_SAVED_FORM]
      FROM #REP_HEAD
     
      EXEC dbo.[RA_COPY_SAVED_FORM] @liLINK_SAVED_FORM,
                                    @varKSintLINK OUTPUT
   END
END

IF @isExistsREP_TABLE<>1
begin
	set @iLinkSF = @varKSintLINK
	return 0
end

-- 1. - список таблиц
DECLARE @Table_Orders	tinyint,
	@Link_Col		int,
	@Link_table		int,
	@Col_orders	tinyint,
	@cRunStr	varchar(2000),
	@Col_Type		tinyint,
	@Table_Type		tinyint,
	@Link_Code_Col	int,
    @key varchar(1000)


declare @tables table (link_table int)
declare @tables1 table (link_table int)
declare @one_table int
declare @ord_code int
declare @cstr varchar(8000)
IF col_length('tempdb..#REP_HEAD', 'link_table') is NULL and @isExistsREP_TABLE=1
   BEGIN
		insert @tables
		select link_table from report_tables 
		where link_form = (select max(link_form) from #REP_HEAD) order by orders
		set @one_table=0
   END
   ELSE
   BEGIN
        --так вытаскиваем Link_Table, через з..
        create table #tmpTable (Link_table int)
        set @cstr='INSERT #tmpTable SELECT  Link_Table FROM #REP_HEAD'
        exec(@cstr)

		insert @tables
		select Link_Table FROM #tmpTable
		set @one_table=1

   END
insert @tables1
select link_table from @tables
declare @is_dinamic int

WHILE exists(select * from @tables1)
BEGIN
    select @link_Table=link_table from @tables1
	delete @tables1 where link_table=@link_Table
	
	select @is_dinamic=isnull(is_dinamic,0) from report_tables where link_table=@link_table 

	exec rn_get_formula_code_row @link_Table,'KEY_WEB=',@key output

	select @Table_Type = val_type, @Link_Code_Col = Link_Code_Col,@Table_Orders=orders from report_tables where Link_Table = @link_Table
	IF @one_table=1
		set @Table_Orders=1

	select @ord_code=orders from report_coloumns where link_col = @Link_Code_Col

	if @Table_Type = 1 or @is_dinamic>0
	begin
		IF @key<>''
		begin
			select @cRunStr = 'update #REP_TABLE_' + ltrim(convert(char(2),@Table_Orders)) + ' SET COL' + LTRIM(STR(@ord_code)) + ' = '+@key
			exec (@cRunStr)
		end
	end

	
END
--
create table #query (query varchar(8000), link int IDENTITY(1,1))
if object_id('tempdb..#t_CodeRow') is NOT NULL
	drop table #t_CodeRow

create table #t_CodeRow(Code varchar(50))
insert #query(query)
SELect ' insert #t_CodeRow
select  Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + '
From #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' where isnull(del,0) <> 1'
from report_tables RT 
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1

insert #query(query)
SELect ' exec dbo.RN_FILL_WITH_CODEROW ' + STR(@varKSintLINK) + ', ' + STR(Link_Form) + ', ' + STR(RT.orders)
from report_tables RT 
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1

exec dbo.ssp_execresultset 'select query from  #query order by link'--, @varKSdebug = 1

drop table #t_CodeRow
truncate table #query
------------------------------------------------------------------------------------------
-- Проверка на наличие в справочнике
declare @cnt int, @nastr_dict varchar(10)
set @cnt = isnull((select  count(*) from #res), 0)
insert #query(query)
SELect ' insert #Report_Dinamics 
select  ' + STR(@varKSintLINK) + ',' + STR(Link_Col) + ',Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + ', COL' + LTRIM(STR(RC.orders)) + '
From #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' where isnull(del,0) <> 1'
from report_tables RT left join report_coloumns RC on RC.Link_Table = RT.Link_Table
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1 and RC.Col_Type <> 0 and RT.Link_Code_Col <> RC.Link_Col


insert #query
select ' insert #Res (res,orders,cdoc,ckod,cTable,cCol,cvalue) exec RN_CHECK_DICT ' + STR(@varKSintLINK) + ',' + STR(RT.orders) + ',4 '
from report_tables RT
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1

exec dbo.ssp_execresultset 'select query from  #query order by link'--, @varKSdebug = 1

exec X_GET_OPTION 'RN_REP_OPTIONS_COM_ZAPRET_SAVE', 0, @nastr_dict output

if (convert(int, @nastr_dict) = 1)  and @cnt <> isnull((select count(*) from #res WHERE isnull(cDoc,'')<>''),0) 
if  @cnt <> isnull((select count(*) from #res),0)
begin
	set @bExcess = 1
	drop table #query
   
     select case when left(cDoc,1)='В' then rtrim(cDoc) else ltrim(res)+'.'+rtrim(cDoc)+', Таблица: '+rtrim(cTable)+', Графа: '+rtrim(cCol) end res from #res where isnull(cDoc,'')<>''
	return 1
end
-- конец проверки
---------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
-- Проверка на наличие дублирующих кодов
delete #query
create table #t_DCodeRow (Code varchar(50), OT int)
SELect @cstr = ' insert  #t_DCodeRow (Code, OT)
select  Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) +', ' + LTRIM(STR(RT.orders)) + '
From #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' where isnull(del,0) <> 1 and upd_cells_mask is not null group by Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + ' having count(*) > 1'
from report_tables RT left join report_coloumns RC on RC.Link_Table = RT.Link_Table
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1-- and RC.Col_Type <> 0 and RT.Link_Code_Col <> RC.Link_Col

exec (@cStr)

SELect @cstr = ' insert  #t_DCodeRow (Code, OT)
select  Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) +',' + LTRIM(STR(RT.orders)) + '
From #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' where isnull(del,0) <> 1 and upd_cells_mask is not null and isnull(Code, '''') <> Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) +'
and exists(select top 1 * from dbo.report_dinamics D join dbo.report_coloumns C on D.Link_Col = C.Link_Col where D.Link_SF = ' + STR(@varKSintLINK) + ' and C.Link_Table = ' + STR(RC.Link_Table) + ' and D.Code_Row = Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + '
		and not exists(select top 1 * from #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' T where isnull(T.code,'''') = D.Code_Row))'
from report_tables RT left join report_coloumns RC on RC.Link_Table = RT.Link_Table
where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1 and RC.Col_Type <> 0 and RT.Link_Code_Col <> RC.Link_Col

exec (@cStr)
if @RepeatRequest = 3 -- пользователь выбрал объединение дублирующих кодов
begin
	insert #query(query)
	SELect ' update T
	set Col' + LTRIM(STR(RC.orders)) + '= (select sum(Col' + LTRIM(STR(RC.orders)) + ') from #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' T1 where isnull(del,0) <> 1 and T1.Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + ' = T.Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + '),
		upd_cells_mask = left(upd_cells_mask, ' + LTRIM(STR(RC.orders - 1)) + ') + ''1'' + substring(upd_cells_mask, ' + LTRIM(STR(RC.orders + 1)) + ', 1000)
	from #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' T
	where T.Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + ' in (select D.Code from #t_DCodeRow D where OT = ' + LTRIM(STR(RT.Orders)) + ')'
	from report_tables RT left join report_coloumns RC on RC.Link_Table = RT.Link_Table
	where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1 and RC.Col_Type = 0
	exec dbo.ssp_execresultset 'select query from  #query order by link'--, @varKSdebug = 1
	delete #query

	insert #query(query)
	SELect ' update T
	set Col' + LTRIM(STR(RC.orders)) + '= Col' + LTRIM(STR(RC.orders)) + ' + isnull((select Float_Val from dbo.report_dinamics D where D.Link_SF = ' + STR(@varKSintLINK) + ' and D.Link_Col = ' + STR(RC.Link_Col) + ' and D.Code_Row = Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + '
			and not exists(select top 1 * from #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' T where isnull(T.code,'''') = D.Code_Row)),0),
		upd_cells_mask = left(upd_cells_mask, ' + LTRIM(STR(RC.orders - 1)) + ') + ''1'' + substring(upd_cells_mask, ' + LTRIM(STR(RC.orders + 1)) + ', 1000)
	from #REP_Table_'+case @one_table when 1 then '1' else ltrim(STR(RT.orders)) end  + ' T
	where T.Col' + LTRIM(STR((select top 1 orders from report_coloumns RC1 where RC1.Link_Col = RT.Link_Code_Col))) + ' in (select D.Code from #t_DCodeRow D where OT = ' + LTRIM(STR(RT.Orders)) + ')'
	from report_tables RT left join report_coloumns RC on RC.Link_Table = RT.Link_Table
	where RT.Link_Table in (select link_table from @tables) and RT.Val_Type = 1 and RC.Col_Type = 0 
	exec dbo.ssp_execresultset 'select query from  #query order by link'--, @varKSdebug = 1
end
else begin
	if  exists(select top 1 * from #t_DCodeRow)
	begin
		SET @bExcess = 2
		SET @cText='Результат @ 3 - Сохранить с объединением'

		Insert into #Res_save (orders, res)
		select 0, 'Найдены дублирующиеся коды. Продолжить сохранение с их объединением?' as res
		
		Insert into #Res_save (orders, res)
		select distinct 1, 'Код:' + Code
		from #t_DCodeRow
		
		select res from #Res_save
		return 1
	end
end

drop table #t_DCodeRow
-- конец проверки
---------------------------------------------------------------------------------------------
create table #table_code (CODE VARCHAR(50),link_row int)
WHILE exists(select * from @tables)
BEGIN
    create table #save_web_form (link_col int,link_row int,code_row varchar(50),str_val varchar(4000),summa numeric(20,4),del bit)
	select @is_dinamic=isnull(is_dinamic,0) from report_tables where link_table=@link_table 

	select @link_Table=link_table from @tables
	delete @tables where link_table=@link_Table

	exec rn_get_formula_code_row @link_Table,'KEY_WEB=',@key output

	select @Table_Type = val_type, @Link_Code_Col = Link_Code_Col,@Table_Orders=orders from report_tables where Link_Table = @link_Table
	IF @one_table=1
		set @Table_Orders=1

	select @ord_code=orders from report_coloumns where link_col = @Link_Code_Col

--    IF @key<>''
--    begin
--		select @cRunStr = 'update #REP_TABLE_' + ltrim(convert(char(2),@Table_Orders)) + ' SET col' + rtrim(convert(varchar(10),@ord_code))+' = '+@key
--		exec (@cRunStr)
--    end

	--обновим link_row
	IF @is_dinamic>0
		begin
			set @cRunStr='delete #table_code 
			insert #table_code (code) select col' + rtrim(convert(varchar(10),@ord_code))+' from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))
			print @cRunStr
			exec (@cRunStr)
			exec rn_get_link_rows 	@link_Table,'#table_code',1
		END	

	IF @Table_Type <> 0 or @is_dinamic=1
	BEGIN
		SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
		select 0,link_row,code,0,0,1 from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
		' where code<>col' + rtrim(convert(varchar(10),@ord_code))
		exec (@cRunStr)

		SET @cRunStr = 'update #REP_TABLE_' + ltrim(convert(char(2),@Table_Orders)) + ' SET upd_cells_mask=replicate(''1'',50)
		 where code<>col' + rtrim(convert(varchar(10),@ord_code))
		exec (@cRunStr)

		select @cRunStr = 'update #REP_TABLE_' + ltrim(convert(char(2),@Table_Orders)) + ' SET code = isnull(col' + rtrim(convert(varchar(10),orders)) + ','''')'
			from report_coloumns where link_col = @Link_Code_Col
		exec (@cRunStr)
	END

	--сформируем 
	DECLARE col_cursor CURSOR FOR
	select link_col, orders, col_type from report_coloumns 
		where link_table = @Link_Table and isEdited=1
	OPEN col_cursor 
	FETCH NEXT FROM col_cursor INTO @Link_Col, @Col_orders, @Col_Type

	--select @link_col,@Col_orders,@Table_orders,@Col_Type,@Table_Type
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @Col_Type <> 0 AND @Table_Type <> 0 -- Динамический текстовый столбец
		BEGIN
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@link_col) + ', 0, code,isnull(col' + ltrim(convert(char(2),@Col_orders)) + ',''''),0,isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
				' where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1'''

		END
		IF @Col_Type = 0 AND @Table_Type = 0 -- Стандартный числовой столбец
		BEGIN
			IF @is_dinamic>0	
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
					select ' + convert(varchar(9),@link_col) + ', B.link_row,'''','''', (col' + ltrim(convert(char(2),@Col_orders)) + '),isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
					' A ,#table_code B 
					 where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1''
					and A.code=B.code and isnull(B.link_row,0)<>0'
				else
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
					select ' + convert(varchar(9),@link_col) + ', link_row,'''','''', col' + ltrim(convert(char(2),@Col_orders)) + ',isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
					' where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1'''
		END
		IF @Col_Type = 0 AND @Table_Type <> 0 -- Динамический числовой столбец
		BEGIN
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@link_col) + ', 0,code,'''',max(isnull(col' + ltrim(convert(char(2),@Col_orders)) + ',0)),isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
				' where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1''' +
				' group by code, isnull(del,0)'

		END
		IF @Col_Type <> 0 AND @Table_Type = 0 -- Стандартный текстовый столбец
		BEGIN
			IF @is_dinamic>0	
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@link_col) + ', B.link_row, '''',isnull(col' + ltrim(convert(char(2),@Col_orders)) + ',''''),0,isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
					' A ,#table_code B 
					 where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1''
					and A.code=B.code and isnull(B.link_row,0)<>0'
				else
				SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
				select ' + convert(varchar(9),@link_col) + ', link_row, '''',isnull(col' + ltrim(convert(char(2),@Col_orders)) + ',''''),0,isnull(del,0) from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
				' where substring(upd_cells_mask,'+str(@Col_orders)+',1)=''1'''

		END

        print @cRunStr
		exec (@cRunStr)

		FETCH NEXT FROM col_cursor INTO @Link_Col, @Col_orders, @Col_Type
	END
	
	CLOSE col_cursor
	DEALLOCATE col_cursor

	IF @Table_Type=0 
		begin
			SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
			select 0,link_row,'''' ,0,0,1 from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
			' where del=1'
			exec (@cRunStr)
		end
	IF @Table_Type=1 
		begin
			SET @cRunStr = 'insert into #save_web_form (link_col,link_row,code_row,str_val,summa,del) 
			select 0,0,code,0,0,1 from #REP_TABLE_' + ltrim(convert(char(2),@Table_orders))+
			' where del=1'
			exec (@cRunStr)
		end

	exec RN_SAVE_SUMMA @varKSintLINK,@Link_Table,'#save_web_form',1

IF @varKSisCalcItog=1 
execute dbo.RI_REPORT_FORMULA_CALCULATE_ITOG default,default,@varKSintLINK

SET @iLinkSF = @varKSintLINK

declare @ord int, @cCodeOrg varchar (50), @cNameOrg varchar(250)
select @ord = max(orders) from #Res_save
if @ord is null
	set @ord = 1

--проверка справочной инфы.
declare @table_ord int
select @table_ord=orders from report_tables where link_table=@Link_Table


end

if (select count(*) from #res)>1
    begin
        select res from (
        select ord ,case when left(cDoc,1)='В' then rtrim(cDoc) else ltrim(res)+'.'+rtrim(cDoc)+', Таблица: '+rtrim(cTable)+', Графа: '+rtrim(cCol) end res from #res where cDoc<>'' 
        union 
        select orders+10000 ord,res from #Res_save) A order by ord
    end
    else
        select res from #Res_save --order by orders

drop table #Res_save
drop table #Res
GO
GRANT ALL ON dbo.[RN_WEB_SAVE_TABLES_CELLS] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_125_1C_XML]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_125_1C_XML]
END
GO
/*******************************************************************************

	© Кейсистемс (Keysystems), 2010

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_125_1C_XML]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,     -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

PRINT 'dbo.RA_IMPORT_FORM_125_1C_XML'
DECLARE @iXML_DOC_HANDLE INT,
        @vcCODE_FORM	VARCHAR(20),
        @vcKBP	      VARCHAR(100),
        @vcVB	      VARCHAR(10),
        @dDT	      DATETIME,
        @tPRD	      TINYINT,

        @vcPRP       VARCHAR(50),
        @vcKSBU      VARCHAR(50),   
        @iRD         INT,
        @vcRD        VARCHAR(100),
        @vcKVD     VARCHAR(100),
        @vcACCOUNT VARCHAR(100),
        @vcKOSGU   VARCHAR(100),
        @vcIsMoney VARCHAR(100)  
        

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [RD]    TINYINT,
                          [PRP]   VARCHAR(50),
                          [KSBU]  VARCHAR(50),
                          [ORDER] INT IDENTITY(1,1))

EXEC dbo.[RA_IMPORT_FORM_ANALYZE_XML] @cCODE_FORM = @vcCODE_FORM OUTPUT,   
                                      @vcKBP = @vcKBP           OUTPUT,
                                      @vcVB = @vcVB             OUTPUT,
                                      @dDT = @dDT               OUTPUT,
                                      @vcSOFT = '',
                                      @vbVF0 = '',
                                      @iXML_DOC_HANDLE = @iXML_DOC_HANDLE OUTPUT

SET @tPRD = ISNULL(MONTH(@dDT),1)

-- Определение шапки для группы отчетов.
INSERT @tabImport([TXT],[RD]) VALUES ('Файл преобразован во внутренний формат из формата 1C',0)
INSERT @tabImport([TXT],[RD]) VALUES ('ВФ=0',0)
INSERT @tabImport([TXT],[RD]) VALUES ('КБП='+ISNULL(@vcKBP,''),0)
INSERT @tabImport([TXT],[RD]) VALUES ('ВБ='+ISNULL(@vcVB,''),0)
INSERT @tabImport([TXT],[RD]) VALUES ('КФ='+ISNULL(@vcCODE_FORM,''),0)
INSERT @tabImport([TXT],[RD]) VALUES ('ПРД='+CAST(ISNULL(@tPRD,1) AS VARCHAR(50)),0)
INSERT @tabImport([TXT],[RD]) VALUES ('ДТ='+CASE 
                                               WHEN @dDT IS NULL THEN ''
                                               ELSE CONVERT(VARCHAR(50),@dDT,104)
                                            END,0)
INSERT @tabImport([TXT],[RD]) VALUES ('РА=0',0)

SELECT TOP 1 @vcKVD = [KVD]
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/key/value',1) with ([KVD] VARCHAR(100) 'text()', [ABOUT] VARCHAR(250) '../@about')
WHERE [ABOUT] = "urn:entities-1c-ru:budget/classification/kvd"

SELECT TOP 1 @vcACCOUNT = REPLACE([ACCOUNT],'.','')
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/key/value',1) with ([ACCOUNT] VARCHAR(100) 'text()', [ABOUT] VARCHAR(250) '../@about')
WHERE [ABOUT] = "urn:entities-1c-ru:budget/account"

SELECT TOP 1 @vcKOSGU = [KOSGU]
from OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/key/value',1) with ([KOSGU] VARCHAR(100) 'text()', [ABOUT] VARCHAR(250) '../@about')
WHERE [ABOUT] = "urn:entities-1c-ru:budget/forms/0503125/kosgu-mask"

SET @vcKSBU =  @vcKVD + @vcACCOUNT + @vcKOSGU
SET @vcPRP = '500' 

DECLARE curRD CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
   SELECT DISTINCT [iRD] = CASE [RD]
                              WHEN 'стр010' THEN 1
                              WHEN 'стр200' THEN 2
                              ELSE 3
                           END,
                   [RD]                     
   FROM OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/group/key/value',1) WITH ([RD] VARCHAR(100) 'text()', [ABOUT] VARCHAR(250) '../@about')
   WHERE [ABOUT] = "urn:entities-1c-ru:reports/row-ref" AND
         [RD] IN ('стр010','стр200')
   ORDER BY [iRD]  
   
OPEN curRD

FETCH NEXT 
FROM curRD 
INTO @iRD,@vcRD

SELECT TOP 1 @vcIsMoney = CASE [IS_MONEY]
                            WHEN 'True' THEN '1'
                            WHEN 'False' THEN '0'                            
                          END
FROM OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/key/value',1) WITH ([IS_MONEY] VARCHAR(100) 'text()', [ABOUT] VARCHAR(250) '../@about')
WHERE [ABOUT] = "urn:entities-1c-ru:budget/payment-token"

WHILE @@FETCH_STATUS = 0
BEGIN
--   SELECT @iRD,@vcRD,@vcIsMoney
 

   SELECT [COL] = CASE [ABOUT]
                     WHEN 'urn:entities-1c-ru:budget/classification/administrator/corresponding' THEN '2'
                     WHEN 'urn:entities-1c-ru:budget/classification/administrator' THEN '51'
                     WHEN 'urn:entities-1c-ru:budget/classification/expenditures/chapter' THEN '52'
                     WHEN 'urn:entities-1c-ru:budget/classification/expenditures/clause/program' THEN '53'
                     WHEN 'urn:entities-1c-ru:budget/classification/expenditures/kind' THEN '54'                               
                     WHEN 'urn:entities-1c-ru:budget/classification/kosgu' THEN '55'
                     WHEN 'urn:entities-1c-ru:budget/account/corresponding' THEN '81'
                     WHEN 'urn:entities-1c-ru:budget/classification/kosgu/corresponding' THEN '82'
                  END,
         [ID],
         [VALUE]
   INTO #tabForPivotA
   FROM OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/group/group/key',1) 
   WITH ([VALUE] VARCHAR(100) 'value/text()', [ABOUT] VARCHAR(250) '@about', [ID] INT '@mp:parentid', [RD] VARCHAR(100) '../../key/value/text()')
   WHERE [ABOUT] NOT IN ('urn:entities-1c-ru:budget/classification/expenditures/clause',
                         'urn:entities-1c-ru:budget/classification/expenditures/clause/subprogram') AND
         [RD] = @vcRD
                         
   SELECT [COL] = REPLACE([ABOUT],'urn:entities-1c-ru:user/resource/гр',''),
          [ID],
          [VALUE]
   INTO #tabForPivotB
   FROM OPENXML (@iXML_DOC_HANDLE, '/envelope/group/group/group/group/group/resource',1) 
   WITH ([VALUE] NUMERIC(19,4) 'value/text()', [ABOUT] VARCHAR(250) '@about', [ID] INT '@mp:parentid', [RD] VARCHAR(100) '../../key/value/text()')
   WHERE [RD] = @vcRD

   INSERT @tabImport([TXT],
                     [RD],
                     [PRP],
                     [KSBU])
   SELECT RTRIM([C].[Name]) + '|' +
          CAST([B].[6] AS VARCHAR(50)) + '|' +
          CAST([B].[7] AS VARCHAR(50)) + '|' +
          ISNULL(@vcIsMoney,'') + '|' +
          LEFT(RTRIM(ISNULL([2],''))+'000',3)+
          LEFT(RTRIM(ISNULL(NULL,''))+'           ',11)+
          RIGHT('00'+RTRIM(ISNULL(NULL,'')),2)+
          LEFT(RTRIM(ISNULL([51],''))+'000',3)+
          LEFT(RTRIM(ISNULL([52],''))+'0000',4)+
          LEFT(RTRIM(ISNULL([53],''))+'0000000',7)+
          LEFT(RTRIM(ISNULL([54],''))+'000',3)+
          --LEFT(RTRIM(ISNULL([55],''))+'000',3)+          
          LEFT(RTRIM(ISNULL(@vcKVD,''))+'0',1)+
          LEFT(RTRIM(ISNULL(REPLACE([81],'.',''),''))+'00000',5)+
          LEFT(RTRIM(ISNULL([82],''))+'000',3),
          @iRD,
          @vcPRP,
          @vcKSBU
   FROM (
      SELECT [A].[ID],
             [2] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '2'), 
             [51] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '51'),
             [52] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '52'),
             [53] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '53'),
             [54] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '54'),
             [55] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '55'),
             [81] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '81'),
             [82] = (SELECT ISNULL(MAX([B].[VALUE]) ,'') FROM #tabForPivotA [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '82')
      FROM (SELECT DISTINCT [ID]
            FROM #tabForPivotA) [A]
   ) [A]
   FULL JOIN 
   (
      SELECT [A].[ID],
             [6] = (SELECT ISNULL(MAX([B].[VALUE]) ,0) FROM #tabForPivotB [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '6'), 
             [7] = (SELECT ISNULL(MAX([B].[VALUE]) ,0) FROM #tabForPivotB [B] WHERE [A].[ID] = [B].[ID] AND [B].[COL] = '7')
      FROM (SELECT DISTINCT [ID]
            FROM #tabForPivotB) [A] 
   ) [B] ON [A].[ID] = [B].[ID]
   LEFT JOIN dbo.[KL_ADMIN_BS] [C] ON [A].[2] = [C].[Code] 

   DROP TABLE #tabForPivotA
   DROP TABLE #tabForPivotB  
   
   FETCH NEXT 
   FROM curRD 
   INTO @iRD,@vcRD
END

UPDATE @tabImport
SET [TXT] = [TXT] + RIGHT('00000000' + CAST([ORDER] AS VARCHAR(50)),8)
WHERE [RD] > 0 

CLOSE curRD
DEALLOCATE curRD
 
DECLARE curImport CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
   SELECT DISTINCT [PRP],[KSBU]
   FROM @tabImport
   WHERE [PRP]  IS NOT NULL AND
         [KSBU] IS NOT NULL
OPEN curImport

FETCH NEXT
FROM curImport
INTO @vcPRP,
     @vcKSBU

WHILE @@FETCH_STATUS = 0
BEGIN
   IF OBJECT_ID('tempdb..#IMPORT_TABLE') IS NOT NULL
   BEGIN
      DROP TABLE #IMPORT_TABLE
   END        
                                  
   CREATE TABLE #IMPORT_TABLE([TXT] VARCHAR(1000),
                              [ORDER] INT IDENTITY(1,1))

   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]   
   FROM @tabImport
   WHERE [RD] = 0
   ORDER BY [ORDER]
   
   INSERT #IMPORT_TABLE([TXT]) VALUES ('REPORTS_ATR_ACC_2011=' + @vcKSBU)
   INSERT #IMPORT_TABLE([TXT]) VALUES ('REPORTS_ATR_PRP=' + @vcPRP)
   INSERT #IMPORT_TABLE([TXT]) VALUES ('REPORTS_FILTER_KBK=Не отобрано')
   
   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=1')

   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabImport
   WHERE [RD] = 1 AND
         [PRP] = @vcPRP AND
         [KSBU] = @vcKSBU

   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=2')

   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabImport
   WHERE [RD] = 2 AND
         [PRP] = @vcPRP AND
         [KSBU] = @vcKSBU

   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=3')

   INSERT #IMPORT_TABLE([TXT])
   SELECT [TXT]
   FROM @tabImport
   WHERE [RD] = 3 AND
         [PRP] = @vcPRP AND
         [KSBU] = @vcKSBU

   INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=4')

   EXEC dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                      @liRepeatRequest,
                                      @tIsAppend,
                                      @bDinamicRows,
                                      @iLINK_SELF,
                                      @tMode

   FETCH NEXT
   FROM curImport
   INTO @vcPRP,
        @vcKSBU
END


CLOSE curImport
DEALLOCATE curImport

--select * from #IMPORT_TABLE order by [order]
EXEC sp_xml_removedocument @iXML_DOC_HANDLE

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_125_1C_XML] 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].[WEB_PRINT_OPTIONS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_PRINT_OPTIONS]
GO

CREATE  PROCEDURE dbo.WEB_PRINT_OPTIONS
		@varKSiLSF	int
AS
begin
	declare @print_object_method varchar(100), @code_form varchar(30)
	select @print_object_method = print_object_method, @code_form = RF.Code from report_saved_forms RSF join report_forms RF on RSF.link_form = RF.link_form and RSF.link_saved_form = @varKSiLSF

	SELECT	[alias] = 'REP_OPTION_PRINT', 
			[order] = convert(smallint,1),
			[tab_name] = 'Диалог печати',
			[link_table] = 888,--convert(int,0),
			[table_type] = 88

	if @print_object_method LIKE '%print_387%'
	begin	
		SELECT * 
		FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 1 AS VALUE, 0 AS [LEFT]
			UNION
			SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
			UNION
			SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 0 AS VALUE, 0) A
		ORDER BY ORDERS
	END
   ELSE
	if @print_object_method like '%svodprint_ask_page%' 
	begin	
		SELECT * 
		FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 0 AS VALUE, 0 AS [LEFT]
			UNION
			SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
			UNION
			SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0) A
		ORDER BY ORDERS
	end
	else 
		if @print_object_method like '%svodprint_ask_variant%'
		begin	
			SELECT * 
			FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 0 AS VALUE, 0 AS [LEFT]
				UNION
				SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
				UNION
				SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0
				UNION
				SELECT '' , 'GROUP' AS [TYPE], 8 AS ORDERS, 'Шаблон:' AS NAME, 'GROUP2' AS CODE, 0 AS VALUE, 1
				UNION
				SELECT 'GROUP2', 'OPTION' AS [TYPE], 9 AS ORDERS, 'Стандартный шаблон' AS NAME, 'STANDART_SHABLON' AS CODE, 0 AS VALUE, 0
				UNION
				SELECT 'GROUP2', 'OPTION' AS [TYPE], 10 AS ORDERS, 'Дополнительный шаблон' AS NAME, 'DOP_SHABLON' AS CODE, 0 AS VALUE, 0) A
			ORDER BY ORDERS
		end
		else
			if @print_object_method like '%svodprint_page_itog%'
			begin	
				SELECT * 
				FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 0 AS VALUE, 0 AS [LEFT]
                  UNION
                  SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0
                  UNION
                  SELECT '', 'CHECK' AS [TYPE], 8 AS ORDERS, 'Все атрибуты в один отчет' AS NAME, 'ATR_IN_ONE' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT '' , 'GROUP' AS [TYPE], 9 AS ORDERS, 'Печатать промежуточные итоги' AS NAME, 'GROUP2' AS CODE, 0 AS VALUE, 1
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 12 AS ORDERS, 'Промежуточные итоги по ЦСР' AS NAME, 'ITOG_CSR' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 13 AS ORDERS, 'Программа' AS NAME, 'ITOG_P' AS CODE, 0 AS VALUE, 2
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 14 AS ORDERS, 'Подрограмма' AS NAME, 'ITOG_PP' AS CODE, 0 AS VALUE, 2
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 15 AS ORDERS, 'Подраздел' AS NAME, 'ITOG_PRZ' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 16 AS ORDERS, 'Раздел' AS NAME, 'ITOG_RZ' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT 'GROUP2', 'CHECK' AS [TYPE], 17 AS ORDERS, 'Администратор' AS NAME, 'ITOG_ADM' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT '', 'CHECK' AS [TYPE], 18 AS ORDERS, 'Не печатать промежуточные итоги' AS NAME, 'NO_ITOG' AS CODE, 0 AS VALUE, 0
                  UNION
                  SELECT '', 'CHECK' AS [TYPE], 18 AS ORDERS, 'Не печатать промежуточные итоги только в расходах' AS NAME, 'NO_ITOG_RASH' AS CODE, 0 AS VALUE, 0
                  UNION 
                  SELECT '' , 'GROUP' AS [TYPE], 19 AS ORDERS, 'Детализировать плановые суммы по ЭКР в Расходах:' AS NAME, 'GROUP2' AS CODE, 3 AS VALUE, 1
                  WHERE @print_object_method like '%svodprint_page_itog_127%'
                  UNION
                  SELECT 'GROUP2', 'OPTION' AS [TYPE], 20 AS ORDERS, '000' AS NAME, 'RASH_EKR1' AS CODE, 0 AS VALUE, 0
                  WHERE @print_object_method like '%svodprint_page_itog_127%'
                  UNION
                  SELECT 'GROUP2', 'OPTION' AS [TYPE], 21 AS ORDERS, 'x00' AS NAME, 'RASH_EKR2' AS CODE, 0 AS VALUE, 0 A
                  WHERE @print_object_method like '%svodprint_page_itog_127%'
                  UNION
                  SELECT 'GROUP2', 'OPTION' AS [TYPE], 22 AS ORDERS, 'xxx' AS NAME, 'RASH_EKR3' AS CODE, 0 AS VALUE, 0 A
                  WHERE @print_object_method like '%svodprint_page_itog_127%'
) A
				ORDER BY ORDERS
			end
			else
				if @print_object_method like '%svodprint_page_no_itog%'
				begin	
					SELECT * 
					FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 0 AS VALUE, 0 AS [LEFT]
						UNION
						SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
						UNION
						SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0
						UNION
						SELECT '', 'CHECK' AS [TYPE], 8 AS ORDERS, 'Все атрибуты в один отчет' AS NAME, 'ATR_IN_ONE' AS CODE, 0 AS VALUE, 0
						UNION
						SELECT '' , 'CHECK' AS [TYPE], 9 AS ORDERS, 'Не печатать промежутоные итоги' AS NAME, 'NO_ITOG' AS CODE, 1 AS VALUE, 0) A
					ORDER BY ORDERS
				end
				else
					if @print_object_method like '%svodprint_page_one%'
					begin	
						SELECT * 
						FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 0 AS VALUE, 0 AS [LEFT]
							UNION
							SELECT '', 'CHECK' AS [TYPE], 5 AS ORDERS, 'Печать только ненулевых столбцов' AS NAME, 'PRINT_COL' AS CODE, 0 AS VALUE, 0
							UNION
							SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0
							UNION
							SELECT '', 'CHECK' AS [TYPE], 8 AS ORDERS, 'Все атрибуты в один отчет' AS NAME, 'ATR_IN_ONE' AS CODE, 0 AS VALUE, 0) A
						ORDER BY ORDERS
					END
					else
					if @print_object_method like '%svodprint_14_ask%'
					begin	
						SELECT * 
						FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печатать промежутонче итоги' AS NAME, 'PRINT_PODITOG' AS CODE, 0 AS VALUE, 0 AS [LEFT]) A
						ORDER BY ORDERS
					end
					else

						SELECT * 
						FROM (SELECT '' AS [GROUP], 'CHECK' AS [TYPE], 4 AS ORDERS, 'Печать пустых строк' AS NAME, 'PRINT_NULL' AS CODE, 1 AS VALUE, 0 AS [LEFT]
							UNION
							SELECT '', 'CHECK' AS [TYPE], 7 AS ORDERS, 'Печать символа "-" вместо нуля' AS NAME, 'PRINT_DEFIS' AS CODE, 1 AS VALUE, 0) A
						ORDER BY ORDERS

	
	
end
GO
GRANT ALL ON dbo.[WEB_PRINT_OPTIONS] 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.[SD_NUO_DGH_NALOG]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_NUO_DGH_NALOG]

GO

CREATE   Procedure [dbo].SD_NUO_DGH_NALOG
@varKSdDateS datetime,
@varKSYear int,
@varKSPol int,
@LINK_SFIN INT = NULL,
@KATEG TINYINT = 1
as
declare @varKSYEAR1 int, @varKSType int, @TARIF TINYINT

DECLARE @SC_DATE DATETIME
SET @SC_DATE = DBO.SALARYCALCPERIOD()

SET @TARIF = ISNULL((SELECT TOP 1 ENVD FROM dbo.SAL_SFIN WHERE LINK = @LINK_SFIN),0) + 1
SET @TARIF = (CASE WHEN ISNULL(@KATEG,0) > @TARIF THEN ISNULL(@KATEG,0) ELSE @TARIF END)

if @varKSPol = 1 
	set  @varKSYEAR1 = 1952
else
	set @varKSYEAR1 = 1956
	
--Список видов взносов на данный период	
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 <= @SC_DATE 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)

--
set @varKSType = (case when @varKSYear<=@varKSYEAR1 then 1 when (@varKSYear>@varKSYEAR1 and @varKSYear<1967) then  2 else 3 end)

DECLARE @PERC_TRAVM_IVALID NUMERIC(18,2)
SET @PERC_TRAVM_IVALID = (SELECT TOP 1 MP.summa FROM dbo.MINROT_PAYS MP WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.MINROT WHERE PERIOD<=@varKSdDateS ORDER BY PERIOD DESC))
	
select 
	link,
	code,
	name,
	way_calc,
	[percent] =	(case when way_calc NOT IN (6,7,8,9) then
							(CASE WHEN way_calc = 5 AND @TARIF = 3 THEN
								@PERC_TRAVM_IVALID
							ELSE
								(	select top 1 [percent] 
									from dbo.dictionary_range 
									where 
										(	
											TARIF = @TARIF 
											OR --Для подоходного налога по общему тарифу всегда
											TARIF = 1 AND LINK_PAYS IN (SELECT LINK FROM dbo.PAYS WHERE [OBJECT] = 2 AND WAY_CALC IN (4,5,6)) 
										)
										AND 
											LINK_PAYS = p.LINK and [DATE]<=@varKSdDateS order by [DATE] desc, PREDEL asc
								)  
											
							END)	
			else  (select top 1 (case when @varKSType = 1 then percent1 
								when @varKSType = 2  then PERCENT2 else PERCENT3 end) from dbo.dictionary_range_pf
							where TARIF = @TARIF AND LINK_PAYS = p.LINK and DATE<=@varKSdDateS order by DATE desc, PREDEL asc)  
			 end),
	[object] = p.object
into
	#Temp
from 
	pays p
where 
	(p.object =2) 
	or 
	(p.object = 3 and EXISTS (SELECT * FROM #PAYS3 P3 WHERE P3.LINK = P.LINK))

select * from #Temp where [percent] is not null

drop table #Temp


GO


GRANT EXECUTE ON dbo.[SD_NUO_DGH_NALOG] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_SZV62]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_SZV62]

GO
CREATE PROCEDURE dbo.SZV4_PRINT_SZV62(@Link int) 
AS

DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
	@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9), @Month int, @Year int, @date datetime

SELECT 
	@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = NAME,
	@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP,
	@Month = month_end, @year = year_begin
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
WHERE P.link = @link

Set @date = dbo.ConvertDMY2Date(1,@Month,@Year)
Set @date = dbo.DateEndOfMonth(@date)

Select 	
	[YEAR] = ISNULL(CASE WHEN year_begin <> 2010 THEN year_begin ELSE NULL END ,0),
	[INN] = @varKSINN,
	[KPP] = @varKSKPP,
	OKPO = @varKSOKPO,
	[REG_NOM_PF] = @varKSNOM_PF, 
	[CODE] = K.CODE,
	[TYPE] = P.vid_kor,
	[PER] = ISNULL(CASE WHEN year_begin <> 2010 THEN PER ELSE NULL END ,0),
	[PER10] = ISNULL(CASE WHEN year_begin = 2010 THEN PER ELSE NULL END ,0),
	[PER_EDT] = ISNULL(PER_EDT,0),
	[YEAR_EDT] = ISNULL(YEAR_EDT,0),
	[CNT] = CASE WHEN S.[orders] % 5 = 0 THEN 5 ELSE S.[orders] % 5 END,
	[ID] = S.orders,
	[NGROUP] = S.pachka,
	[NDOC] = CEILING (CAST(S.orders AS FLOAT) /5 ),
	[FIO] = FIO2,
	[FM],
	[IM],
	[OT],	
	[ADDRESS] = [ADDRESS],
	[ADDRESS2] = ADDRESS2,
	[INSUR] = COALESCE(S.sum_doh,0), --Это сумма начисленных взносов на страхов. часть
	[INSUR1] = COALESCE(S.INSUR,0)+COALESCE(S.SUM_UPLATA_DOLGA_STR,0), --Это сумма уплаченных взносов на страхов. часть
	[GAIN] = COALESCE(S.GAIN,0), --Это сумма начисленных взносов на накопит. часть
	[GAIN1] = COALESCE(S.DOP,0) + COALESCE(S.SUM_UPLATA_DOLGA_NAK,0), --Это сумма уплаченных взносов на накопит. часть
	[DATE_BEG] = date1,
	[DATE_SACK] = date2,
	S.PF_NUM AS PFNUMBER, 
	@varKSname AS DEP_NAME,
	DATE_CRT = @date,
	DATE_DOC = [date]
from 
	dbo.SA_SZV4_PACHKA P 
	INNER JOIN dbo.SA_SZV4_SVEDENIA S ON P.link = S.link
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
	LEFT JOIN dbo.SA_SZV4_STAZH ST ON S.link1 = ST.link
where
	P.link = @Link
	and S.forma = 2
	and P.proverka = 1
order by
	S.pachka, S.orders


GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_SZV62] 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_DEP_ACC_DETAILS_TABLE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_DEP_ACC_DETAILS_TABLE]
GO




/*
© Кейсистемс (Keysystems), 2005
*/

CREATE PROCEDURE dbo.BB_DEP_ACC_DETAILS_TABLE
	@varKSiDepAcc 	INT,
	@varKSdDateB 	DATETIME = null,
	@varKSdDateE 	DATETIME,
	@varKSiEmptyAcc tinyint = 0
	

AS

	IF @varKSdDateB IS NULL
		SET @varKSdDateB = dbo.DateBeginOfYear(@varKSdDateE)

	DECLARE @varKSiOwnDep	INT,
		@varKSiFYear	INT,
		@cSource	char(1)	


	set @varKSiOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	set @varKSiFYear = YEAR(@varKSdDateE)

	-- Ассигнования
	DECLARE @varKSTableAssign TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	--Лимиты
	DECLARE @varKSTableLimit TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Кассовый расход 
	DECLARE @varKSTableKassa TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Финансирование
	DECLARE @varKSTableFinans TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(19,2))

	-- Бюджетные обязательства
	DECLARE @varKSTableBO TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Денжные обязательства
	DECLARE @varKSTableDO TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	DECLARE @varKSTableKP TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	if exists(select * from dbo.DEPARTMENT_ACCOUNT_SOURCE A inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc and S.CODE = '1')
		set @cSource = '1'
	else 
		set @cSource = '2'



	-- Ассигнования
	/*INSERT INTO @varKSTableAssign
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FINANS_ASSIGN', @cSource, 1, @varKSiOwnDep)
	WHERE DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL*/


	--Кассовый план
	INSERT INTO @varKSTableKP
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FB_PLAN', @cSource, 1, @varKSiOwnDep)
	WHERE DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL



	exec dbo.BufferClear 'ISP_BO'
	exec dbo.BufferClear 'ISP_DO'
	exec dbo.BufferClear 'ISP_KR'
	exec dbo.BufferClear 'ISP_KR_V'
	exec dbo.BufferClear 'LIMIT'
	exec dbo.BufferClear 'ASSIGN'
	exec dbo.BufferClear 'FIN'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_BO' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '502' and SA.cAnalit = '11' or 
									 SA.cSinth = '506' and SA.cAnalit = '00'or 
									 SA.cSinth = '506' and SA.cAnalit = '10')

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_DO' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '502' and SA.cAnalit = '12'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_KR' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '304' and SA.cAnalit = '05' or 
									 SA.cSinth = '201' and (SA.cAnalit = '11' or SA.cAnalit = '21' or SA.cAnalit = '27'))

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_KR_V' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '304' and SA.cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'LIMIT' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '501' and SA.cAnalit = '13' or 
									SA.cSinth = '506' and SA.cAnalit = '00'or 
									SA.cSinth = '506' and SA.cAnalit = '10')

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ASSIGN' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '503' and SA.cAnalit = '13' or 
									SA.cSinth = '504' and SA.cAnalit = '00'or 
									SA.cSinth = '506' and SA.cAnalit = '10')

	INSERT INTO BUFFER (link, id)
	select SA.link, 'FIN' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '508' 


	
	--Ассиггнования
	INSERT INTO @varKSTableAssign
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ASSIGN')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	--Лимиты
	INSERT INTO @varKSTableLimit
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'LIMIT')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	
	-- Бюджетные обязательства
	INSERT INTO @varKSTableBO
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_BO') ) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2
	
	-- Денежные обязательства
	INSERT INTO @varKSTableDO
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_DO')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	-- Кассовый расход 
	INSERT INTO @varKSTableKassa
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa, KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_KR') union all
			select LINK, -summa, DT_DEP_ACC, DEP_LINK, DT_VKR, DT_EKR, DT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, 'ISP_KR_V', NULL)) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	-- Финансирование
	INSERT INTO @varKSTableFinans
	SELECT dt_vkr, dt_ekr, isnull(dt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,DT_DEP_ACC, DEP_LINK, DT_VKR, DT_EKR, DT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, 'FIN', NULL) union all
		  select LINK, summa, KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'FIN')) A	
	WHERE (DT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by dt_vkr, dt_ekr, dt_ap2

	
	INSERT INTO @varKSTableFinans
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FB_RESULT_FINANS', @cSource, 1, @varKSiOwnDep) 
	WHERE DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL
	UNION
	SELECT F.VKR, F.EKR, 0, SUM(MONEY_CURRENT)
	FROM FIN_RR_TABLE F
	INNER JOIN FIN_RR FRR ON FRR.LINK_G_PROV = F.LINK_UP AND (DEST_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DEST_ACC is null)  
	INNER JOIN G_PROV GP ON GP.LINK = FRR.LINK_G_PROV AND 
				GP.DATE_PROV <= @varKSdDateE AND
				YEAR(GP.DATE_PROV) = @varKSiFYear AND
				GP.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_IN')
				AND DEP = @varKSiOwnDep
				
	GROUP BY VKR, EKR
	
	exec dbo.BufferClear 'ISP_BO'
	exec dbo.BufferClear 'ISP_DO'
	exec dbo.BufferClear 'ISP_KR'
	exec dbo.BufferClear 'ISP_KR_V'
	exec dbo.BufferClear 'LIMIT'
	exec dbo.BufferClear 'ASSIGN'
	exec dbo.BufferClear 'FIN'

	--объединяем и добавляем расшифровку 
	SELECT CD.VKR, CD.EKR, CD.DOP_CL,
		[CHECKED] = 0,	
		[UPD] = 0,
		[DEL] = 0,
		[LOCKED] = convert(bit,0),
		[VKR_CODE] = VKR.CODE,
		[EKR_CODE] = EKR.CODE,
		[DOP_CL_CODE] = DC.CODE,
		[VKR_NAME] = VKR.NAME,
		[EKR_NAME] = EKR.NAME,
		[DOP_CL_NAME] = DC.NAME,
		[SUMMA_A] = ISNULL(A.SUMMA,0),
		[SALDO_A] = ISNULL(A.SUMMA,0) - case O.ASSIGN when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_L] = ISNULL(L.SUMMA,0),
		[SALDO_L] = ISNULL(L.SUMMA,0) - case O.LBO    when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_BO] = ISNULL(B.SUMMA,0),
		[SUMMA_DO] = ISNULL(D.SUMMA,0),
		[SUMMA_K] = ISNULL(K.SUMMA,0),
		[SUMMA_F] = ISNULL( F.SUMMA,0),
		[SALDO_F] = ISNULL(F.SUMMA,0) - case O.FIN	  when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_KP] = ISNULL( KP.SUMMA,0),
		[SALDO_KP] = ISNULL(KP.SUMMA,0) - case O.KP   when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end
		
	FROM (SELECT VKR, EKR, DOP_CL FROM @varKSTableAssign where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableLimit where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableBO where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableDO where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableKassa where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableFinans where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableKP where SUMMA <> 0) CD
	LEFT JOIN @varKSTableAssign A ON isnull(CD.VKR,0) = isnull(A.VKR,0) AND isnull(CD.EKR,0) = isnull(A.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(A.DOP_CL,0)
	LEFT JOIN @varKSTableLimit L  ON isnull(CD.VKR,0) = isnull(L.VKR,0) AND isnull(CD.EKR,0) = isnull(L.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(L.DOP_CL,0)
	LEFT JOIN @varKSTableBO B  ON isnull(CD.VKR,0) = isnull(B.VKR,0) AND isnull(CD.EKR,0) = isnull(B.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(B.DOP_CL,0)
	LEFT JOIN @varKSTableDO D  ON isnull(CD.VKR,0) = isnull(D.VKR,0) AND isnull(CD.EKR,0) = isnull(D.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(D.DOP_CL,0)
	LEFT JOIN @varKSTableKassa K  ON isnull(CD.VKR,0) = isnull(K.VKR,0) AND isnull(CD.EKR,0) = isnull(K.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(K.DOP_CL,0)
	LEFT JOIN @varKSTableFinans F  ON isnull(CD.VKR,0) = isnull(F.VKR,0) AND isnull(CD.EKR,0) = isnull(F.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(F.DOP_CL,0)
	LEFT JOIN @varKSTableKP KP  ON isnull(CD.VKR,0) = isnull(KP.VKR,0) AND isnull(CD.EKR,0) = isnull(KP.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(KP.DOP_CL,0)
	LEFT JOIN KL_KBK VKR on CD.vkr = VKR.link
	LEFT JOIN KOSGU EKR on CD.ekr = EKR.link
	LEFT JOIN DOP_CLASSIF DC on CD.DOP_CL = DC.link
	left join DEP_ACC_DETAILS_OPTIONS O on 1 = 1
	ORDER BY VKR.CODE, EKR.CODE, DC.CODE 
	
SELECT * FROM @varKSTableFinans where SUMMA <> 0 and EKR = 44 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_DEP_ACC_DETAILS_TABLE to public
GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_ONE_ATR1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_ONE_ATR1]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_ONE_ATR1]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS
	if isnull(@WEB_excel, 0) <> 1
		select '' col1 
   
   DECLARE @iLF INT, @iLT INT , @tOT TINYINT , @atr VARCHAR(50)
   
   SELECT @iLF = link_form FROM dbo.report_saved_forms WHERE [Link_Saved_Form] = @LSF
 
   DECLARE cur CURSOR LOCAL STATIC FOR
      SELECT link_table, orders 
      FROM dbo.[REPORT_TABLES] rt 
      WHERE rt.[Link_Form] = @iLF
      
   OPEN [cur]
   
   FETCH NEXT FROM cur INTO @iLT, @tOT
   
   WHILE @@fetch_status = 0
   BEGIN
      EXEC [dbo].[rn_get_all_adm_table] @LSF, @tOT, @bDeleteEmptyRows, @AtrInOnePage, 0

       
      FETCH NEXT FROM cur INTO @iLT, @tOT
   END      
   
   close [cur]
   DEALLOCATE [cur]
   

	if isnull(@WEB_excel, 0) <> 1
	select cells as style,style as value from report_print_style where 1=0 order by cells


GO
GRANT ALL ON dbo.[RO_PRINT_ONE_ATR1] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_WEB_EDIT_OBJECT_METHOD_SVOD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_EDIT_OBJECT_METHOD_SVOD]
GO

/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB

	2010: только печать
*/


CREATE       PROCEDURE dbo.RO_WEB_EDIT_OBJECT_METHOD_SVOD
	@varKSnLink	bigint,
	@varKSnTree	int = 0,
    @bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @varKSisHeader int = 0, -- 1 создаем только реквизиты
    @repository int = 0 -- 1 данные для хранилища
AS

declare @iLF int
DECLARE @DATE	datetime,
	@PType	tinyint,
	@PNom	tinyint,
	@DATE1 datetime,
	@DATE2 datetime, 
	@Periodic tinyint,
	@LSF	int,
	@Mode	int,
	@LinkOrg int,
	@LinkBudg int,
    @atributs varchar(250),
	@Start_Date datetime,
	@print_form_server tinyint,
	@print_object_method varchar(1000),
	@AtrInOnePage tinyint,
	@notNullCol tinyint,
	@replaceZero varchar(1),
	@Poditog	int

set @LinkOrg = dbo.RO_SVOD_ORG(@varKSnTree)
set @LinkBudg = dbo.RO_SVOD_BUDG(@varKSnTree)
set @Mode = convert(int, @varKSnLink/4294967296)
set @varKSnLink = @varKSnLink - @Mode * 4294967296
set @Mode = abs(@Mode)
declare @iCode_Col int,@atr varchar(100),@tmp_table_main varchar(100),@tmp_table varchar(100),@cnt int,@LF int,@code_form varchar(50),@begin_date datetime,@period_type int,@period_number int,@link_org int,@link_type_svod int
create table #LSF (lsf int, link_Form int, codeForm char(20), startDate datetime)

select @code_form=code, @start_date = start_date, @LF=link_form, @print_object_method = print_object_method from report_forms where link_form=(select top 1 link_form from report_saved_forms where link_saved_form=@varKSnLink)

if @print_object_method like 'svodprint_page_itog%' or @print_object_method like 'svodprint_new_gen%' or @print_object_method like 'svodprint_page_no_itog%' or @print_object_method like 'svodprint_page_one_atr%' or @print_object_method like 'svodprint_variant_delempty%'  or @print_object_method like 'print_387%'
	set @print_form_server = 1
else
	set @print_form_server = 0
   
CREATE TABLE #WEB_C_NASTR (WEB TINYINT) 
INSERT #WEB_c_NASTR (WEB)
VALUES (1)  

--проверим есть ли атрибуты у формы
select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink)

if @varKSnLink<0
    select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = -@varKSnLink

/* Список возвращаемых таблиц */
SELECT	[alias] = 'REP_HEAD', 
	[order] = convert(smallint,0),
	[tab_name] = 'Реквизиты',
	[link_table] = convert(int,0),
	[table_type] = convert(smallint,2)
UNION
SELECT	[alias] = 'REP_ATR', 
	[order] = convert(smallint, 1),
	[tab_name] = 'Атрибуты',
	[link_table] = convert(int, -98),
	[table_type] = convert(smallint, 0)
    WHERE @atributs<>'' 
UNION
SELECT	[alias] = 'REP_TABLE_' + ltrim(convert(char(2),orders)), 
	[order] = (orders - 1) * 3 + 1,
	[tab_name] = name,
	[link_table] = Link_Table,
	[table_type] = val_type
FROM RN_REPORT_TABLES
WHERE ((@varKSisHeader=0 and @varKSnLink>0 and Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink))
	OR (@varKSisHeader=0 and @varKSnLink<0 and Link_Form = abs(@varKSnLink)))
	and orders <= isnull((select count_tables from dbo.RO_PRINT_COUNT_TABLES where Code_Form = @code_form and start_date = @start_date),30)
UNION
SELECT	[alias] = 'REP_TABLE_' + ltrim(convert(char(2),2)), 
	[order] =  3 + 1,
	[tab_name] = 'т2',
	[link_table] = Link_Table,
	[table_type] = val_type
FROM RN_REPORT_TABLES
WHERE ((@varKSisHeader=0 and @varKSnLink>0 and Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink))
	OR (@varKSisHeader=0 and @varKSnLink<0 and Link_Form = abs(@varKSnLink)))
	and  '0503387M' = @code_form and '20120501' = @start_date
UNION
SELECT	[alias] = 'REP_NASTR', 
	[order] = convert(smallint, 99),
	[tab_name] = 'Настройки печати',
	[link_table] = convert(int, 0),
	[table_type] = convert(smallint, -1)
ORDER BY [order]



/* Данные об отчете */

create table #org (code varchar(20), name varchar(250))
CREATE TABLE #note (link INT, note_all TEXT)

IF @varKSnLink > 0
BEGIN
	if object_id('tempdb..#REP_OPTION_PRINT') is NOT NULL
	begin
		set @bDeleteEmptyRows = convert(bit, 1 - isnull((select value from #REP_OPTION_PRINT where code = 'PRINT_NULL'), 0))
	end

	CREATE TABLE #REP_HEAD_temp ("checked" Int,"UPD" Int,"del" Int,"date" DateTime,"date_prov" DateTime,"link" Int,"period" VarChar(17),"name" VarChar(200),"code" Char(20),"Start_Date" Char(10),"link_saved_form" Int,"Link_form" Int,"Version" SmallInt,"begin_date" DateTime,"period_type" TinyInt,"period_type_web" Int,"period_number" TinyInt,"period_year" Int,"link_organization" Int,"dep_name" VarChar(254),"dep_code" Char(10),"isUpload" TinyInt,"isSvod" TinyInt,"isChangeAnalit" Bit,"IsRO" TinyInt,"Note" VarChar(4000),"Link_Type_Svod" Int,"Type_Svod" VarChar(250),"IsUsedRazdel" Int,"IsUsedCelSt" Int,"IsUsedRashod" Int,"LinkRazdel" Int,"LinkCelSt" Int,"LinkRashod" Int,"CodeRazdel" VarChar(1),"NameRazdel" VarChar(1),"CodeCelSt" VarChar(1),"NameCelSt" VarChar(1),"CodeRashod" VarChar(1),"NameRashod" VarChar(1),"Print_Object_Method" VarChar(200),"Query_Add_Module" VarChar(200),"Query_Before" VarChar(200),"Query_RepMaker" VarChar(200),"Query_Report" VarChar(200),"Query_Report_Path" VarChar(200),"Decript_Proc" VarChar(30),"IsRemoteAccess" TinyInt,"RULES" TinyInt,"isCalcItog" Int,"IsRO_MASK" Int,"CountSave" Int,"Object" Char(254),[IS_AUTOFILL] TINYINT,"IsCopy" BIT,"End_Date" Char(10), Query_Report_New varchar(250), Print_Object_Method_New varchar(250))

	insert #REP_HEAD_temp 
EXEC dbo.[I_REPORT_USER_SAVED_FORM] @varKSiLinkSF = @varKSnLink, @bIsWeb = 1

	if @bDeleteEmptyRows = 1
	begin
		update #REP_HEAD_temp
		set Query_Add_Module = LEFT(Query_Add_Module, CHARINDEX('.', Query_Add_Module) - 1) + '_del' + substring(Query_Add_Module, CHARINDEX('.', Query_Add_Module), 5),
			Query_Report = LEFT(Query_Report, CHARINDEX('.', Query_Report) - 1) + '_del' + substring(Query_Report, CHARINDEX('.', Query_Report), 5)
		where print_object_method like 'svodprint_variant_delempty%'
	end


	update #REP_HEAD_temp
	set Query_Add_Module = 'sv_0503360G_20091231.bas',
		Query_Report = 'sv_0503360G_20091231.xlt'
	where Code in ('0503360G', '0503360M')

	update #REP_HEAD_temp
	set Query_Add_Module = 'sv_0503360G_20091231.bas',
		Query_Report = 'sv_0503160G_20091231.xlt'
	where Code in ('0503160G', '0503160M')

	update #REP_HEAD_temp
	set Query_Add_Module = 'sv_0503360G_20091231.bas',
		Query_Report = 'sv_0503760M_20110101.XLT'
	where Code in ('0503760M', '0503760G')
   
   INSERT #note (link, note_all)
   EXEC dbo.RO_SAVED_FORM_NOTES @varKSnLink

	select T.*, Note_All from #REP_HEAD_temp T, #note N

	drop table #REP_HEAD_temp
END
ELSE BEGIN 
	EXEC dbo.[I_REPORT_USER_SAVED_FORM] @varKSnLink, @LinkOrg, @LinkBudg,
                                       @bIsWeb = 1
END

--exec I_REPORT_USER_SAVED_FORM @varKSnLink

/* Таблицы отчета, настройки цвета, настройки readonly */
DECLARE @iLTable	INT,
	@cRuStr		varchar(8000), @cPPP varchar(10), @cTmpTable varchar(100)
DECLARE tables_cursor CURSOR LOCAL FOR 
	SELECT link_table FROM report_tables 
		WHERE (@varKSisHeader=0 and @varKSnLink>0 and Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink))
			OR (@varKSisHeader=0 and @varKSnLink<0 and Link_Form = abs(@varKSnLink))
		order by orders 

declare @nameProcTable varchar(50)
set @nameProcTable='dbo.RI_PROC_T'
--IF @bDeleteEmptyRows is not null and (select code from report_forms where Link_Form = (select top 1 link_form from Report_Saved_Forms where link_saved_form = @varKSnLink))='428'
--begin
--    CREATE TABLE #REPORT_DINAMICS(link_SF int,Link_Col int,Code_Row varchar(50),Float_val numeric(20,4),Str_Val varchar(250))
    --создаем временную таблицу #REPORT_DINAMICS для подсчета подитогов в 428 форме
--    exec RN_CALCULATE_PODITOG @varKSnLink
--    set @nameProcTable='dbo.RI_PROC_T#'    
--end

--атрибуты
IF @atributs<>''
    begin
        IF @varKSnLink<0
            begin
                set @iLF=-@varKSnLink
                exec dbo.X_Get_Table_Name @cTmpTable output
                exec RN_GET_ATRIBUT_VALUES  null,@iLF,0, @tmp_table2 = @cTmpTable
                set @cRuStr = ''
                if @atributs like '%REPORTS_ATR_ADM%'
                begin
                     select @cPPP = Ved from dbo.dictionary_department where link = @LinkOrg
                     if @cPPP <> ''
                     begin
                        set @cRuStr = 'update ' + @cTmpTable + ' set REPORTS_ATR_ADM = ''' + RTRIM(@cPPP) + ''''
                     end                     
                end
                set @cRuStr = @cRuStr + ' select * from ' + @cTmpTable + ' drop table ' + @cTmpTable
                exec (@cRuStr)
            end
        else
            exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,0
    end

declare @cstr varchar(100)
exec X_GET_OPTION 'OBJ_FTP_REGION',0,@cStr output

select @LSF=link_saved_form,@begin_date=begin_date,@period_type=period_type,@period_number=period_number,@link_org=link_organization,@link_type_svod=link_type_svod from report_saved_forms where link_saved_form=@varKSnLink
IF @bDeleteEmptyRows is not null and @code_form in ('(72н)0503127M','0503127M','0503164G') and @cStr='Владимир'
	begin
		insert #LSF exec dbo.I_REPORT_ORG_FORMS_LIST @link_Org, @Begin_date, @period_Type, @period_number, 0, @link_type_svod 
		delete #LSF where link_form<>@LF
	end
--блокируем
IF @bDeleteEmptyRows is  null
	exec rn_lock_form @varKSnLink,0,'',1

EXEC dbo.X_GET_TABLE_NAME @tmp_table_main OUTPUT
EXEC dbo.X_GET_TABLE_NAME @tmp_table OUTPUT

select @cnt=count(*) from #LSF

set @bDeleteEmptyRows = 1
set @AtrInOnePage = 0
set @notNullCol = 0
set @replaceZero = '-'
if object_id('tempdb..#REP_OPTION_PRINT') is NOT NULL
begin
	set @bDeleteEmptyRows = convert(bit, 1 - isnull((select value from #REP_OPTION_PRINT where code = 'PRINT_NULL'), 0))
	set @AtrInOnePage = isnull((select value from #REP_OPTION_PRINT where code = 'ATR_IN_ONE'), 0)
	set @notNullCol = isnull((select value from #REP_OPTION_PRINT where code = 'PRINT_COL'), 0)
	set @replaceZero = case isnull((select value from #REP_OPTION_PRINT where code = 'PRINT_DEFIS'), 0) when 1 then '-' else '' end
	create table #Param_Print (Param varchar(100), Value int)
	
   IF EXISTS(SELECT * FROM #REP_OPTION_PRINT WHERE code = 'NO_ITOG_RASH' AND VALUE = 1)
   BEGIN
      insert #Param_Print (Param, Value)
      VALUES('NoItog_Rash', 1)

   END 
   ELSE BEGIN
	   insert #Param_Print (Param, Value)
	   select 'NoPoditog', Value
	   from #REP_OPTION_PRINT
	   where Code = 'NO_ITOG'
   END    

	set @Poditog = 0

	select @Poditog = @Poditog | (case Code when 'ITOG_CSR' then 2 when 'ITOG_PRZ' then 4 when 'ITOG_RZ' then 8 when 'ITOG_ADM' then 16 when 'ITOG_PP' then 32 when 'ITOG_P' then 64 else Value end)
	from #REP_OPTION_PRINT
	where Value = 1 and Code in ('ITOG_EKR','ITOG_VR','ITOG_CSR','ITOG_P','ITOG_PP','ITOG_RZ', 'ITOG_PRZ','ITOG_PRZ','ITOG_ADM')
	
	insert #Param_Print (Param, Value)
	values ('Poditog', @Poditog)
   
   IF EXISTS(SELECT * FROM #REP_OPTION_PRINT WHERE code = 'RASH_EKR3' AND VALUE = 1)
   BEGIN
      insert #Param_Print (Param, Value)
      VALUES('RASH_EKR', 3)
   END 
   IF EXISTS(SELECT * FROM #REP_OPTION_PRINT WHERE code = 'RASH_EKR2' AND VALUE = 1)
   BEGIN
      insert #Param_Print (Param, Value)
      VALUES('RASH_EKR', 2)
   END 
   IF EXISTS(SELECT * FROM #REP_OPTION_PRINT WHERE code = 'RASH_EKR1' AND VALUE = 1)
   BEGIN
      insert #Param_Print (Param, Value)
      VALUES('RASH_EKR', 1)
   END 
end

if @print_form_server = 1
begin
	exec dbo.RN_PRINT_SVOD 	@varKSnLink, @bDeleteEmptyRows, 1, @notNullCol, @AtrInOnePage, 1
end
else begin
		OPEN tables_cursor 
		FETCH NEXT FROM tables_cursor INTO @iLTable

	if @code_form like 'RRO%'
	begin
		exec dbo.RT_PRINT_RRO @varKSnLink,1, 0
		select @iLF = Link_Form from report_saved_forms where Link_Saved_Form = @varKSnLink
	--	select @iLTable = Link_Table from report_tables where Link_Form = @iLF and orders = 1
	--	exec dbo.RO_TOTAL_CELLS @iLTable, @varKSnLink

		exec dbo.RT_PRINT_RRO @varKSnLink,2, 0

		exec dbo.RT_PRINT_RRO @varKSnLink,3, 0
	--	select @iLTable = Link_Table from report_tables where Link_Form = @iLF and orders = 1
	--	exec dbo.RO_TOTAL_CELLS @iLTable, @varKSnLink

	end
	else begin
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @cnt>1
				begin
					select @LSF=link_saved_form,@begin_date=begin_date,@period_type=period_type,@period_number=period_number,@link_org=link_organization,@link_type_svod=link_type_svod from report_saved_forms where link_saved_form=@varKSnLink
					delete #LSF
					insert #LSF exec dbo.I_REPORT_ORG_FORMS_LIST @link_Org, @Begin_date, @period_Type, @period_number, 0, @link_type_svod 
					delete #LSF where link_form<>@LF
					select @iCode_Col=orders from report_coloumns where link_col=(select top 1 link_code_col from report_tables where link_table=@iLTable)
					select top 1 @LSF=lsf from #LSF 
					delete #LSF where lsf=@lsf
					set @atr=rtrim(dbo.RN_GET_ATR_VALUE(@lsf,'REPORTS_ATR_ADM'))
					SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@iLTable)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table_main
					execute (@cRuStr)		


					SET @cRuStr='UPDATE '+@tmp_table_main+' set COL'+ltrim(str(@iCode_Col))+'=rtrim('''+@atr+''')+RTRIM(COL'+ltrim(str(@iCode_Col))+'),CODE=rtrim('''+@atr+''')+RTRIM(CODE)'
					print @cRuStr
					execute (@cRuStr)
					while exists(select * from #LSF) 
						begin
							select top 1 @LSF=lsf from #LSF 
							delete #LSF where lsf=@lsf
							SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@iLTable)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table
		--					print @cRuStr
							execute (@cRuStr)					
							set @atr=dbo.RN_GET_ATR_VALUE(@lsf,'REPORTS_ATR_ADM')
							SET @cRuStr='UPDATE '+@tmp_table+' set COL'+ltrim(str(@iCode_Col))+'=rtrim('''+@atr+''')+COL'+ltrim(str(@iCode_Col))+',CODE=rtrim('''+@atr+''')+CODE'
		--					print @cRuStr
							execute (@cRuStr)					



							SET @cRuStr='insert '+@tmp_table_main+' select * from '+@tmp_table+' drop table ' +@tmp_table
		--					print @cRuStr
							execute (@cRuStr)					
						end

					SET @cRuStr='select * from  '+@tmp_table_main+'  drop table ' +@tmp_table_main
		--			print @cRuStr
					execute (@cRuStr)					
				/*	if not(@code_form like '0503360%' or @code_form like '0503160%')
					begin
						SET @cRuStr = ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', ''COL'', 2,default,default,default,'+str(ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),0))+',1'
			--			print @cRuStr
						execute (@cRuStr)					
					end*/
				end
			else
			begin	
				SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@iLTable)) + ' @varKSLSF = ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1' 
			/*	if not(@code_form like '0503360%' or @code_form like '0503160%')
					SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', ''COL'', 2,default,default,default,'+str(ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),0))+',1'
			*/	execute (@cRuStr)
			end
		--    SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@iLTable)) + ' @varKSLSF = ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')
		--	SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end)
		--	SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@iLTable)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', ''COL'', 1'
		--print    @cRuStr

			FETCH NEXT FROM tables_cursor INTO @iLTable
		END

	end
		CLOSE tables_cursor
		DEALLOCATE tables_cursor
end

/* Настройки печати */
DECLARE	@iLOrg	int,
	@DocDate	datetime
EXEC @iLOrg = getowndeplink 
IF @varKSnLink>0
	select @iLOrg = link_organization, @DocDate = begin_date from report_saved_forms where link_saved_form = @varKSnLink
ELSE
	select @DocDate = getdate()

declare @code_atr varchar(50),@str_val varchar(250)
create table #print_tmp (code_atr varchar(50),atr_name varchar(254),str_val varchar(1000))
    insert #print_tmp 
        exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,1
    set @cRuStr=''
    while exists(select * from #print_tmp)
        begin
            select top 1 @code_atr=code_atr,@str_val='#'+str_val from #print_tmp 
            set @cRuStr=@cRuStr+case when @cRuStr='' then ',' else ',' end + ''''+@str_val+''' as '+@code_atr        
            delete #print_tmp where code_atr=@code_atr
        end

declare @depname varchar(254), @depfullname varchar(254)
set @depname = dbo.GetDepName(@iLOrg, @DocDate)
set @depfullname = convert(varchar(254), dbo.GetDepFullName(@iLOrg, @DocDate))

set @cRuStr='
       SELECT [A].DEP_LINK, ''' + @depFullName + ''' as longname, ''' + @depName + ''' as ORGNAME, [A].GLBUH, [A].CHIEF, [A].CHIEF_POST, ''#'' + [A].okpo as okpo,[A].okato,[A].sono,[A].REGION,[A].OKVED,[A].CHIEF_FIN,[A].CHIEF_DIV, [A].OKVED1,''' + @depFullName + ''' as DEP_FULL_NAME,
          [A].[isp],
          [A].[isp_post],
          [A].[isp_tel],
          [A].[cb_name],
          [A].[cb_ogrn],
          [A].[cb_inn],
          [A].[cb_kpp],
          [A].[cb_address],
          [A].[ul_fio],
          [A].[ul_post],
		[notNULLCol] = ' + LTRIM(STR(@notNullCol)) + ',
	   [BUDG_NAME]			 = '''+coalesce((select [name] from dbo.kl_budg_type where link = @LinkBudg),'')+''',
	   [OKATO1]				 = ISNULL([A].[OKATO],''''),
       [DOC_DATE]            = '''+CONVERT(CHAR(10), @DocDate + 1, 104)+''',
		[cYear1]			=  '''+CONVERT(CHAR(4), YEAR(@DocDate))+''',
		[REM_YEAR]     =  '''+CONVERT(CHAR(4), YEAR(@DocDate))+''',
       [PERFORMER_FIO]       = ISNULL([B].[FIO],''''),
       [PERFORMER_POST]      = ISNULL([B].[POST],''''),
       [PERFORMER_PHONE]     = ISNULL([B].[PHONES],''''),
       [CHIEF_SOC_POST]      = ISNULL([C].[CHIEF_SOC_POST],''''),
       [CHIEF_SOC_FIO]       = ISNULL([C].[CHIEF_SOC_FIO],''''),
       [PERFORMER_SOC_POST]  = ISNULL([C].[PERFORMER_SOC_POST],''''),
       [PERFORMER_SOC_FIO]   = ISNULL([C].[PERFORMER_SOC_FIO],''''),
       [PERFORMER_SOC_PHONE] = ISNULL([C].[PERFORMER_SOC_PHONE],''''),
	   [VED] = ''#'' + A.[VED],
       [VED_NAME] = A.[VED_NAME],
       [OKATO2] = ''#'' + A.[OKATO],       
		[REPLACE_ZERO] = ''' + @replaceZero + ''''+@cRuStr+ ',
       CN.*' +
' FROM dbo.[PrintDoc_GetDepData2] ('+str(@iLOrg)+') [A]
LEFT JOIN dbo.[I_REPORT_OPTIONS_COMMON]  [C] ON 1=1
LEFT JOIN dbo.[RA_GET_USER_INFO](NULL)   [B] ON 1=1'
+ ' left join #WEB_C_NASTR CN ON 1=1'
--print 	@cRuStr
execute (@cRuStr)   

IF @print_object_method LIKE  '%svodprint_14_ask%'
   BEGIN 
	   exec dbo.BufferClear 'PRINT_14'
	   exec BufferPushTable '#REP_OPTION_PRINT', 'PRINT_14', 'VALUE'
   END	   

GO
GRANT ALL ON dbo.[RO_WEB_EDIT_OBJECT_METHOD_SVOD] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ro_get_all_atr_table]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ro_get_all_atr_table]
GO

/*

	© Кейсистемс (Keysystems), 2011
	Редактирование/создание отчета/свода/свода сводов в WEB
*/


CREATE       PROCEDURE dbo.ro_get_all_atr_table
	@varKSiLSF int,
	@varKSiTable  int, -- порядок таблицы
	@varKSbDeleteEmptyRows int=0,
	@varKSiAllAtr int=1,
	@varKScCodeAtr varchar(100),  -- код атрибута
   @varKSbTempTable BIT = 0,
   @varKScTempTable VARCHAR(100) = '' OUTPUT
AS

declare @iLF int,@LT int



declare @LSF int, @nameProcTable varchar(50),@cRuStr varchar(8000), @cStrNotItog varchar(1000), @cStrItog varchar(1000), @cStrCols varchar(1000)
set @nameProcTable='dbo.RI_PROC_T'

declare @iCode_Col int,@atr varchar(100),@tmp_table_main varchar(100),@tmp_table varchar(100),@cnt int,@LF int,@code_form varchar(50),@begin_date datetime,@period_type int,@period_number int,@link_org int,@link_type_svod int
create table #LSF (lsf int)

select @code_form=code,@LF=link_form from report_forms where link_form=(select top 1 link_form from report_saved_forms where link_saved_form=@varKSiLSF)

select @LT=LINK_TABLE from report_tables where link_form=@LF and  orders=@varKSiTable

EXEC dbo.X_GET_TABLE_NAME @tmp_table_main OUTPUT
EXEC dbo.X_GET_TABLE_NAME @tmp_table OUTPUT

select @LSF=link_saved_form,@begin_date=begin_date,@period_type=period_type,@period_number=period_number,@link_org=link_organization,@link_type_svod=link_type_svod from report_saved_forms where link_saved_form=@varKSiLSF

IF @varKSiAllAtr=1
begin
		insert #LSF (lsf)
		select max(RSF1.link_saved_form) as link_saved_form
		from report_saved_forms RSF1 (NOLOCK) left join report_forms RF (NOLOCK) on RSF1.link_form = RF.link_form
		  where RSF1.link_organization = @link_Org
			and isnull(RSF1.Link_Type_Svod, 0) = isnull(@link_type_svod, 0)
			and year(RSF1.begin_Date) = year(@Begin_date)
			and RSF1.period_type = @period_Type
			and RSF1.period_number = @period_number
			and RSF1.IsChangeAnalit = 0
			and RSF1.Link_Form = @LF
         AND rsf1.del = 0
			and RSF1.version = (select max(version) from report_saved_forms RSF2 (NOLOCK)
					where RSF2.link_organization = @link_Org
                  AND rsf2.del = 0
						and isnull(RSF2.Link_Type_Svod, 0) = isnull(@link_type_svod, 0)
						and year(RSF2.begin_Date) = year(@Begin_date) 
						and RSF2.period_type = @period_Type
						and RSF2.period_number = @period_number
						and RSF2.link_form = RSF1.link_form 
						and RSF2.IsChangeAnalit = 0
		 and isnull(RSF2.atr_code,'')=isnull(RSF1.atr_code,'')                       
		)
		group by RSF1.link_form, RF.code,isnull(RSF1.atr_code,'')
	end
	else
		insert #LSF (lsf)
		select @varKSiLSF


select @iCode_Col=orders from report_coloumns where link_col=(select top 1 link_code_col from report_tables where link_table=@LT)

select top 1 @LSF=lsf from #LSF 
delete #LSF where lsf=@lsf
set @atr=rtrim(dbo.RN_GET_ATR_VALUE(@lsf,@varKScCodeAtr))
SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@LT)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@varKSbDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table_main

	
execute (@cRuStr)		

SET @cRuStr='ALTER TABLE ' + @tmp_table_main + ' ADD atr varchar(250) '
print @cRuStr 		
execute (@cRuStr)
SET @cRuStr='UPDATE '+@tmp_table_main+' set atr = '''  + @atr + ''''
print @cRuStr 				
execute (@cRuStr)

while exists(select * from #LSF) 
	begin
		select top 1 @LSF=lsf from #LSF 
		delete #LSF where lsf=@lsf
		SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@LT)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@varKSbDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table
		execute (@cRuStr)					
		set @atr=dbo.RN_GET_ATR_VALUE(@lsf,@varKScCodeAtr)

		SET @cRuStr='ALTER TABLE ' + @tmp_table + ' ADD atr varchar(250) ' 
--print @cRuStr 		
		execute (@cRuStr)	
		SET @cRuStr='UPDATE '+@tmp_table+' set atr = '''  + @atr + ''''
--print @cRuStr 		
		execute (@cRuStr)	


		SET @cRuStr='insert '+@tmp_table_main+' select * from '+@tmp_table+' drop table ' +@tmp_table
--print @cRuStr 					
		execute (@cRuStr)					
	end		


IF @varKSbTempTable = 0
BEGIN 
   SET @cRuStr='select * from  '+@tmp_table_main+' order by atr, orders, code  drop table ' +@tmp_table_main
   execute (@cRuStr)
END    
ELSE BEGIN
   SET @varKScTempTable = @tmp_table_main
END
      
					


GO
GRANT EXECUTE ON dbo.[ro_get_all_atr_table] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KJ_GET_PERIOD_VACATION]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KJ_GET_PERIOD_VACATION]

GO
CREATE PROCEDURE [dbo].KJ_GET_PERIOD_VACATION
/*
	ОПРЕДЕЛЯЕТ ПЕРИОД, ЗА КОТОРЫЙ ПРЕДОСТАВЛЯЕТСЯ ОТПУСК РАБОТНИКУ
*/
	@parEMPL_LINK	int
AS
-- РАБОЧАЯ ДАТА
DECLARE @parDATE_WORK     DATETIME
SELECT  @parDATE_WORK = WORKDATE FROM USER_INFO
-- ДАТА ПРИЕМА НА РАБОТУ
DECLARE @DATE_BEGIN DATETIME
DECLARE @DATE_END DATETIME
SELECT  @DATE_BEGIN = DATE_BEGIN FROM ITEM_MOVE WHERE ACTIVE = 1 AND EMPL_LINK = @parEMPL_LINK and NEW_FACE = 1
--SET @parDATE_WORK = '20110420'

IF YEAR(@DATE_BEGIN) != YEAR(@parDATE_WORK)
	SET @parDATE_WORK = DATEADD(YEAR, -1, @parDATE_WORK)

SET     @DATE_END = DATEADD(YEAR,1,@DATE_BEGIN) -1
-- НАСТРОЙКА ПО АВТООПРЕДЛЕНИЮ ПЕРИОДА
DECLARE @AUTO INT
SELECT	@AUTO = VALUE FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'KADRY_OPT7')

IF @AUTO = 1 BEGIN
	-- ТАБЛИЦА ОТПУСКОВ, ВЛИЯЮЩИХ НА ПЕРИОД
	SELECT     V.LINK,
	     V.PERIOD_BEGIN, 
	     V.PERIOD_END,     
	     V.DATE_BEGIN,
	     CASE WHEN ISNULL(VB.DATE_BREAK,0) = 0
	          THEN V.DATE_END
	          ELSE DATEADD(DAY,ISNULL(LEN_KAL_DAYS,0),VB.DATE_BREAK)
	     END AS DATE_END,
	     CASE WHEN KVV.NO_SAL = 1
	          THEN 1
	          ELSE 0
	     END AS VAC_TYPE,
	     CASE WHEN ISNULL(VB.DATE_BREAK,0) = 0
	          THEN DATEDIFF(DAY,V.DATE_BEGIN,V.DATE_END) + 1
	          ELSE DATEDIFF(DAY,V.DATE_BEGIN,VB.DATE_BREAK) + ISNULL(LEN_KAL_DAYS,0) + 1
	     END AS DURATION
	INTO     #VACATION
	FROM     ITEM_VACATION V LEFT JOIN KD_VACATION_VID KVV
	     ON V.TYPE_LINK = KVV.LINK LEFT JOIN VACATION_BREAK VB
	     ON V.LINK = VB.VAC_LINK AND VB.ACTIVE = 1
	WHERE     V.ACTIVE = 1
	     AND (KVV.NO_SAL = 1 OR KVV.CHILDREN = 1)
	     AND V.EMPL_LINK = @parEMPL_LINK
	ORDER     BY V.DATE_BEGIN
	
	DECLARE @VAC_LINK INT
	DECLARE @VAC_TYPE INT
	DECLARE @PERIOD_BEGIN DATETIME
	DECLARE @DURATION INT
	DECLARE @VAC_DATE_END DATETIME
	
	DECLARE @DURATION_SUM INT
	DECLARE @PERIOD_SUM DATETIME
	SET     @DURATION_SUM = 0
	SET     @PERIOD_SUM = NULL
	WHILE EXISTS(SELECT * FROM #VACATION) BEGIN
	     SELECT     TOP 1 @VAC_LINK = LINK, @PERIOD_BEGIN = PERIOD_BEGIN,
	          @DURATION = DURATION,@VAC_DATE_END = DATE_END,@VAC_TYPE = VAC_TYPE
	     FROM     #VACATION
	     IF @VAC_TYPE = 1 BEGIN
	          SET @PERIOD_SUM = ISNULL(@PERIOD_SUM, @PERIOD_BEGIN)
	          --
	          IF @PERIOD_BEGIN = @PERIOD_SUM BEGIN
	               SET @DURATION_SUM = @DURATION_SUM + @DURATION
	          END ELSE BEGIN
	               IF @DURATION_SUM > 14 BEGIN
	                    SET @DATE_BEGIN = DATEADD(DAY, @DURATION_SUM - 14 + 1, @DATE_END)
	               END
	               SET @DURATION_SUM = @DURATION
	          END
	     END ELSE BEGIN
	          SET @DATE_BEGIN = DATEADD(DAY, 1, @VAC_DATE_END)
	     END
	     --
	     DELETE     FROM #VACATION WHERE LINK = @VAC_LINK
	END
	IF @VAC_TYPE = 1 AND @DURATION_SUM > 14 BEGIN
	     SET @DATE_BEGIN = DATEADD(DAY, @DURATION_SUM - 14 + 1, @DATE_END)
	END
	DROP TABLE #VACATION
END

DECLARE @DAY VARCHAR(2)
DECLARE @MONTH VARCHAR(2)
DECLARE @YEAR VARCHAR(4)
SET @YEAR = CONVERT(VARCHAR(4),YEAR(@parDATE_WORK))
SET @MONTH = SUBSTRING(CONVERT(VARCHAR(10),@DATE_BEGIN,104),4,2)
SET @DAY = SUBSTRING(CONVERT(VARCHAR(10),@DATE_BEGIN,104),1,2)
SET @DAY = CASE WHEN CONVERT(INT,@DAY) > DAY(dbo.DateEndOfMonth(@YEAR + @MONTH + '01')) 
					THEN CONVERT(VARCHAR(2),DAY(dbo.DateEndOfMonth(@YEAR + @MONTH + '01')))
				ELSE @DAY
		   END


SET @DATE_BEGIN = @YEAR + @MONTH + @DAY
SET @DATE_END = DATEADD(YEAR,1,@DATE_BEGIN) -1	
SELECT	@DATE_BEGIN AS DATE_BEGIN, @DATE_END AS DATE_END


GO


GRANT EXECUTE ON dbo.[KJ_GET_PERIOD_VACATION] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_N_CHILD_TABLE_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_N_CHILD_TABLE_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].SA_N_CHILD_TABLE_SAVE          
	@LINK_UP int,
	@ORDERS int,
	@LINK_VAC_CHILD int,
	@LINK_SFIN int,
	@DAYS int,
	@HOURS numeric(18, 2),
	@DAYS_NORM int,
	@HOURS_NORM numeric(18, 2),
	@SUMMA_NEW numeric(18, 2),
	@SUMMA_OLD numeric(18, 2),
	@SUMMA numeric(18, 2),
	@DATE_BEG datetime,
	@DATE_END datetime,
	@REGION numeric(10, 2),
	@REGSUM numeric(18, 2),
	@NORTH numeric(10, 2),
	@NORTHSUM numeric(18, 2)
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int,  @varKSSQLError int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF @LINK_UP IS NULL OR @LINK_UP =0 OR  @ORDERS IS NULL  OR  @LINK_VAC_CHILD IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

INSERT INTO DBO.SDOC_ACHILD_TABLE WITH (ROWLOCK) (LINK_UP,ORDERS,LINK_VAC_CHILD,LINK_SFIN,DAYS,HOURS,DAYS_NORM,HOURS_NORM,SUMMA_NEW,SUMMA_OLD,SUMMA,DATE_BEG,DATE_END,REGION,REGSUM,NORTH,NORTHSUM) 
							VALUES (@LINK_UP,@ORDERS,@LINK_VAC_CHILD,@LINK_SFIN,@DAYS,@HOURS,@DAYS_NORM,@HOURS_NORM,@SUMMA_NEW,@SUMMA_OLD,@SUMMA,@DATE_BEG,@DATE_END,@REGION,@REGSUM,@NORTH,@NORTHSUM)

SELECT @varKSSQLError = @@ERROR
IF @varKSSQLError <> 0
BEGIN
	ROLLBACK
	RETURN 7
END

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[SA_N_CHILD_TABLE_SAVE] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_ADV62]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_ADV62]

GO

CREATE    PROCEDURE dbo.SZV4_PRINT_ADV62(@Link int, @mode tinyint = 0) 
AS

DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
	@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9), @Month int, @Year int, @date datetime

SELECT 
	@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
	@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP,
	@Month = month_end, @year = year_begin
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV4_PACHKA P on D.link = P.link_dep
WHERE P.link = @link

Set @date = dbo.ConvertDMY2Date(1,@Month,@Year)
Set @date = dbo.DateEndOfMonth(@date)

--Округление каждой строчки таблицы
DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT2')
Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)

--Округление только итогов
DECLARE @IT_ROUND_TYPE tinyint
Set @IT_ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT5')

declare @TYPE_TARIF tinyint
SET @TYPE_TARIF = (
	SELECT TOP 1 FLAG_MS
	FROM dbo.DOCUMENTS_ESN_G
	WHERE 
		FLAG_JC = 1
		AND YEAR_BASE = @Year and month_base <= @Month
	ORDER BY MONTH_BASE DESC	
)
IF @mode = 0 OR @mode = 1
	Select 	
		[YEAR] = ISNULL(CASE WHEN year_begin <> 2010 THEN year_begin ELSE NULL END ,0),
		[PER] = ISNULL(CASE WHEN year_begin <> 2010 THEN PER ELSE NULL END ,0),
		[PER10] = ISNULL(CASE WHEN year_begin = 2010 THEN PER ELSE NULL END ,0),
		[COUNT_P] = COUNT(distinct CASE WHEN P.vid_kor = 1 THEN S.pachka ELSE NULL END),
		[COUNT_PK] = COUNT(distinct CASE WHEN P.vid_kor > 1 THEN S.pachka ELSE NULL END),
		@varKSNOM_PF AS REG_NOM_PF, 
		[DEP_NAME] = @varKSname,
		@varKSOKPO AS OKPO,
		@varKSINN AS INN,
		@varKSKPP AS KPP,
		DATE_CRT = @date,
		DATE_DOC = [date]
	from 
		dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
	where
		P.link = @Link
		and P.proverka = 1
	GROUP BY 
		P.year_begin, P.PER, P.[date]

IF @mode = 0 OR @mode = 2
	Select
		[NGROUP] = S.pachka,
		[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
		[CODE] = K.CODE,
		[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
		[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str+S.SUM_UPLATA_DOLGA_STR)),@ROUND_LEN,@ROUND_TYPE),
		[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
		[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop+S.SUM_UPLATA_DOLGA_NAK)),@ROUND_LEN,@ROUND_TYPE),
		[PERS_CNT] = COUNT(S.orders),
		FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(@varKSNOM_PF)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
		IT_ROUND = @IT_ROUND_TYPE
	from 
		dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
		INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
	where
		P.link = @Link
		and P.proverka = 1
		and P.vid_kor = 1
	group by
		s.pachka, year_begin, K.CODE
	UNION ALL SELECT NULL,'','',NULL,NULL,NULL,NULL,NULL,NULL, IT_ROUND = @IT_ROUND_TYPE
	WHERE NOT EXISTS(SELECT * FROM dbo.SA_SZV4_PACHKA P where P.link = @Link and P.proverka = 1 and P.vid_kor = 1)	
	order by S.pachka

IF @mode = 0 OR @mode = 3
	Select 	
		[NGROUP] = S.pachka,
		[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
		[CODE] = K.CODE,
		[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
		[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str+S.SUM_UPLATA_DOLGA_STR)),@ROUND_LEN,@ROUND_TYPE),
		[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
		[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop+S.SUM_UPLATA_DOLGA_NAK)),@ROUND_LEN,@ROUND_TYPE),
		[PERS_CNT] = COUNT(S.orders),
		FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(@varKSNOM_PF)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
		IT_ROUND = @IT_ROUND_TYPE
	from 
		dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
		INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
	where
		P.link = @Link
		and P.proverka = 1
		and P.vid_kor > 1
	group by
		s.pachka, year_begin, K.CODE
	UNION ALL SELECT NULL,'','',NULL,NULL,NULL,NULL,NULL,NULL, IT_ROUND = @IT_ROUND_TYPE			
	WHERE NOT EXISTS(SELECT * FROM dbo.SA_SZV4_PACHKA P where P.link = @Link and P.proverka = 1 and P.vid_kor > 1)	
	order by
		S.pachka


GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_ADV62] TO PUBLIC

GO


GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[rn_web_calc_skelet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[rn_web_calc_skelet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




/*
	Процедура формирования скелет для любой таблицы
	на вход: код формы и номер таблицы
	на выходе: курсор для данной таблицы с заданным количеством колонок
	Курсор берется на основании справочника, который подключен к ключевому столбцу
*/


CREATE     PROCEDURE dbo.rn_web_calc_skelet
  @LSF		int,
  @cTables varchar(1000) = ''
AS
IF @LSF is null
	RETURN 

declare @access int
exec dbo.WEB_OBJ_REPORT_ACCESS @access output,'','REPORT_FORMS_TABLES',@LSF
print @access
--IF @access<>255
	--return



declare @Link_Form int,@i int,@cword varchar(1000),@liTable int

select @Link_Form = Link_Form from dbo.report_saved_forms where Link_Saved_Form = @LSF
if @Link_Form is NULL
  return  -1

declare @str varchar(8000)
set @str=@cTables
create table #itables (link_table int)
create table #t_ColDict (orders tinyint,field varchar(100))

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)            
  END


declare @table table (orders int)
IF @cTables=''
BEGIN
        insert @table (orders)
        select orders from report_tables where Link_Form = @Link_Form and Val_Type = 1
END
ELSE
BEGIN
        insert @table (orders)
        select orders from report_tables RT where RT.Link_Form = @Link_Form and RT.Val_Type = 1
        and exists(select * from #iTables IT where IT.link_Table=RT.Link_table)
END



declare @LF int, @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
	@ExecStr varchar(8000), @Field varchar(50),  @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
	@CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @col_type tinyint, @orders_col tinyint,@orderTable INT, @DictWhere VARCHAR(1000)

while exists(select * from @table)
begin
	select 	top 1 @OrderTable=orders from @table

select @LC = Link_Code_Col, @LT = Link_Table from report_tables where orders = @OrderTable and Link_Form = @Link_form

if @LC is NULL
begin
	return -2
end

select @OrderCol = Orders, @Dict = RTRIM(Dictionary), @DictCol = RTRIM(Dictionary_Columns_List), @DictField =  RTRIM(Dictionary_Fields_List),
      @DictWhere = ISNULL([Dictionary_Where], '') 
from report_coloumns where Link_Col = @LC

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] = @LSF

if ISNULL(@Dict, '') = '' or ISNULL(@DictCol, '') = '' or ISNULL(@DictField, '') = ''
begin
	return 0 -- нет подключенных справочников
end

delete #t_ColDict 

set @Cols = ''
set @Field =''
set @Fields = ''
set @Col = ''

set @ExecStr = ''

while @DictField <> '' and @DictCol <> ''
begin
	exec dbo.RO_FORMULA_FUNCTIONS 1, @DictField output, @Field output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @DictCol output, @Col output, ','
	set @i = CONVERT(int, REPLACE(@COL, 'COL', ''))
	if @i = @OrderCol
	begin
		set @CodeCol = @Col -- ключевой столбец
		set @FieldCol = @Field -- поле из справочника, соответствующее ключевому столбцу
		--select @linkCol=link_col from report_coloumns where link_table=@LT and orders=@i
		continue 
	end
	insert #t_ColDict (orders,Field)
		values(@i,@Field)
end

--ключевой столбец
set @ExecStr = 'INSERT REPORT_DINAMICS (LINK_SF,CODE_ROW,LINK_COL)
SELECT DISTINCT '+LTRIM(STR(@LSF))+','+ @FieldCol+','+ltrim(str(@LC))+' from ' + @Dict+' A 
WHERE NOT EXISTS(SELECT * FROM i_report_dinamic_rows B WHERE A.'+@FieldCol+'=B.CODE_ROW and link_sf='+ltrim(str(@LSF))+' and B.LINK_TABLE='+ltrim(str(@LT))+')'
print @ExecStr
execute(@ExecStr)

while exists(select * from #t_colDict)
	begin
		select top 1 @i=orders,@Field=Field from #t_colDict
		select @linkCol=link_col from report_coloumns where link_table=@LT and orders=@i

		set @ExecStr = 'INSERT REPORT_DINAMICS (LINK_SF,CODE_ROW,LINK_COL,STR_VAL)
		SELECT DISTINCT '+LTRIM(STR(@LSF))+','+ @FieldCol+','+ltrim(str(@LinkCol))+','+@Field+' from ' + @Dict+' A 
		WHERE NOT EXISTS(SELECT * FROM report_dinamics B WHERE A.'+@FieldCol+'=B.CODE_ROW and B.link_sf='+ltrim(str(@LSF))+' and B.LINK_COL='+ltrim(str(@linkCol))+')'
      + CASE WHEN @DictWhere = '' THEN '' ELSE ' and ' + @DictWhere END 
		print @ExecStr
		execute(@ExecStr)
				
		delete #t_colDict where orders=@i
	end

	delete @table where  orders=@OrderTable 
end

return



GO
GRANT ALL ON dbo.[rn_web_calc_skelet] 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.[SD_N_TABEL_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_N_TABEL_FILL]

GO

CREATE PROCEDURE DBO.SD_N_TABEL_FILL
	@VARKSNLINK	 INT = 0, @MODE TINYINT =0, 	@VARKSDDATE DATETIME = NULL, @BUFFERCODE VARCHAR(15) = '', @DEP_LINK INT = NULL, @LINK_R INT = 0
/*ЕСЛИ @MODE = 0, ТО @VARKSNLINK - ССЫЛКА НА ТАБЕЛЬ, 
ЕСЛИ @MODE= 1, ТО @VARKSNLINK - ССЫЛКА НА СОТРУДНИКА И @VARKSDDATE - ПЕРИОД
ЕСЛИ @MODE= 2, ТО @VARKSDDATE - ПЕРИОД И ЛИНКИ СОТРУДНИКОВ ИЗ БУФФЕРА С КОДОМ @BUFFERCODE 
РЕЗУЛЬТАТ СРАЗУ СОХРАНИТЬ В РАСЧЕТЕ С ЛИНКОМ @LINK_R
*/
AS

/*
C КЕЙСИСТЕМС (KEYSYSTEMS), 2005
*/

SET NOCOUNT ON
DECLARE 	@VARKSDAT 	[DATETIME], 
	  	@VARKSDAT1 [DATETIME],
		@VARKSDAT2 [DATETIME]

---------------------------------------------------
IF @MODE = 0
	SET 	@VARKSDAT = CONVERT(DATETIME,ISNULL((SELECT TOP 1 TAB.PERIOD FROM DBO.TABELS TAB WHERE TAB.LINK_DOC = @VARKSNLINK),GETDATE()),104)
ELSE
	SET 	@VARKSDAT = @VARKSDDATE

SET 	@VARKSDAT = DBO.DATEENDOFMONTH(@VARKSDAT)

---------------------------------------------------
DECLARE @P INT
SET @P = (CASE @MODE WHEN 0 THEN -1 WHEN 1 THEN @VARKSNLINK WHEN 2 THEN -1 END)

---------------------------------------------------
CREATE TABLE #VARKSTMP
([LINK]					[INT],
 [ORDERS]				[INT] IDENTITY(1,1),
 [TAB_NUMER]			[VARCHAR] (6),
 [NAME_EMPL]			[VARCHAR] (30),
 [LINK_EMPL]			[INT],
 [LINK_SOVM]			[INT],
 [DATE1]				[DATETIME],		
 [DATE2]				[DATETIME],		
 [DAY]					[NUMERIC] (4,0),
 [HOUR]					[NUMERIC] (10,2),
 [DAY_NORM]				[NUMERIC] (4,0),
 [HOUR_NORM]			[NUMERIC] (10,2),
 [GRAPH_NAME]			[VARCHAR] (30),
 [GRAPH_LINK]			[INT],
 [SUMMA_BASE]			[NUMERIC] (18,2),
 [SUMMA] 				[NUMERIC] (18,2),
 [SUMMA_VIPL]			[NUMERIC] (18,2),
 [SUMMA_ALL]			[NUMERIC] (18,2),
 [PERCENT]				[NUMERIC] (18,4),
 [RATE]					[NUMERIC] (5,2),
 [REF_PAY]				[INT],
 [CODE_PAY]				[VARCHAR] (10),
 [NAME_PAY]				[VARCHAR] (60),
 [WAY_CALC]				[TINYINT],
 [DATE1_PAY]			[DATETIME],  
 [DATE2_PAY]			[DATETIME],
 LINK_KBK				INT,
 CODE_KBK				VARCHAR(20),
 SYST_PAY				INT,
 ORD					INT,
 [DAY_OLD]				[NUMERIC] (18,2),
 [HOUR_OLD]				[NUMERIC] (18,2),
 NO_TIME				BIT 		
)

---------------------------------------------------
IF NOT EXISTS ( --ЕСЛИ ТАБЕЛЯ НЕ СУЩЕСТВУЕТ, ТО ВЫДАТЬ ПУСТОЙ КУРСОР
	SELECT *
	FROM 
		DBO.SDOC DOC
		INNER JOIN DBO.TABELS T ON DOC.LINK = T.LINK_DOC
	WHERE 
		(
			DOC.LINK = @VARKSNLINK AND @MODE = 0) 
			OR 
			(@MODE IN (1,2) AND YEAR(T.PERIOD) = YEAR(@VARKSDDATE) AND MONTH(T.PERIOD) = MONTH(@VARKSDDATE)
		)
		AND DOC.OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_TABELS') 
)
BEGIN
	SELECT 
		[LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
		CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
		[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
		[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
		[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK
	FROM #VARKSTMP	

	RETURN 0	
END

--ДЛЯ КОГО СЧИТАТЬ
DECLARE @BUF_ID VARCHAR(20)
DECLARE @SQL VARCHAR(1000)

IF @MODE < 2 BEGIN
	EXEC DBO.GETRANDSTR 20, @BUF_ID OUT

	SET @SQL = '
	INSERT INTO DBO.BUFFER (ID, LINK)
	SELECT DISTINCT ''' + @BUF_ID + ''', T.LINK_EMPL
	FROM
		DBO.TABELS T WITH (NOLOCK) 
	WHERE
		T.LINK_DOC = ' + CONVERT(VARCHAR(20),@VARKSNLINK) + ' AND ' + CONVERT(VARCHAR(20),@MODE) + ' = 0'

	EXEC (@SQL)
	

	SET @SQL = '
	INSERT INTO DBO.BUFFER (ID, LINK)
	SELECT DISTINCT ''' + @BUF_ID + ''', ' + CONVERT(VARCHAR(20),@VARKSNLINK) + '
		WHERE ' + CONVERT(VARCHAR(20),@MODE) + ' = 1'

	EXEC (@SQL)

END
ELSE
BEGIN
	SET @BUF_ID = @BUFFERCODE
	SET @VARKSNLINK = -1 --По всем табелям за период
END

---------------------------------------------------
SET	@VARKSDAT1 	= DATEADD(DAY,1-DAY(@VARKSDAT),@VARKSDAT)
SET	@VARKSDAT2 	= DATEADD(DAY,-1,DATEADD(MONTH,1,@VARKSDAT1))

--------------------------------------------------

CREATE TABLE #DPEE (
	LINK_EMPL INT,
	LINK_SOVM INT,
	LINK_PAYS INT,
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	DATE_BEGIN DATETIME,
	DATE_END DATETIME,
	WAY_CALC TINYINT,
	SUMMA_BASE NUMERIC(18,2),
	PERC NUMERIC(18,4),
	SUMMA NUMERIC(18,2),
	LINK_KBK INT,
	CODE_KBK VARCHAR(20),
	[DAYS] NUMERIC(5,2), 
	[HOURS] NUMERIC(18,2),
	NO_TIME BIT 
)

INSERT INTO #DPEE (LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME)
SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME
FROM DBO.SA_ALL_PAYS_ALL(@P,@VARKSDAT2,@BUF_ID, @DEP_LINK, @VARKSNLINK)

CREATE TABLE #SA_EMPLS_W (LINK_EMPL INT, LINK_SOVM INT, GRAPH_LINK INT, NUM_STAKE NUMERIC(5,2), SYST_PAY TINYINT, DATE_BEGIN DATETIME, DATE_END DATETIME, LINK_SFIN INT, SALPERC NUMERIC(18,2), link_type INT)
INSERT INTO #SA_EMPLS_W (LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type)
SELECT LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type FROM DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID)

---
SET @SQL = 'DELETE FROM DBO.BUFFER WHERE ID = ''' + @BUF_ID + ''''
EXEC (@SQL)

-------------  ИНФОРМАЦИЯ НА БАЗЕ ОСНОВНОГО ТАБЕЛЯ ---------------
INSERT INTO #VARKSTMP ([LINK], [TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK, SYST_PAY,[DAY_OLD],[HOUR_OLD], NO_TIME)
SELECT 
	[LINK]			= DOC.LINK,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30),
	[LINK_EMPL] 	= E.LINK_EMPL,
	[LINK_SOVM] 	= E.LINK_SOVM,
	[DATE1]			= DPE.DATE_BEGIN,
	[DATE2]			= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	[DAY]			= DPE.DAYS,
	[HOUR]			= DPE.HOURS,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),G1.DAY_NORM),0),
	[HOUR_NORM] 	= ISNULL(CONVERT(NUMERIC(10,2),G1.HOUR_NORM),0),
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[SUMMA_BASE]	= CONVERT(NUMERIC(18,2),ISNULL( DPE.SUMMA_BASE ,0)),
	[SUMMA]		  	= 0.00,
	[SUMMA_VIPL]	= (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.SUMMA,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.SUMMA,0)) END),
	[SUMMA_ALL]		= CONVERT(NUMERIC(18,2),ISNULL( DPE.SUMMA,0)),
	[PERCENT] 		= CONVERT(NUMERIC(18,4),ISNULL( DPE.PERC,0)),
	[RATE]			= ISNULL(E.NUM_STAKE,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.CODE_PAYS)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.NAME_PAYS)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,20),
	E.SYST_PAY,
	DAY_OLD = (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.DAYS,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.DAYS,0)) END), 
	HOUR_OLD = (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.HOURS,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.HOURS,0)) END),
	DPE.NO_TIME
FROM 
	DBO.SDOC DOC INNER JOIN DBO.TABELS T ON DOC.LINK = T.LINK_DOC
	INNER JOIN DBO.EMPL EM ON T.LINK_EMPL = EM.LINK
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	INNER JOIN #SA_EMPLS_W  E ON T.LINK_EMPL = E.LINK_EMPL --DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID) E ON T.LINK_EMPL = E.LINK_EMPL 
	INNER JOIN #DPEE DPE ON DPE.LINK_EMPL = E.LINK_EMPL AND DPE.LINK_SOVM = E.LINK_SOVM
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.GRAPHICS G1 ON G1.GRAPH_LINK = G.LINK AND MONTH(G1.PERIOD) = MONTH(@VARKSDDATE) AND YEAR(G1.PERIOD) = YEAR(@VARKSDDATE)
	LEFT JOIN ( 
		SELECT LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC 
			INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			ST.REF_DOC = @VARKSNLINK 
		GROUP BY LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLD 
		ON OLD.LINK_EMPL = E.LINK_EMPL AND OLD.LINK_SOVM = E.LINK_SOVM AND OLD.LINK_PAYS = DPE.LINK_PAYS AND OLD.LINK_VKR = DPE.LINK_KBK
	LEFT JOIN ( 
		SELECT SJC.LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			MONTH(DATE_BEGIN) = MONTH(@VARKSDAT) AND YEAR(DATE_BEGIN) = YEAR(@VARKSDAT) 
		GROUP BY SJC.LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLDA 
		ON OLDA.LINK_EMPL = E.LINK_EMPL  AND OLDA.LINK_SOVM = E.LINK_SOVM AND OLDA.LINK_PAYS = DPE.LINK_PAYS AND OLDA.LINK_VKR = DPE.LINK_KBK
WHERE 	
	((DOC.LINK = @VARKSNLINK AND @MODE = 0) OR (@MODE IN (1,2) AND YEAR(T.PERIOD) = YEAR(@VARKSDDATE) AND MONTH(T.PERIOD) = MONTH(@VARKSDDATE)))
ORDER BY 
	SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30)

--------------------------------------------------
DELETE FROM #VARKSTMP 
WHERE 
	(ISNULL([HOUR],0) = 0 AND NO_TIME <> 1)
	OR 
	SUMMA_ALL = 0

---------------------------------------------------
SELECT LINK_EMPL, LINK_SOVM, LINK_PAY = REF_PAY, LINK_KBK, SUMMA = SUM(SUMMA_ALL) INTO #TMP FROM #VARKSTMP GROUP BY LINK_EMPL, LINK_SOVM, REF_PAY, LINK_KBK

-------------------------------------------------
UPDATE #VARKSTMP  
SET 
	SUMMA_VIPL = SUMMA_VIPL * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK),
	[DAY] = [DAY]  - [DAY_OLD] * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK), 
	[HOUR] = [HOUR] - [HOUR_OLD] * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK)
FROM #VARKSTMP T1

---------------------------------------------------
UPDATE #VARKSTMP SET [SUMMA] = ISNULL([SUMMA_ALL],0)-ISNULL([SUMMA_VIPL],0)
FROM #VARKSTMP T1

------------------------------------------------
IF ISNULL(@LINK_R,0) <> 0 BEGIN
	DECLARE @PREVORD INT
	SET @PREVORD = ISNULL((SELECT MAX(ORDERS) FROM DBO.SDOC_TABEL_TABLE WHERE LINK_UP  = @LINK_R),0)

	INSERT INTO DBO.SDOC_TABEL_TABLE (
		LINK_UP,ORDERS,LINK_EMPL,LINK_SOVM,LINK_PAY,SUMMA_ALL,SUMMA_VIPL,SUMMA,SUMMA_BASE,DATE1,DATE2,DAYS,HOURS,DAY_NORM,HOUR_NORM,PERC,RATE,LINK_KBK
	)
	SELECT @LINK_R, ORDERS + @PREVORD, [LINK_EMPL],LINK_SOVM,[REF_PAY],ISNULL([SUMMA_ALL],0),ISNULL([SUMMA_VIPL],0),ISNULL([SUMMA],0),ISNULL([SUMMA_BASE],0),[DATE1],[DATE2],
			ISNULL(CONVERT(INT,[DAY]),0) AS [DAY],ISNULL([HOUR],0),ISNULL(CONVERT(INT,[DAY_NORM]),0) AS [DAY_NORM],ISNULL([HOUR_NORM],0),ISNULL([PERCENT],0),ISNULL([RATE],0), LINK_KBK
	FROM #VARKSTMP
	ORDER BY [NAME_EMPL], LINK_SOVM, CONVERT(INT,[CODE_PAY]), [DATE1_PAY]

	UPDATE dbo.SDOC
	SET SUMMA_T = ISNULL((SELECT SUM(SUMMA) FROM #VARKSTMP),0)
	WHERE LINK = @LINK_R
	
	IF @MODE = 0 AND ISNULL(@VARKSNLINK,0) > 0 BEGIN
		UPDATE dbo.SDOC SET FLAG_JC = 1 WHERE LINK = @VARKSNLINK
		DELETE FROM dbo.SA_DOCFR WHERE LINK = @VARKSNLINK
	END	

END ELSE
	SELECT [LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
 			 CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
		   [HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
			 [SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
			 [DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK
	FROM #VARKSTMP
	ORDER BY [NAME_EMPL], LINK_SOVM, CONVERT(INT,[CODE_PAY]), [DATE1_PAY]

SET NOCOUNT OFF

RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_FILL] TO PUBLIC

GO

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RO_CALC_DETAIL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RO_CALC_DETAIL]

GO


/*******************************************************************************

	c Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE [dbo].[RO_CALC_DETAIL] 
	@varKSiLSF		INT,
	@varKSiLT		INT = NULL,
	@varKSiOrderCol	INT = 0, -- внутренний порядок
	@varKScCodeRow	varchar(50) = ''
AS

DECLARE @ldEnd		  DATETIME,
		@ldBegin      DATETIME,
		@liYear       INT,
		@ADM_CODE	  CHAR(3),
		@dCALC_DATE	  DATETIME,
		@iDEP_LINK	  INT,
		@LF		int, @LT int,
		@tmpStr		varchar(8000),
		@LC			int,
		@CodeForm	varchar(30),
		@orderCol	tinyint,
		@bid		varchar(100),
		@nabor_filter varchar(100),
		@iLinkCalcForm INT,
		@iForm737 tinyint

if exists(select * from dbo.REPORT_FORMS RF 
					inner join dbo.REPORT_SAVED_FORMS RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
					where left(RF.CODE,7) = '0503737')
	set @iForm737 = 1
else	
	set @iForm737 = 0

declare @temp_nastr table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL, [Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL, [Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint, orderCol tinyint)
declare @filter_kbk table (kbk varchar(20))
declare @t_Col table (Link_Col int, orderCol tinyint)

create table #t_PROV (signa varchar(10), orderCol varchar(10), KBK varchar(50), DT varchar(50), KT varchar(50),
	DATE_PROV varchar(10),  SUMMA varchar(100), COMMENT VARCHAR (254))
create table #t_Rest_Begin (signa varchar(10), orderCol varchar(10), KBK varchar(50), ACCOUNT varchar(50),
	DATE_REST varchar(10), SUMMA varchar(100))
create table #t_Rest_End (signa varchar(10), orderCol varchar(10), KBK varchar(50), ACCOUNT varchar(50),
	DATE_REST varchar(10), SUMMA varchar(100))

------------------------------------------------------------------------------------------
-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА

select @LF = RSF.Link_Form, 
		@iDEP_LINK 	= Link_Organization, 
		@ldEnd		= Begin_Date + 1,
		@dCALC_DATE = Begin_Date, 
		@liYear		= YEAR(Begin_Date),
		@ldBegin	= dbo.DateBeginOfYear(Begin_Date),
		@CodeForm	= RF.Code
from report_saved_forms RSF join report_forms RF on RSF.Link_Form = RF.Link_Form and RSF.link_saved_form = @varKSiLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@varKSiLSF,0)

-- select @iLinkCalcForm

/*
if @iLinkCalcForm is null 
	RETURN 0
*/

SET @varKScCodeRow = LTRIM (RTRIM (@varKScCodeRow))

if @varKSiLT is NULL or isnull(@varKSiOrderCol,0) = 0
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns RC join report_tables RT on RC.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF
else
begin
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns where link_table = @varKSiLT and (orders = @varKSiOrderCol or isnull(@varKSiOrderCol, 0) = 0)
end

SET @ADM_CODE = Null
IF @iDEP_LINK is not null
	SELECT @ADM_CODE = LEFT(LTRIM(dbo.rn_get_atr_value(@varKSiLSF, 'REPORTS_ATR_ADM')),3)

IF @ADM_CODE = '' OR @ADM_CODE = '000'
	SET @ADM_CODE = Null

select @nabor_filter = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_FILTER_KBK')

select @nabor_filter = REPLACE (@nabor_filter, 'Не отобрано', '')

insert @filter_kbk (kbk)
select code from dbo.rn_view_filter 
where link_self in (select link from dbo.rn_view_filter_nabor where '№' + LTRIM(RTRIM(STR(orders))) + ' - ' + Name = @nabor_filter)

if isnull(@nabor_filter, '') = ''
	insert @filter_kbk (kbk)
	values ('1')

--select * from @t_Col

---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК

insert @temp_nastr 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT.link , KT.link, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt,
	RC.orderCol
from dbo.REPORT_CALC C 
INNER JOIN @t_Col RC on RC.Link_Col = C.Link_Col
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

insert @temp_nastr_xor -- проводки, которые мы исключаем 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like CR.DT_Mask 
	left join dbo.s_accounts KT on KT.Code like CR.KT_Mask 
where [sign] = 3 and CR.[type] = 1 

insert @temp_nastr_rest 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], case when DT.link is NULL then KT.link else DT.link end, case when DT.link is NULL then kt_ekr else dt_ekr end, [type], type_kbk, mask_kbk, dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like case when CR.DT_Mask = '%' OR CR.DT_Mask = '' then 'x' else CR.DT_Mask + '%' end
	left join dbo.s_accounts KT on KT.Code like case when CR.KT_Mask = '%' OR CR.KT_Mask = '' then 'x' else CR.KT_Mask + '%'  end
where  CR.[type] in (2,3) and [sign] in (1,2) 

insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], case when DT.link is NULL then KT.link else DT.link end, case when DT.link is NULL then kt_ekr else dt_ekr end,  [type], type_kbk , dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like case when CR.DT_Mask = '%' OR CR.DT_Mask = '' then 'x' else CR.DT_Mask + '%' end
	left join dbo.s_accounts KT on KT.Code like case when CR.KT_Mask = '%' OR CR.KT_Mask = '' then 'x' else CR.KT_Mask + '%'  end
where  CR.[type] in (2,3) and [sign] = 3 


/*
if not exists(select top 1 * from @temp_nastr) and not exists(select top 1 * from @temp_nastr_rest)
	return
*/
----------------------------------------------------------------------
-- ПОЛУЧАЕМ ТО ИЗ ЧЕГО СЧИТАЕМ
---------------- проводки ----------------------------
insert #t_PROV (signa, orderCol, KBK, DT, KT, DATE_PROV,  SUMMA, COMMENT)
SELECT CASE [SIGN] WHEN 1 THEN '+' WHEN 2 THEN '-' ELSE '' END, 
		LTRIM(STR(TMP.orderCol)),
--		KBK.CODE,
	CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6)
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '') + '000', 3), TMP.Mask_KBK)
		END,
	SAD.CODE,
	SAK.CODE,

	CONVERT (VARCHAR (10), G.DATE_PROV, 104),
	G2.SUMMA,
	CONVERT (VARCHAR (254), RTRIM (dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT)))
		+ ISNULL (' № ' + LTRIM (RTRIM (G.NUMBER)), '')
		+ ISNULL (' от ' + CONVERT (VARCHAR (10), G.DATE, 104), '')  

FROM dbo.G_PROV G
INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK
	AND DT.DB_KR = 0)
LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK
	AND KT.DB_KR = 1)

LEFT JOIN dbo.S_ACCOUNTS SAD ON (SAD.LINK = DT.ACCOUNT)
LEFT JOIN dbo.S_ACCOUNTS SAK ON (SAK.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
LEFT JOIN dbo.KOSGU DTE ON (DTE.Link = DT.EKR)
LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
LEFT JOIN dbo.KOSGU KTE ON (KTE.Link = KT.EKR)

INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
		AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 0)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 0)

LEFT JOIN dbo.S_ACCOUNTS SA ON (TMP.DT_KT = 0 AND SA.LINK = DT.ACCOUNT
	OR TMP.DT_KT = 1 AND SA.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK
		OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
LEFT JOIN @filter_kbk F on F.kbk = KBK.Code 
WHERE G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
	AND G.DEP = @iDEP_LINK
	AND (F.kbk IS NOT NULL
		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link and 
				xor.link_dt = dt.account and xor.link_kt = kt.account
				and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
					or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
				and (RTRIM(isnull(KTS.Code,'
		')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем

-- SELECT * FROM #t_PROV
/*	SELECT [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(TMP.orderCol)),
			[KBK] = LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17) + LEFT(ISNULL(case dt_kt when 1 then DTS.CODE else KTS.CODE end, '') + '000', 3),
			[DT] = DSA.Code,
			[KT] = KSA.Code,
			[DATE] = convert(varchar(10), G.DATE_PROV, 104),
			[SUMMA] = dbo.rn_convert_number(case [sign] when 1 then G2.SUMMA when 2 then - G2.SUMMA else 0 end, 2, ' ')
	FROM 
		dbo.G_PROV G INNER JOIN dbo.G_PROV1 G1 
			ON (G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
			AND G.LINK = G1.LINK_UP) and G.DEP = @iDEP_LINK
		INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
		INNER JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
		INNER JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)
		LEFT JOIN dbo.KOSGU DTS ON DTS.Link = DT.EKR
		LEFT JOIN dbo.KOSGU KTS ON KTS.Link = KT.EKR
		iNNER JOIN @temp_nastr TMP ON (DT.ACCOUNT = link_dt or link_dt is NULL) and (KT.ACCOUNT = link_kt or link_kt is NULL) and (dbo.RO_LIKE_LIST(DTS.Code, dt_ekr) > 0 or dt_ekr = '') and (dbo.RO_LIKE_LIST(KTS.Code, kt_ekr) > 0 or kt_ekr = '')
		INNER JOIN dbo.KL_KBK KBK ON case dt_kt when 1 then DT.KBK else KT.KBK end = KBK.LINK and TMP.TYPE_KBK & (case KBK.[TYPE] when 3 then 4 when 4 then 8 else KBK.[TYPE] end) > 0  and (@ADM_CODE= left(ltrim(KBK.CODE),3) OR @ADM_CODE IS NULL)
		INNER JOIN @filter_kbk F on KBK.Code = F.kbk or isnull(@nabor_filter, '') = ''
		LEFT JOIN dbo.S_ACCOUNTS DSA ON DT.ACCOUNT = DSA.Link
		LEFT JOIN dbo.S_ACCOUNTS KSA ON KT.ACCOUNT = KSA.Link
	where not exists(select top 1 * from @temp_nastr_xor xor where xor.link_dt = dt.account and xor.link_kt = kt.account and  (CHARINDEX(RTRIM(DTS.Code),xor.dt_ekr) > 0 or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%')  and (RTRIM(isnull(KTS.Code,'')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем

*/

----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @orderCol = orderCol from @temp_nastr_rest order by orderCol

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@orderCol)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where @orderCol = orderCol

	-- остаток на начало периода
	insert #t_Rest_Begin (signa, orderCol, KBK, ACCOUNT, DATE_REST, SUMMA)
	select [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(@orderCol)), 	
			CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
					+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
					+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
					+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
					+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
			END,
	
			[ACCOUNT] = SA.Code,
			[DATE] = convert(varchar(10), INDATE, 104),
			[SUMMA] = dbo.rn_convert_number(sum(CASE when(SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),2,' ')
	from dbo.ARestTableByDateAccounts(@ldBegin, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.orderCol = @orderCol and R.[Type] = 2
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	LEFT JOIN @filter_kbk F on F.kbk = K.Code 
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and R1.link = R.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	group by SA.Code,
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3)
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		case [sign] when 1 then '+' when 2 then '-' else '' end,
		convert(varchar(10), INDATE, 104)
	
	-- остаток на конец периода
	insert #t_Rest_End (signa, orderCol, KBK, ACCOUNT, DATE_REST, SUMMA)
	select [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(@orderCol)), 	
			[KBK] = CASE
					WHEN R.Code_Row <> '' THEN R.Code_Row
					ELSE
					+ dbo.RA_Mask(CASE 
								WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
								ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
							END 
					+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
					+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
					+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
					+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
				END,
			[ACCOUNT] = SA.Code,
			[DATE] = convert(varchar(10), INDATE, 104),
			[SUMMA] = dbo.rn_convert_number(sum(CASE when(SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),2,' ')
	from dbo.ARestTableByDateAccounts(@ldEnd, @bid) A
		join @temp_nastr_rest R on R.link_account = account and R.orderCol = @orderCol and R.[Type] = 3
		left join dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end)>0)
		LEFT JOIN @filter_kbk F on F.kbk = K.Code 
		left join dbo.KOSGU S on (S.Link = A.EKR)  -- and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		left join dbo.KOSGU E on E.Link = A.EKR
		left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0 or R1.ekr ='') and R1.link = R.link)
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	group by SA.Code,
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		case [sign] when 1 then '+' when 2 then '-' else '' end,convert(varchar(10), INDATE, 104)

	delete @temp_nastr_rest where orderCol = @orderCol

	exec dbo.BufferClear @bid
end

UPDATE #t_Prov SET KBK = REPLACE (KBK, '#', '')
UPDATE #t_Rest_Begin SET KBK = REPLACE (KBK, '#', '')
UPDATE #t_Rest_End SET KBK = REPLACE (KBK, '#', '')

delete #t_Prov where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 
delete #t_Rest_Begin where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 
delete #t_Rest_End where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 

-- для протокола HTML
CREATE TABLE #protokol_HTML ([order] Integer, [type] Integer, [html] VarChar(8000))
set @tmpStr = 'Протокол расчета для формы: ' + @codeForm + ' Графа: ' + LTRIM(STR(@orderCol)) + ' Строка: ' + @varKScCodeRow
exec HTMLReport @nMode = 0, @cWorkTableName = '#protokol_HTML', @cRepHeader = @tmpStr

if exists(select top 1 * from #t_Prov)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Корреспонденция счетов</font>', @cDataTableName  = '#t_Prov',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK'' WRAP=''1''></field>
	 <field name=''DT''  WRAP=''1''></field>
	 <field name=''KT''  WRAP=''0''></field>
	<field name=''SUMMA''  WRAP=''0''></field>
	<field name=''COMMENT''  WRAP=''0''></field>
	 <field name=''DATE_PROV''  WRAP=''1''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Дебет|Кредит|Сумма|Документ|Дата пров.', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end

if exists(select top 1 * from #t_Rest_Begin)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Остатки на начало года</font>', @cDataTableName  = '#t_Rest_Begin',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK''  WRAP=''1''></field>
	 <field name=''ACCOUNT''  WRAP=''1''></field>
	<field name=''SUMMA''  WRAP=''0''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Счет|Сумма', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end

if exists(select top 1 * from #t_Rest_End)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Остатки на конец года</font>', @cDataTableName  = '#t_Rest_End',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK''  WRAP=''1''></field>
	 <field name=''ACCOUNT''  WRAP=''1''></field>
	<field name=''SUMMA''  WRAP=''0''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Счет|Сумма', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end
	
	select * from #protokol_HTML order by [order]

	drop table #t_Prov
	drop table #t_Rest_Begin
	drop table #t_Rest_End


GO


GRANT EXECUTE ON dbo.[RO_CALC_DETAIL] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_EMPL_OSV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_EMPL_OSV]

GO

CREATE  PROCEDURE [dbo].[SD_EMPL_OSV]
@varKSMonth INT, @varKSYear INT
/*
© Кейсистемс (Keysystems), 2005
Оборотно-сальдовая ведомость
*/
AS
DECLARE @varKSDATE1 DATETIME, 
		@varKSDATE2 DATETIME

SET @varKSDATE1 = dbo.ConvertDMY2Date(1,@varKSMonth,@varKSYear)
SET @varKSDATE2 = dateadd(m,1,@varKSDATE1)

SELECT LINK_EMPL,LINK_VKR,SUMMA,TYP_OPER 
INTO #T1 
FROM S_J_C_Short 
WHERE MONTH_BEGIN = @varKSMonth AND YEAR_BEGIN = @varKSYear AND NOT LINK_EMPL IS NULL 
		AND NOT LINK_VKR IS NULL

SELECT DISTINCT LINK_EMPL,LINK_VKR 
INTO #T2 
FROM (SELECT LINK_EMPL,LINK_VKR FROM #T1 
		UNION 
		SELECT LINK_EMPL,LINK_VKR FROM SAL_REMAIN WHERE YEAR_SAL = @varKSYear) T5

SELECT  T2.LINK_EMPL, 
		  [TAB_NUM] = EP.TAB,
		  [FIO] 		= EP.NAME_EMPL, 
		  [NAME_SUBDIV] = EP.SUBDIV_NAME,
		  [NAME_POST] 	 = EP.POST_NAME,
		  T2.LINK_VKR,
		  [NAME_VKR] = (SELECT CODE FROM dbo.SAL_SFIN WHERE LINK = T2.LINK_VKR)
INTO #T3
FROM #T2 T2 inner join  dbo.KU_EMPL_PLACING_FN(@varKSDATE2) EP on T2.LINK_EMPL = EP.LINK
	inner join dbo.ks_options_zb zb on EP.DEP_LINK = zb.ZB_LINK

SELECT 
	LINK_EMPL, 
	TAB_NUM, 
	[FIO]= COALESCE(FIO,''), 
	[NAME_VKR]= COALESCE(NAME_VKR,''), 
	[NAME_SUBDIV]= COALESCE(NAME_SUBDIV,''), 
	[NAME_POST] = COALESCE(NAME_POST,''),
	[S_BEGIN] = DBO.SALARY_EMPL_SALDO_MONTH_VKR(Link_Empl, @varKSDATE1,LINK_VKR, DEFAULT),
	[ADD] = isnull((select sum(summa) from #T1  T1 where  typ_oper = 1 and T1.LINK_EMPL =T3.Link_EMPL AND T1.LINK_VKR = T3.LINK_VKR),0),
	[DED] = isnull((select sum(summa) from #T1  T1 where  typ_oper = 2 and T1.LINK_EMPL =T3.Link_EMPL AND T1.LINK_VKR = T3.LINK_VKR),0),
	[S_END] = DBO.SALARY_EMPL_SALDO_MONTH_VKR(Link_Empl, @varKSDATE2,LINK_VKR, DEFAULT)
FROM #T3 T3
ORDER BY 2

DROP TABLE #T1
DROP TABLE #T2
DROP TABLE #T3

GO


GRANT EXECUTE ON dbo.[SD_EMPL_OSV] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_EXPORT_FORM_015_2012]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_EXPORT_FORM_015_2012]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2010

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_015_2012]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

SET NOCOUNT ON
SET DATEFORMAT dmy

--перенос формы из архивной базы
EXEC dbo.[RN_MOVE_FORM_FROM_ARH] @iLINK_SAVED_FORM

DECLARE @vcDataTable     VARCHAR(250),
        @dBEGIN_DATE     DATETIME,
        @iReturn			 INT,
		  @iLINK_FORM		 INT,
		  @iLINK_TABLE		 INT,
        @vcVersion		 VARCHAR(50),
        @sVersion        SMALLINT,
		  @vcExec			 VARCHAR(8000),
		  @vcSubjectCode   VARCHAR(2),		  
        @vcSubjectID     VARCHAR(50),

        @vcNAME                VARCHAR(8000),
        @vcFORM_CODE           VARCHAR(8000),
        @vcSEND_DATE           VARCHAR(8000),
        @vcPROGRAM_VERSION     VARCHAR(8000),
		  @vcSENDER_RUK          VARCHAR(8000),
        @vcSENDER_ISP          VARCHAR(8000),
        @vcSENDER_CONTACT_DATA VARCHAR(8000),
        @vcCOMMENT             VARCHAR(8000),
        @vcIS_DIRTY            VARCHAR(8000),
        @vcCRC                 VARCHAR(8000),
        @vcPeriod              VARCHAR(8000),
        @bCancel BIT,
        
        @iControl INT,
        @vcFILE_NAME_ARH VARCHAR(100)
 
CREATE TABLE #tabXML ([TXT]	  VARCHAR(8000),
							 [ORDERS] INT IDENTITY(1,1))

IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL
BEGIN
   SELECT @vcVersion = [VERSION]
   FROM #tabExportOutput 
END

IF @iMODE = 1
BEGIN
	EXEC @iReturn = dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
																 @vcFILE_NAME OUTPUT,
																 @iMODE
	RETURN @iReturn
END

EXEC dbo.[RA_EXPORT_FORM_015_ANALYZE] @iLINK_SAVED_FORM, 
                                      @bCancel OUTPUT

IF @bCancel = 1
BEGIN
   RETURN 0
END

SELECT @iLINK_FORM = [LINK_FORM]       
FROM dbo.[REPORT_SAVED_FORMS]
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM 

UPDATE dbo.[REPORT_DINAMICS]
SET [STR_VAL] = REPLACE(REPLACE(REPLACE([STR_VAL],CHAR(9),' '),CHAR(13),' '),CHAR(10),'')
WHERE [LINK_SF] = @iLINK_SAVED_FORM

UPDATE dbo.[REPORT_DINAMICS]
SET [STR_VAL] = ''
WHERE [LINK_SF] = @iLINK_SAVED_FORM AND
      LEN([STR_VAL])=0

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 2

SET @vcExec = '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] VARCHAR(8000),[COL1] VARCHAR(8000),[COL2] VARCHAR(8000),[FCOL2] VARCHAR(8000),
[COL3] VARCHAR(8000),[ITOG] INT) ' +
	    		  'INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T' + RTRIM(LTRIM(@iLINK_TABLE)) + '] ' + STR(@iLINK_SAVED_FORM) + 
		   	  ' INSERT #tabAttr([CODE],[VAL]) SELECT [CODE],[COL2] FROM #tabRI_PROC_T WHERE ISNULL([FCOL2],'''')<>''ЗАПРЕТ()'' DROP TABLE #tabRI_PROC_T' 

CREATE TABLE #tabAttr ([CODE] VARCHAR(100),
							  [VAL]	VARCHAR(8000))

EXEC(@vcExec)

--select * from #tabAttr 
SELECT @vcSENDER_RUK = RTRIM(LEFT([VAL],200))
FROM #tabAttr
WHERE [CODE]='SENDER_RUK'

SELECT @vcSENDER_ISP = RTRIM(LEFT([VAL],200))
FROM #tabAttr
WHERE [CODE]='SENDER_ISP'

SELECT @vcSENDER_CONTACT_DATA = RTRIM(LEFT([VAL],300))
FROM #tabAttr
WHERE [CODE]='SENDER_CONTACT_DATA'

SELECT @vcCOMMENT = RTRIM(LEFT([VAL],1000))
FROM #tabAttr
WHERE [CODE]='COMMENT'

SELECT @vcIS_DIRTY = CASE 
                        WHEN LEN([VAL])>0 THEN 'TRUE'
                        ELSE 'FALSE'
                     END
FROM #tabAttr
WHERE [CODE]='IS_DIRTY'

EXEC dbo.[RA_GET_VERSION] @vcPROGRAM_VERSION OUTPUT

SELECT @bCancel = 0,       
		 @vcSubjectCode = ISNULL(RIGHT(RTRIM(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT')),2),''),       
       @vcNAME = 'Сведения об отдельных показателях исполнения консолидированного бюджета субъекта Российской Федерации',
       @vcFORM_CODE = '426',
       @vcSEND_DATE = CONVERT(VARCHAR(50),GETDATE(),104) + ' ' + CONVERT(VARCHAR(50),GETDATE(),108),
		 @vcSENDER_RUK = ISNULL(@vcSENDER_RUK,''),
		 @vcSENDER_ISP = ISNULL(@vcSENDER_ISP,''),
		 @vcSENDER_CONTACT_DATA = ISNULL(@vcSENDER_CONTACT_DATA,''),
		 @vcCOMMENT = ISNULL(@vcCOMMENT,''),
		 @vcIS_DIRTY = ISNULL(@vcIS_DIRTY,'FALSE'),
       @vcPROGRAM_VERSION = ISNULL(@vcPROGRAM_VERSION,'')

SELECT @sVersion = [VERSION] + 1,
       @dBEGIN_DATE = [BEGIN_DATE],
       @vcPeriod = CAST(YEAR(@dBEGIN_DATE) AS VARCHAR(4)) + '00' + RTRIM(CAST(MONTH(@dBEGIN_DATE) AS VARCHAR(2)))
FROM dbo.[REPORT_SAVED_FORMS]
WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM

IF @vcVersion IS NOT NULL
BEGIN
   IF dbo.[RA_ISNUMERIC](REPLACE(@vcVersion,'.','')) = 1
   BEGIN
      SET @sVersion = CAST(@vcVersion AS INT)
   END
END

SET @vcVersion = RIGHT(CAST(@sVersion AS VARCHAR(50)),1)
SELECT @vcExec =  '092' +  '_' + 
                  @vcSubjectCode + '_' + 
                  LEFT(CONVERT(VARCHAR(50),@dBEGIN_DATE,112),6) + '_' +
                  @vcFORM_CODE + '_' +
                  @vcVersion,
       @vcFILE_NAME =  @vcExec + '.xml',
       @vcFILE_NAME_ARH = @vcExec + '.zip'

CREATE TABLE #tabEL ([STR_VAL]     VARCHAR(8000),
                     [FCOL4]       VARCHAR(8000),
                     [IS_EDITABLE] VARCHAR(8000))

SELECT @iLINK_TABLE = [LINK_TABLE]
FROM dbo.[REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM AND
		[ORDERS] = 1

SET @vcDataTable = '##tab' + REPLACE(CAST(NEWID() AS VARCHAR(100)),'-','')
SET @vcExec = 'EXEC dbo.[RI_PROC_T' + CAST(@iLINK_TABLE AS VARCHAR(50)) + 
              '] @tmp_table=''' + @vcDataTable + ''', @varKSLSF=' + CAST(@iLINK_SAVED_FORM AS VARCHAR(50))+CHAR(13)+CHAR(10)+
              'INSERT #tabEL ([STR_VAL],[FCOL4],[IS_EDITABLE])' + CHAR(13)+CHAR(10)+
              'SELECT [STR_VAL] = CASE ' + CHAR(13) + CHAR(10) +
              '                      WHEN [FCOL3] = ''ЗАПРЕТ()'' THEN '''''+CHAR(13)+CHAR(10)+
              '                      ELSE dbo.rn_convert_number(Col3,/*case when code = ''5500'' or code = ''5600'' then 0 else 1 end*/0, '''')'+CHAR(13)+CHAR(10)+
              '                   END,'+CHAR(13)+CHAR(10)+
              '       [FCOL4],'+CHAR(13)+CHAR(10)+
              '       [IS_EDITABLE] = CASE ' +CHAR(13)+CHAR(10)+
              '                          WHEN [FCOL3] = ''ЗАПРЕТ()'' THEN ''IS_EDITABLE="FALSE"'''+CHAR(13)+CHAR(10)+
              '                          ELSE '''''+CHAR(13)+CHAR(10)+
              '                       END'+CHAR(13)+CHAR(10) +              
              'FROM ' + @vcDataTable + CHAR(13)+CHAR(10) +
              'DROP TABLE ' + @vcDataTable

print @vcExec
EXEC(@vcExec)

--
SET @vcCRC = ''
SELECT  @vcCRC = @vcCRC + RTRIM(LTRIM([STR_VAL]))
FROM #tabEL
ORDER BY [FCOL4]

SET @vcCRC = RTRIM(LTRIM(@vcFORM_CODE)) + 
             RTRIM(LTRIM(@vcSubjectCode)) + 
             RTRIM(LTRIM(@vcPeriod)) + 
             RTRIM(LTRIM(@vcSENDER_ISP)) + 
             RTRIM(LTRIM(@vcSENDER_RUK)) + 
             RTRIM(LTRIM(CAST(CAST(dbo.[RA_GET_CRC_32](@vcCRC) AS BIGINT) AS VARCHAR(50))))

--select @vcCRC 

SET @vcCRC = CAST(CAST(dbo.[RA_GET_CRC_32](@vcCRC) AS BIGINT) AS VARCHAR(50))

INSERT #tabXML([TXT]) VALUES ('<XML ENCODING="windows-1251">')
INSERT #tabXML([TXT]) VALUES ('   <HEADER NAME="' + @vcNAME + '" ' +
                                         'SEND_DATE="' + @vcSEND_DATE + '" ' + 
                                         'FORM_CODE="' + @vcFORM_CODE  + '" ' + 
                                         'SENDER_RUK="' + @vcSENDER_RUK + '" ' + 
                                         'SENDER_ISP="' + @vcSENDER_ISP + '" ' + 
                                         'SENDER_CONTACT_DATA="' + @vcSENDER_CONTACT_DATA + '" ' +
                                         'GUID="' + RTRIM(CONVERT(VARCHAR(100), NEWID())) + '" ' + 
                                         'PROGRAM_NAME="Свод-КС" ' + 
                                         'PROGRAM_VERSION="' + @vcPROGRAM_VERSION + '" ' + 
                                         'COMMENT="' + dbo.[RA_XML_MASK](@vcCOMMENT) + '" ' + 
                                         'REVISION="' + @vcVersion + '" ' + 
                                         'IS_DIRTY="' + @vcIS_DIRTY + '" ' + 
                                         'CRC="' + @vcCRC + '" '+
                                         'FILE_NAME_MASK="''092_''#1$CODE''_''#0$CODE''_''@FORM_CODE''_''@REVISION"></HEADER>')
INSERT #tabXML([TXT]) VALUES ('   <BODY>')
INSERT #tabXML([TXT]) VALUES ('      <FIXED_ATTRS>')
INSERT #tabXML([TXT]) VALUES ('         <ATTR DATATYPE="STRING" ID="0" IS_EDITABLE="TRUE" NAME="Отчетная дата" RULE_ID="0" SHOW_CODE="FALSE">' + @vcPeriod + '</ATTR>')

SELECT @vcSubjectID = [ID]
FROM dbo.[RA_VIEW_015_SUBJECT_ID]
WHERE [CODE] = @vcSubjectCode

IF @vcSubjectID IS NULL
BEGIN
   SET @vcSubjectID = ''
END

INSERT #tabXML([TXT]) VALUES ('      <ATTR DATATYPE="STRING" ID="1" IS_EDITABLE="TRUE" NAME="Субъект РФ" RULE_ID="1" SHOW_CODE="TRUE">' + @vcSubjectID + '</ATTR>')
INSERT #tabXML([TXT]) VALUES ('      </FIXED_ATTRS>')
INSERT #tabXML([TXT]) VALUES ('      <COLS>')
INSERT #tabXML([TXT]) VALUES ('         <COL ID="20" ORDER="0" DATATYPE="NUMERIC(20,2)">тыс. руб.</COL>')
INSERT #tabXML([TXT]) VALUES ('      </COLS>')
INSERT #tabXML([TXT]) VALUES ('      <ROWS HAS_CODE="TRUE">')
INSERT #tabXML([TXT]) VALUES ('         <ROW ID="8725371" ORDER="0" CODE="">Доходы бюджета')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725381" ORDER="1" CODE="1000">ИТОГО ДОХОДОВ</ROW>')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725391" ORDER="2" CODE="1100">Налоговые и неналоговые доходы')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725401" ORDER="3" CODE="1110">Налог на прибыль организаций</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725421" ORDER="4" CODE="1120">Налог на доходы физических лиц</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725431" ORDER="5" CODE="1130">Акцизы</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725441" ORDER="6" CODE="1140">Налог на имущество организаций</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725451" ORDER="7" CODE="1150">Налог на добычу полезных ископаемых</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725461" ORDER="8" CODE="1160">Земельный налог</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725471" ORDER="9" CODE="1170">Транспортный налог</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787221" ORDER="10" CODE="1180">Прочие налоговые доходы</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787231" ORDER="11" CODE="1190">Неналоговые доходы')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')
INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725481" ORDER="13" CODE="1200">Безвозмездные поступления')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725491" ORDER="14" CODE="1210">Безвозмездные поступления от других бюджетов бюджетной системы')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725501" ORDER="15" CODE="1211">Дотации на выравнивание бюджетной обеспеченности</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725511" ORDER="16" CODE="1212">Дотации на поддержку мер по обеспечению сбалансированности бюджетов субъектов Российской Федерации</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725521" ORDER="17" CODE="1213">Субсидии из федерального бюджета</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725531" ORDER="18" CODE="1214">Субвенции из федерального бюджета</ROW>')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')

INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8872351" ORDER="18" CODE="1228">Доходы бюджетов бюджетной системы Российской Федерации от возврата остатков субсидий, субвенций и иных межбюджетных трансфертов, имеющих целевое назначение, прошлых лет</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8872361" ORDER="18" CODE="1229">Возврат остатков субсидий, субвенций и иных межбюджетных трансфертов, имеющих целевое назначение, прошлых лет</ROW>')

INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('         </ROW>')
INSERT #tabXML([TXT]) VALUES ('         <ROW ID="8725541" ORDER="19" CODE="">Расходы бюджета')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725551" ORDER="20" CODE="2000">ИТОГО РАСХОДОВ')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725561" ORDER="21" CODE="2100">Оплата труда с начислениями</ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725571" ORDER="22" CODE="2200">Капитальные вложения, из них')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725581" ORDER="23" CODE="2210">Капитальные вложения, осуществленные за счет безвозмездных поступлений из федерального бюджета</ROW>')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725591" ORDER="24" CODE="2300">Иные расходы, из них')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8787241" ORDER="25" CODE="2310">Оплата коммунальных услуг</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8787251" ORDER="26" CODE="2320">Социальное обеспечение</ROW>')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')
INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725601" ORDER="27" CODE="3000">Профицит (+) / Дефицит (-)</ROW>')
INSERT #tabXML([TXT]) VALUES ('         </ROW>')
INSERT #tabXML([TXT]) VALUES ('         <ROW ID="8725611" ORDER="28" CODE="">Источники финансирования дефицита бюджета')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725621" ORDER="29" CODE="4000">ИТОГО ИСТОЧНИКОВ ФИНАНСИРОВАНИЯ ДЕФИЦИТА')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725631" ORDER="30" CODE="4100">Кредиты кредитных организаций')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725641" ORDER="31" CODE="4110">Получение кредитов от кредитных организаций</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725651" ORDER="32" CODE="4120">Погашение кредитов, полученных от кредитных организаций</ROW>')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725661" ORDER="33" CODE="4200">Бюджетные кредиты от других бюджетов бюджетной системы Российской Федерации')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725671" ORDER="34" CODE="4210">Получение бюджетных кредитов от других бюджетов бюджетной системы Российской Федерации</ROW>')
INSERT #tabXML([TXT]) VALUES ('                  <ROW ID="8725681" ORDER="35" CODE="4220">Погашение кредитов, полученных от других бюджетов бюджетной системы Российской Федерации</ROW>')
INSERT #tabXML([TXT]) VALUES ('               </ROW>')
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787261" ORDER="36" CODE="4300">Изменение остатков средств на счетах по учету средств бюджета</ROW>') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787271" ORDER="37" CODE="4400">Иные источники финансирования дефицитов бюджетов</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('         </ROW>')
INSERT #tabXML([TXT]) VALUES ('         <ROW ID="8725691" ORDER="38" CODE="">Справочно')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8725711" ORDER="39" CODE="5100">Остатки средств бюджетов, из них') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8725701" ORDER="40" CODE="5110">Остатки целевых средств бюджетов</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8787281" ORDER="41" CODE="5200">Государственный долг субъекта Российской Федерации</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8787291" ORDER="42" CODE="5300">Муниципальный долг</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="8787301" ORDER="43" CODE="5400">Просроченная задолженность, в том числе') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787311" ORDER="44" CODE="5410">По заработной плате</ROW>') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787321" ORDER="45" CODE="5420">По начислениям на выплаты по оплате труда</ROW>') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787331" ORDER="46" CODE="5430">По оплате коммунальных услуг</ROW>') 
INSERT #tabXML([TXT]) VALUES ('               <ROW ID="8787341" ORDER="47" CODE="5440">По мерам социальной поддержки граждан</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            </ROW>')
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="9848501" ORDER="48" CODE="5500">Расходы на оплату труда с начислениями (аналитические данные с учетом расходов бюджетных и автономных учреждений)</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="9848511" ORDER="49" CODE="5600">Расходы на капитальные вложения (аналитические данные с учетом расходов бюджетных и автономных учреждений)</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="9848521" ORDER="50" CODE="5700">Расходы на оплату коммунальных услуг (аналитические данные с учетом расходов бюджетных и автономных учреждений)</ROW>') 
INSERT #tabXML([TXT]) VALUES ('            <ROW ID="9848531" ORDER="51" CODE="5800">Расходы на социальное обеспечение (аналитические данные с учетом расходов бюджетных и автономных учреждений)</ROW>') 
INSERT #tabXML([TXT]) VALUES ('         </ROW>')
INSERT #tabXML([TXT]) VALUES ('      </ROWS>')
INSERT #tabXML([TXT]) VALUES ('      <CORNER></CORNER>')
INSERT #tabXML([TXT]) VALUES ('      <DATA>')

INSERT #tabXML([TXT]) 
SELECT '         <EL COL="20" ROW="' + [FCOL4] + '" ' + [IS_EDITABLE] + ' DATATYPE="NUMERIC(10)">' + [STR_VAL] + '</EL>'
FROM #tabEL
ORDER BY [FCOL4] 

--print @vcExec
EXEC(@vcExec)
INSERT #tabXML([TXT]) VALUES ('      </DATA>')

INSERT #tabXML([TXT]) VALUES ('      <RULES>')
INSERT #tabXML([TXT]) VALUES ('         <RULE ID="0" TYPE="REFERENTIAL" SPR_ID="0"></RULE>')
INSERT #tabXML([TXT]) VALUES ('         <RULE ID="1" TYPE="REFERENTIAL" SPR_ID="1"></RULE>')
INSERT #tabXML([TXT]) VALUES ('      </RULES>')
INSERT #tabXML([TXT]) VALUES ('      <SPRS>')
INSERT #tabXML([TXT]) VALUES ('         <SPR ID="0">Отчетная дата')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012001" ORDER="1" CODE="201201">на 1 февраля 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012002" ORDER="2" CODE="201202">на 1 марта 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012003" ORDER="3" CODE="201203">на 1 апреля 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012004" ORDER="4" CODE="201204">на 1 мая 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012005" ORDER="5" CODE="201205">на 1 июня 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012006" ORDER="6" CODE="201206">на 1 июля 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012007" ORDER="7" CODE="201207">на 1 августа 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012008" ORDER="8" CODE="201208">на 1 сентября 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="2012009" ORDER="9" CODE="201209">на 1 октября 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="20120010" ORDER="10" CODE="201210">на 1 ноября 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="20120011" ORDER="11" CODE="201211">на 1 декабря 2012 года</EL>')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="20120012" ORDER="12" CODE="201212">на 1 января 2013 года</EL>')
INSERT #tabXML([TXT]) VALUES ('         </SPR>')
INSERT #tabXML([TXT]) VALUES ('         <SPR ID="1">Субъект РФ')
INSERT #tabXML([TXT]) VALUES ('            <EL ID="14" ORDER="2" CODE="26">Белгородская область</EL><EL ID="15" ORDER="3" CODE="27">Брянская область</EL><EL ID="17" ORDER="4" CODE="28">Владимирская область</EL><EL ID="20" ORDER="5" CODE="31">Воронежская ' + 
'область</EL><EL ID="24" ORDER="6" CODE="33">Ивановская область</EL><EL ID="29" ORDER="7" CODE="37">Калужская область</EL><EL ID="34" ORDER="8" CODE="41">Костромская область</EL><EL ID="38" ORDER="9" CODE="44">Курская область</EL><EL ID="42" ORDER="10" COD' +
'E="46">Липецкая область</EL><EL ID="46" ORDER="11" CODE="48">Московская область</EL><EL ID="54" ORDER="12" CODE="54">Орловская область</EL><EL ID="61" ORDER="13" CODE="59">Рязанская область</EL><EL ID="66" ORDER="14" CODE="63">Смоленская область</EL><EL I' +
'D="68" ORDER="15" CODE="64">Тамбовская область</EL><EL ID="28" ORDER="16" CODE="36">Тверская область</EL><EL ID="70" ORDER="17" CODE="66">Тульская область</EL><EL ID="78" ORDER="18" CODE="71">Ярославская область</EL><EL ID="45" ORDER="19" CODE="73">г. Мос' +
'ква</EL><EL ID="86" ORDER="21" CODE="06">Республика Карелия</EL><EL ID="87" ORDER="22" CODE="07">Республика Коми</EL><EL ID="11" ORDER="23" CODE="24">Архангельская область</EL><EL ID="19" ORDER="24" CODE="30">Вологодская область</EL><EL ID="27" ORDER="25"' +
' CODE="35">Калининградская область</EL><EL ID="41" ORDER="26" CODE="45">Ленинградская область</EL><EL ID="47" ORDER="27" CODE="49">Мурманская область</EL><EL ID="49" ORDER="28" CODE="50">Новгородская область</EL><EL ID="58" ORDER="29" CODE="57">Псковская ' +
'область</EL><EL ID="40" ORDER="30" CODE="72">г. Санкт-Петербург</EL><EL ID="11100" ORDER="31" CODE="84">Ненецкий автономный округ</EL><EL ID="79" ORDER="33" CODE="76">Республика Адыгея</EL><EL ID="85" ORDER="34" CODE="05">Республика Калмыкия</EL><EL ID="3' +
'" ORDER="35" CODE="18">Краснодарский край</EL><EL ID="12" ORDER="36" CODE="25">Астраханская область</EL><EL ID="18" ORDER="37" CODE="29">Волгоградская область</EL><EL ID="60" ORDER="38" CODE="58">Ростовская область</EL><EL ID="82" ORDER="40" CODE="03">Рес' +
'публика Дагестан</EL><EL ID="26" ORDER="41" CODE="14">Республика Ингушетия</EL><EL ID="83" ORDER="42" CODE="04">Кабардино-Балкарская Республика</EL><EL ID="91" ORDER="43" CODE="79">Карачаево-Черкесская Республика</EL><EL ID="90" ORDER="44" CODE="10">Респу' +
'блика Северная Осетия-Алания</EL><EL ID="96" ORDER="45" CODE="94">Чеченская Республика</EL><EL ID="7" ORDER="46" CODE="21">Ставропольский край</EL><EL ID="80" ORDER="48" CODE="01">Республика Башкортостан</EL><EL ID="88" ORDER="49" CODE="08">Республика Мар' +
'ий Эл</EL><EL ID="89" ORDER="50" CODE="09">Республика Мордовия</EL><EL ID="92" ORDER="51" CODE="11">Республика Татарстан</EL><EL ID="94" ORDER="52" CODE="13">Удмуртская Республика</EL><EL ID="97" ORDER="53" CODE="15">Чувашская Республика</EL><EL ID="33" O' +
'RDER="54" CODE="40">Кировская область</EL><EL ID="22" ORDER="55" CODE="32">Нижегородская область</EL><EL ID="53" ORDER="56" CODE="53">Оренбургская область</EL><EL ID="56" ORDER="57" CODE="55">Пензенская область</EL><EL ID="5711" ORDER="58" CODE="56">Пермс' +
'кий край</EL><EL ID="36" ORDER="61" CODE="42">Самарская область</EL><EL ID="63" ORDER="62" CODE="60">Саратовская область</EL><EL ID="73" ORDER="63" CODE="68">Ульяновская область</EL><EL ID="37" ORDER="65" CODE="43">Курганская область</EL><EL ID="65" ORDER' +
'="66" CODE="62">Свердловская область</EL><EL ID="71" ORDER="67" CODE="67">Тюменская область</EL><EL ID="75" ORDER="68" CODE="69">Челябинская область</EL><EL ID="71100" ORDER="69" CODE="87">Ханты-Мансийский автономный округ</EL><EL ID="71140" ORDER="70" CO' +
'DE="90">Ямало-Ненецкий автономный округ</EL><EL ID="84" ORDER="72" CODE="77">Республика Алтай</EL><EL ID="81" ORDER="73" CODE="02">Республика Бурятия</EL><EL ID="93" ORDER="74" CODE="12">Республика Тыва</EL><EL ID="95" ORDER="75" CODE="80">Республика Хака' +
'сия</EL><EL ID="1" ORDER="76" CODE="17">Алтайский край</EL><EL ID="411" ORDER="77" CODE="19">Красноярский край</EL><EL ID="2511" ORDER="81" CODE="34">Иркутская область</EL><EL ID="32" ORDER="84" CODE="39">Кемеровская область</EL><EL ID="50" ORDER="85" COD' +
'E="51">Новосибирская область</EL><EL ID="52" ORDER="86" CODE="52">Омская область</EL><EL ID="69" ORDER="87" CODE="65">Томская область</EL><EL ID="7611" ORDER="88" CODE="91">Забайкальский край</EL><EL ID="98" ORDER="92" CODE="16">Республика Саха (Якутия)</' +
'EL><EL ID="5" ORDER="93" CODE="20">Приморский край</EL><EL ID="8" ORDER="94" CODE="22">Хабаровский край</EL><EL ID="10" ORDER="95" CODE="23">Амурская область</EL><EL ID="3011" ORDER="96" CODE="38">Камчатский край</EL><EL ID="44" ORDER="99" CODE="47">Магад' +
'анская область</EL><EL ID="64" ORDER="100" CODE="61">Сахалинская область</EL><EL ID="99" ORDER="101" CODE="78">Еврейская автономная область</EL><EL ID="77" ORDER="102" CODE="88">Чукотский автономный округ</EL>')
INSERT #tabXML([TXT]) VALUES ('         </SPR>')
INSERT #tabXML([TXT]) VALUES ('         </SPRS>')
INSERT #tabXML([TXT]) VALUES ('   </BODY>')
INSERT #tabXML([TXT]) VALUES ('</XML>')

INSERT #FileExportReport([TXT],
                         [NameFile],
                         [ORDERS],
                         [NameFileArh])
SELECT [TXT],
	    @vcFILE_NAME,
	    [ORDERS],
       @vcFILE_NAME_ARH
FROM #tabXML
ORDER BY [ORDERS]

DROP TABLE #tabXML
DROP TABLE #tabEL



GO
GRANT ALL ON dbo.[RA_EXPORT_FORM_015_2012] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	  
create table #Reps (LSF int)
insert #Reps (LSF) values(     17508)
exec dbo.RO_EXPORT_REPORT '#Reps',2

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] VARCHAR(100),[COL1] VARCHAR(100),[COL2] VARCHAR(100),[COL3] VARCHAR(8000),[FCOL3] VARCHAR(50),[ITOG] INT) 


INSERT #tabRI_PROC_T EXEC dbo.[RI_PROC_T5087]      17508 INSERT #tabAttr([CODE],[VAL]) SELECT [COL1],[COL3] FROM #tabRI_PROC_T WHERE ISNULL([FCOL3],'')<>'ЗАПРЕТ()' DROP TABLE #tabRI_PROC_T

select(len("&quot;О приведении в соответствие с федеральным и областным законодательством учредительных документов государственного учреждения &quot;Региональная продовольственная корпорация при главном управлении сельского хозяйства и перерабатывающей промышленности Смол"))

select * from 

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_371]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_371]
END
GO



/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_371]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @vcOKATO VARCHAR(100), @vcPPP VARCHAR(100) 

DECLARE @tabFileExport TABLE ([TXT]	        VARCHAR(800), 
							         [NAMEFILE]    VARCHAR(100), 
                              [NAMEFILEARH] VARCHAR(100),
							         [ORDERS]      INT IDENTITY(1,1))  


EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          

IF @iMODE = 2
BEGIN
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders <= (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=01')
   ORDER BY ORDERS

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders > (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=02')
         AND orders < (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = '#&')
   ORDER BY ORDERS

   UPDATE @tabFileExport
   SET TXT = REPLACE(TXT, '999|9999|9999999|999|9|99999|999|999|', '***|****|*******|***|*|*****|***|***|')
   WHERE TXT LIKE '999|9999|9999999|999|9|99999|999|999|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#@<LN>ТБ=02', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport   
   
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT NOT LIKE '888|8888|8888|88|8888|8|88888|888|888|%'
         AND orders > (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=01')
         AND orders < (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=02')
   ORDER BY ORDERS

   UPDATE @tabFileExport
   SET TXT = REPLACE(TXT, '777|7777|7777|77|7777|7|77777|777|777|', '***|****|****|**|****|*|*****|***|***|')
   WHERE TXT LIKE '777|7777|7777|77|7777|7|77777|777|777|%'      
   
   
   
   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 'ТБ=03<LN>#$', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT REPLACE(TXT, '888|8888|8888|88|8888|8|88888|888|888|', '***|**************|*|*****|***|***|'), [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE TXT LIKE '888|8888|8888|88|8888|8|88888|888|888|%'

   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT TOP 1 '#', [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport


   INSERT @tabFileExport ([TXT], [NAMEFILE], [NAMEFILEARH])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH]
   FROM #FileExportReport
   WHERE orders >= (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = '#&')
   ORDER BY ORDERS
   
   UPDATE @tabFileExport
   SET TXT = LEFT(REPLACE(TXT, '000|0000|0000000|000|', '***|****|*******|***|'),33) + '***' + SUBSTRING(TXT, CHARINDEX('|', TXT, 34), 8000)
   WHERE RTRIM(TXT) LIKE '000|0000|0000000|000|%|-|-|' AND dbo.[RA_GETWORDNUM](TXT, 8, '|') ='000'

   UPDATE @tabFileExport
   SET TXT = LEFT(REPLACE(TXT, '000|0000|0000|00|0000|', '***|****|****|**|****|'),34) + '***' + SUBSTRING(TXT, CHARINDEX('|', TXT, 35), 8000)
   WHERE RTRIM(TXT) LIKE '000|0000|0000|00|0000|%|-|-|' AND dbo.[RA_GETWORDNUM](TXT, 9, '|') ='000'

   DELETE #FileExportReport
   
   INSERT #FileExportReport ([TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS]
   FROM @tabFileExport
                                  
END



GO
GRANT ALL ON dbo.RO_EXPORT_FORM_371 TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_IMPORT_FORM_371]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_IMPORT_FORM_371]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RO_IMPORT_FORM_371]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @iOrder INT,
         @liReturn INT

DECLARE @tabImport TABLE ([TXT]   VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))         
                        
                           

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] <= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=01')
      ORDER BY [ORDER]
      
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] > (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=02')
            AND [ORDER] <= (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = '#&')
            AND TXT <> 'ТБ=03'
      ORDER BY [ORDER]
      
      
      INSERT @tabImport (TXT)
      VALUES('ТБ=02')
      
      INSERT @tabImport (TXT)
      SELECT [TXT]
      FROM #IMPORT_TABLE
      WHERE [ORDER] > (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=01')
            AND [ORDER] < (SELECT MIN([ORDER]) FROM #IMPORT_TABLE WHERE TXT = 'ТБ=02')
      ORDER BY [ORDER]
      

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|****|*******|***|*|*****|***|***|', '999|9999|9999999|999|9|99999|999|999|')
      WHERE TXT LIKE '***|****|*******|***|*|*****|***|***|%' 

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|****|****|**|****|*|*****|***|***|', '777|7777|7777|77|7777|7|77777|777|777|')
      WHERE TXT LIKE '***|****|****|**|****|*|*****|***|***|%' 

      UPDATE @tabImport
      SET TXT = REPLACE(TXT, '***|**************|*|*****|***|***|', '888|8888|8888|88|8888|8|88888|888|888|')
      WHERE TXT LIKE '***|**************|*|*****|***|***|%' 
      
      UPDATE @tabImport
      SET TXT = REPLACE(REPLACE(REPLACE(TXT, '***|****|*******|***|', '000|0000|0000000|000|'), '***|****|****|**|****|', '000|0000|0000|00|0000|'), '|***|', '|000|')

      DELETE #IMPORT_TABLE
      
      INSERT #IMPORT_TABLE (TXT)
      SELECT [TXT]
      FROM @tabImport
      ORDER BY [ORDER]
--SELECT * FROM #import_table
 
      EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                     @liRepeatRequest,
                                                     @tIsAppend,
                                                     @bDinamicRows,
                                                     @iLINK_SELF,
                                                     @tMode


END

RETURN @liReturn

GO
GRANT ALL ON dbo.[RO_IMPORT_FORM_371] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RN_WEB_EDIT_TABLES]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_WEB_EDIT_TABLES]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[RN_WEB_EDIT_TABLES]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [RN_WEB_EDIT_TABLES]
GO
/*

  © Кейсистемс (Keysystems), 2006
  Редактирование/создание отчета/свода/свода сводов в WEB для таблиц формы
*/


CREATE       PROCEDURE dbo.RN_WEB_EDIT_TABLES
  @varKSnLink bigint,
  @varKSnTree int = 0, -- если форма новая, то линк дерева сводов, иначе - линк дерева таблицы
        @varKSisHeader int = 0
AS

declare @iLF int
DECLARE @DATE datetime,
  @PType  tinyint,
  @PNom tinyint,
  @DATE1 datetime,
  @DATE2 datetime, 
  @Periodic tinyint,
  @LSF  int,
  @Mode int,
  @LinkOrg int,
  @LinkBudg int,
  @atributs varchar(250)


set @LinkOrg = dbo.RO_SVOD_ORG(@varKSnTree)
set @LinkBudg = dbo.RO_SVOD_BUDG(@varKSnTree)
set @Mode = convert(int, @varKSnLink/4294967296)
set @varKSnLink = @varKSnLink - @Mode * 4294967296
set @Mode = abs(@Mode)
set @atributs = ''

print @varKSnTree
IF @varKSnTree=-2
 begin
       EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD @varKSnLink
       RETURN 
 end
IF @varKSnLink<0 and @varKSnTree>0 --новый отчет
 begin
       EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD @varKSnLink=@varKSnLink,@varKSnTree=@varKSnLink,@varKSisHeader=@varKSnLink
       RETURN 
 end

/* Список возвращаемых таблиц */
if @varKSnLink > 0
begin
--проверим есть ли атрибуты у формы
select @atributs=isnull(RTRIM(atributs),'') from REPORT_FORMS where Link_Form = (select link_form from Report_Saved_Forms where link_saved_form = @varKSnLink)

  SELECT  [alias] = 'REP_HEAD', 
    [order] = convert(smallint,0),
    [tab_name] = 'Реквизиты',
    [link_table] = convert(varchar(50), 'REPORT_SVOD'),--convert(int,0),
    [table_type] = convert(smallint,2) 
  UNION
SELECT	[alias] = 'REP_ATR', 
	[order] = convert(smallint, 1),
	[tab_name] = 'Атрибуты',
	[link_table] = convert(varchar(50), '-98'),
	[table_type] = convert(smallint, 0)
    WHERE @atributs<>'' 
UNION
  SELECT  [alias] = 'REP_TABLE_1', 
    [order] = (orders - 1) * 3 + 1,
    [tab_name] = name,
    [link_table] = convert(varchar(50), Link_Table),
    [table_type] = val_type 
  FROM RN_REPORT_TABLES
  WHERE link_table = @varKSnTree and @varKSnTree>0
  UNION
  SELECT  [alias] = 'REP_RGB_1', 
    [order] = (orders - 1) * 3 + 2,
    [tab_name] = name,
    [link_table] = convert(varchar(50), Link_Table),
    [table_type] = 21 
  FROM REPORT_TABLES
  WHERE link_table = @varKSnTree and @varKSnTree>0
  UNION
--  SELECT  [alias] = 'REP_RO_1', 
--    [order] = (orders - 1) * 3 + 3,
--    [tab_name] = name,
--    [link_table] = convert(varchar(50), Link_Table),
--    [table_type] = 22
--  FROM REPORT_TABLES
--  WHERE link_table = @varKSnTree and @varKSnTree>0
--  UNION
  SELECT  [alias] = 'REP_NASTR', 
    [order] = convert(smallint, 99),
    [tab_name] = 'Настройки печати',
    [link_table] = convert(varchar(50), '0'),
    [table_type] = convert(smallint, -1)
  ORDER BY [order]
end
else begin -- новая форма
  SELECT  [alias] = 'REP_HEAD', 
    [order] = convert(smallint,1),
    [tab_name] = 'Реквизиты',
    [link_table] = convert(varchar(50), 'REPORT_SVOD'),
    [table_type] = convert(smallint,2)
  UNION
  SELECT  [alias] = 'REP_NASTR', 
    [order] = convert(smallint, 99),
    [tab_name] = 'Настройки печати',
    [link_table] = convert(varchar(50), '0'),
    [table_type] = convert(smallint, -1)
  ORDER by [order]
end
/* Данные об отчете */
CREATE TABLE #REP_HEAD_temp ("checked" Int,"UPD" Int,"del" Int,"date" DateTime,"date_prov" DateTime,"link" Int,"period" VarChar(17),"name" VarChar(200),"code" Char(20),"Start_Date" Char(10),"link_saved_form" Int,"Link_form" Int,"Version" SmallInt,"begin_date" DateTime,"period_type" TinyInt,"period_type_web" Int,"period_number" TinyInt,"period_year" Int,"link_organization" Int,"dep_name" VarChar(254),"dep_code" Char(10),"isUpload" TinyInt,"isSvod" TinyInt,"isChangeAnalit" Bit,"IsRO" TinyInt,"Note" VarChar(4000),"Link_Type_Svod" Int,"Type_Svod" VarChar(250),"IsUsedRazdel" Int,"IsUsedCelSt" Int,"IsUsedRashod" Int,"LinkRazdel" Int,"LinkCelSt" Int,"LinkRashod" Int,"CodeRazdel" VarChar(1),"NameRazdel" VarChar(1),"CodeCelSt" VarChar(1),"NameCelSt" VarChar(1),"CodeRashod" VarChar(1),"NameRashod" VarChar(1),"Print_Object_Method" VarChar(200),"Query_Add_Module" VarChar(200),"Query_Before" VarChar(200),"Query_RepMaker" VarChar(200),"Query_Report" VarChar(200),"Query_Report_Path" VarChar(200),"Decript_Proc" VarChar(30),"IsRemoteAccess" TinyInt,"RULES" TinyInt,"isCalcItog" Int,"IsRO_MASK" Int,"CountSave" Int,"Object" varChar(250),[IS_AUTOFILL] TINYINT,"IsCopy" BIT,"End_Date" Char(10), Query_Report_New varchar(250), Print_Object_Method_New varchar(250))
CREATE TABLE #note (link INT, note_all TEXT)
if @varKSnLink > 0 and (@varKSnTree>0 )
begin
  insert #REP_HEAD_temp exec I_REPORT_USER_SAVED_FORM @varKSiLinkSF =@varKSnLink, @bIsWeb = 1 -- редактирование
        --обновим countsave из report_saved_tables
        IF @varKSnTree>0
                UPDATE #REP_HEAD_temp SET CountSave=coalesce((select top 1 countsave from REPORT_SAVED_TABLES where Link_Saved_Form=@varKSnLink and Link_Table=@varKSnTree),0)

   INSERT #note (link, note_all)
   EXEC dbo.RO_SAVED_FORM_NOTES @varKSnLink
   
  select @varKSnTree as Link_Table, T.*, Note_All from #REP_HEAD_temp T, #note N

    --атрибуты
    IF @atributs<>''
    begin
        exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,0
    end

  /* Таблицы отчета, настройки цвета, настройки readonly */
  DECLARE @iLTable  INT,
    @cRuStr   varchar(8000)
--новый вызов
--   IF OBJECT_ID('RI_PROC_T'  + ltrim(convert(varchar(15),@varKSnTree))) IS NULL
--   BEGIN
--       SET @cRuStr = 'EXEC [I_REPORT_CREATE_PROC] ' + LTRIM(STR(@varKSnTree))
--       execute (@cRuStr) 
--   END 
   
  SET @cRuStr = 'EXEC dbo.RI_PROC_T' + ltrim(convert(varchar(15),@varKSnTree)) + ' ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end)+',default,default,default,default,default,default,default,1'
  SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@varKSnTree)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end)+ ',''COL'',2,default,default,default,default,1'
--старый вызов
--  SET @cRuStr = 'EXEC dbo.RI_PROC_T' + ltrim(convert(varchar(15),@varKSnTree)) + ' ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end)
--  SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@varKSnTree)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end)
--  SET @cRuStr = @cRuStr + ' EXEC dbo.RO_TOTAL_CELLS ' + LTRIM(STR(@varKSnTree)) + ', ' + (case when @varKSnLink>0 then convert(varchar(15), @varKSnLink) else '0'  end) + ', ''COL'', 1'

  print @cRuStr
  execute (@cRuStr)
--блокируем отчет
print @varKSnLink
print @varKSnTree
  IF @varKSnLink>0 
	exec RN_LOCK_FORM @varKSnLink,@varKSnTree,'',1
end
else
begin -- новый отчет
   
        IF  @varKSnTree=-1
        BEGIN
          --PRINT 'exec I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg, 1'
          insert #REP_HEAD_temp 
          exec I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg, 1
        END
        ELSE BEGIN                  
          IF @varKSnTree=-1000
          BEGIN
            --PRINT 'I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg, 1,1'          
            insert #REP_HEAD_temp 
            EXEC I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg, 1,1
          END
          ELSE BEGIN
            --PRINT 'I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg'          
            insert #REP_HEAD_temp 
            EXEC I_REPORT_USER_SAVED_FORM @varKSnLink, @LinkOrg, @LinkBudg
          END
        END

   INSERT #note (link, note_all)
   EXEC dbo.RO_SAVED_FORM_NOTES @varKSnLink



--   if  @varKSnTree <> -1000
--	   select T.*, Note_All from #REP_HEAD_temp T, #note N      
--   else
	   select T.*, Note_All from #REP_HEAD_temp T, #note N      



    --атрибуты
    IF @atributs<>''
    begin
        exec RN_GET_ATRIBUT_VALUES  @varKSnLink,null,0
    end

end
  drop table #REP_HEAD_temp
/* Настройки печати */
DECLARE @iLOrg  int,
  @DocDate  datetime
EXEC @iLOrg = getowndeplink 
IF @varKSnLink>0
  select @iLOrg = link_organization, @DocDate = begin_date from report_saved_forms where link_saved_form = @varKSnLink
ELSE
  select @DocDate = getdate()

select *, convert(char(10), @DocDate + 1, 104) as Doc_Date from dbo.PrintDoc_GetDepData2 (@iLOrg)


GO
GRANT ALL ON dbo.[RN_WEB_EDIT_TABLES] 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].[BV_SAVE_G_PROV2_AP_AO_REP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_SAVE_G_PROV2_AP_AO_REP]
GO








/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE BV_SAVE_G_PROV2_AP_AO_REP
	@varKSnLINK_GP1  INT,		
	@varKSnDT_LINK INT,			
	@varKSnKT_LINK  INT,			
	@varKSnEKR_DT INT =0,
	@varKSnEKR_KT INT =0,
	@varKSnEMP INT =0,
	@varKSnOSNOV INT =0,
	@varKSnINV INT =0,
	@varKSnNOMEN INT =0,
	@varKSnSUMMA	NUMERIC(28,2) = 0.00,
	@varKSnQTY	NUMERIC(19,4) = 0.0000,
	@varKSnKBK INT,
	@varKSnDEP INT,
	@varKSnSUB INT,
	@intAO_EMPL INT
	
AS

DECLARE 
--	@varKSnNOMEN INT,
--	@varKSnINV INT,
	@varKSnKAU INT,
	@varKSnDEP_ACC INT,
	@varKSnTMC INT,
	@varKSnINDATE DATETIME,
	@varKSnAP1 INT,
	@varKSnAP2 INT,
	@varKSnAP3 INT,

	@varKSnG2_LINK  INT,
	@varKScG2_NAME  VARCHAR(254),
	@varKSnG2_ECON_OPER INT,
	@varKSnG2_ORDERS INT,
	@varKSnLINK_GP2 INT,
	@varKSnSGU_DT INT,
	@varKSnSGU_KT INT,
	@varKSxRet INT,
	@intP_KASSA	TINYINT,
	@cSINTH		CHAR (3)
	
IF @varKSnLINK_GP1 IS NULL
	RETURN -1	

-- Берется первая хоз.операция , а надо бы вообще перевести грид авансового отчета на работу с хоз.операциями
SELECT TOP 1 @varKSnG2_ECON_OPER = T.LINK, @varKScG2_NAME = RTRIM(CONVERT(VARCHAR(254), XO.NAME))
FROM DBO.BX_BPROV_VIBOR_ECON_OPER(@varKSnDT_LINK,@varKSnKT_LINK) T, XOZ_OPER XO
WHERE XO.LINK = T.LINK
 
SET @varKSnG2_ORDERS = 1

SET @varKSnLINK_GP2 = NULL
EXEC @varKSxRet = X_UPDATE_G_PROV2 @varKSnLINK_GP2 OUTPUT, @varKSnLINK_GP1, NULL,
	@varKSnSumma, @varKSnQTY, 0, @varKScG2_NAME, @varKSnG2_ECON_OPER,  @varKSnG2_ORDERS
IF @varKSxRet <> 0
	RETURN @varKSxRet
IF @varKSnLINK_GP2 IS NULL
	RETURN -3	

--SELECT @varKSnLINK_DOC = LINK_UP FROM G_PROV1 WHERE LINK = @varKSnLINK_GP1

/*
SELECT TOP 1 
	@varKSnKBK = KBK_LINK,
--	@varKSnEMP = EMP_LINK,
	@varKSnSUB = OTDEL_LINK
FROM BV_DOC_AVANSE_REP WHERE LINK = @varKSnLINK_DOC
*/
--EXEC X_GET_OWN_DEP_LINK @varKSnDEP OUTPUT

IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnDT_LINK AND cSinth = '401') AND @varKSnEKR_DT <> 0
	SET @varKSnSGU_DT = @varKSnEKR_DT
ELSE
	SELECT TOP 1 @varKSnSGU_DT = SGU_LINK
	FROM DBO.PLAN_ACCOUNTS_SGU
	WHERE ACCOUNT = @varKSnDT_LINK AND DB_KR = 0

IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnKT_LINK AND cSinth = '401') AND @varKSnEKR_KT <> 0
	SET @varKSnSGU_KT = @varKSnEKR_KT
ELSE
	SELECT TOP 1 @varKSnSGU_KT = SGU_LINK
	FROM DBO.PLAN_ACCOUNTS_SGU
	WHERE ACCOUNT = @varKSnKT_LINK AND DB_KR = 1

/*
IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE p_KASSA = 1  AND LINK = @varKSnDT_LINK)
  SET @varKSnEKR_DT = @varKSnSGU_DT
*/

SET @intP_KASSA	= 0
SET @cSINTH = ''

SELECT @intP_KASSA = p_KASSA, @cSINTH = cSINTH
FROM dbo.S_ACCOUNTS
WHERE LINK = @varKSnDT_LINK

IF @intP_KASSA = 1
  SET @varKSnEKR_DT = @varKSnSGU_DT

IF @cSINTH = '208'
  SET @varKSnEMP = @intAO_EMPL

SELECT @varKSnEKR_DT = ANALIT_EKR FROM S_ACCOUNTS WHERE LINK = @varKSnDT_LINK AND p_EKR = 1
EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 0, @varKSnDT_LINK, @varKSnKBK, @varKSnEKR_DT, @varKSnDEP,
	@varKSnSUB, @varKSnEMP, @varKSnNOMEN, @varKSnINV, 0, 0, 0, 0, @varKSnOSNOV, 0, 0, @varKSnSGU_DT
IF @varKSxRet <> 0
	RETURN @varKSxRet

/*
IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE p_KASSA = 1  AND LINK = @varKSnKT_LINK)
  SET @varKSnEKR_KT = @varKSnSGU_KT
*/

SET @intP_KASSA	= 0
SET @cSINTH = ''

SELECT @intP_KASSA = p_KASSA, @cSINTH = cSINTH
FROM dbo.S_ACCOUNTS
WHERE LINK = @varKSnKT_LINK

IF @intP_KASSA = 1
  SET @varKSnEKR_KT = @varKSnSGU_KT

IF @cSINTH = '208'
  SET @varKSnEMP = @intAO_EMPL

SELECT @varKSnEKR_KT = ANALIT_EKR FROM S_ACCOUNTS WHERE LINK = @varKSnKT_LINK AND p_EKR = 1
EXEC @varKSxRet = X_UPDATE_G_PROV_AP @varKSnLINK_GP2, 1, @varKSnKT_LINK, @varKSnKBK, @varKSnEKR_KT, @varKSnDEP,
	@varKSnSUB, @varKSnEMP, @varKSnNOMEN, @varKSnINV, 0, 0, 0, 0, @varKSnOSNOV, 0, 0, @varKSnSGU_KT
IF @varKSxRet <> 0
	RETURN @varKSxRet

RETURN 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_RAZMNOJ_KS_OUTSIDE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_RAZMNOJ_KS_OUTSIDE]
GO


/*
c Кейсистемс (Keysystems), 2009
Размножение правил "для всех столбцов", "для всех колонок"
с учетом диапазона столбцов и колонок для правил, в котором есть деление, умножение, маски

create table #t_KS (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(250), Filter_desc varchar(250), Mask varchar(250), part tinyint, algorithm tinyint, cols varchar(250), [rows] varchar(250), [Value] float, orderCol tinyint default 0, CodeRow varchar(254) default '',cOrderTable varchar(254), cOrderCol varchar(10))
create table #t_Rows_Static(Link_Row int primary key, Code varchar(50), Link_Table int)
create table #report_Dinamics(Link_SF int, Code_Row varchar(50), link_col int, float_val numeric(20,4), str_val varchar(8000))
*/
CREATE    PROCEDURE dbo.RO_RAZMNOJ_KS_OUTSIDE
  @From tinyint = 0, -- откуда вызвали, 0 - с проверки КС, 1 - с досчета КС,
  @cProgressTable     varchar(254)  = ''

AS

if object_id('tempdb..#t_KS') is NULL
begin
  return -1
end

create table #t_KS2 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1000), 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)

insert #t_KS2
select *
from #t_KS
where algorithm = 0    



delete #t_KS where algorithm = 0

declare @link_table int,@calc_maska int,@ExecStr varchar(8000), @LinkRule int, @LinkTable int, @ValType tinyint, @CondRows varchar(3000),@get_str varchar(250),@ExecStr1 varchar(8000)
declare @strProgressExec varchar(1000), @lsf int

create table #t_temp (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1250), 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)

   update #T_KS2
    set mask=dbo.ra_getwordnum(mask,1,'#')         
    where  mask like '%#%' and mask not like '%select%' 


-- РАЗМНОЖАЕМ КОЛОНКИ   
insert #t_temp
  select * from #t_KS2 where (Link_Col is NULL or Cols <> '') and (Val_Type = 0 or Val_Type = 3 or Val_Type = 4)
  

 delete #t_KS2 where (Link_Col is NULL or Cols <> '') and (Val_Type = 0 or Val_Type = 3 or Val_Type = 4)

insert #t_KS2
  select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, B.Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], B.orderCol, CodeRow, cOrderTable, B.cOrderCol, px_comment, [property]
  from #t_temp A left merge join #t_Col B on A.link_table = B.link_table
  where A.Cols = '' or (A.Cols <> '' and CHARINDEX(',' + LTRIM(STR(B.OrderCol)) + ',', ',' + RTRIM(A.Cols) + ',') > 0) 

insert #t_KS2 
  select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, B.Link_Table, B.Link_Col, Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], C.orderCol, CodeRow, cOrderTable, B.cOrderCol, px_comment, [property]
  from #t_Col C, #t_KS2 B  
  where B.orderCol = 0
    and C.Link_Table = (select top 1 Link_Table from #t_temp A1 where A1.Link_Rule = B.Link_Rule and Link_Table is NOT NULL) 
    and not exists(select top 1 * from #t_temp A where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow)
    and (B.Cols = '' or (B.Cols <> '' and CHARINDEX(',' + LTRIM(STR(C.OrderCol)) + ',', ',' + B.Cols + ',') > 0))

delete #t_KS2 where Link_Rule in (select distinct Link_Rule from #t_temp) and (orderCol = 0)


--select * from #t_ks where link_rule=745468 order by orders,orderrow
--  select * from #t_KS where [Rows] <> '' and filter<>''
if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка правил'', percents = 32'
        execute(@strProgressExec)
end

truncate table #t_temp

if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка правил'', percents = 31'
        execute(@strProgressExec)
end


-- РАЗМНОЖАЕМ СТРОКИ С ДИАПАЗОНОМ
declare @t_table table (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), 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)

insert #t_temp
  select * from #t_KS2 where [Rows] <> '' and rtrim(filter)=''

insert @t_table
select * from #t_temp

delete #t_KS2 where [Rows] <> '' and val_type<>1 and rtrim(filter)=''

while exists(select top 1 * from #t_temp)
begin
  set @LinkTable=null	
  select top 1 @LinkRule = Link_Rule, @CondRows = [Rows] from #t_temp

  select top 1 @LinkTable = Link_Table, @ValType = Val_Type from #t_temp where Link_Rule = @LinkRule and Link_Table is NOT NULL
  if @ValType = 0 -- таблица статическая
  begin
    set @ExecStr = 'insert #t_KS2 
select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join #t_Rows_Static B on A.link_table = B.link_table
where A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and B.Link_Table  = ' + STR(@LinkTable) + ' and ' + REPLACE(@CondRows, 'COL(', 'dbo.RO_COL_Static(A.lsf,' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')
  end
  else 
    begin -- таблица динамическая
  set @ExecStr = 'insert #t_KS2
select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, RD.Code_Row, cOrderTable, cOrderCol, px_comment, [property]
from #t_temp A inner join 
#report_dinamics RD on A.lsf = RD.Link_SF and A.Link_Col = RD.Link_Col
where A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and RD.Link_Table  = ' + STR(@LinkTable) + ' and ' + REPLACE(REPLACE(REPLACE(@CondRows, 'CODE', 'RD.Code_Row'),'.RD.Code_Row', '.CODE'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,' + LTRIM(STR(@LinkTable)) + ', RD.Code_Row,')
end
 print @ExecStr
  execute(@ExecStr)
IF @linktable is null
	delete #t_temp where Link_Rule = @LinkRule and link_table is null
else
	delete #t_temp where Link_Rule = @LinkRule and link_table=@linktable
delete #t_temp where Link_Rule = @LinkRule and link_table=isnull(@linktable,link_table) 


end
-- если вообще нет строк
insert #t_KS2 
select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, NULL, 'нет данных', Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, '', cOrderTable, cOrderCol, px_comment, [property]
from @t_table A
where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and CodeRow <> '')

insert #t_KS2 -- в случае если есть другие слагаемые, которые не надо размножать
select A.Link_Rule, OrderRow, val_type, [sign],Link_Form, period_form, period_type, period_year, begin_date, budg_code, A.atr_code, lsf, A.Link_Table, A.Link_Col, NULL, K1.CodeRow, Factor, px, Exec_Proc, Filter, Filter_desc, Mask , part, algorithm, cols, [rows], [Value], A.orderCol, K1.CodeRow, cOrderTable, cOrderCol,px_comment, [property]
from @t_table A  inner join (select distinct Link_Rule, CodeRow, OrderCol, atr_code from #t_ks2 where CodeRow <> '') K1 on A.Link_Rule = K1.Link_Rule and A.orderCol = K1.OrderCol and A.atr_code = K1.atr_code
where not exists(select * from #t_KS2 K where A.Link_Rule = K.Link_Rule and A.orderCol = K.orderCol and A.OrderRow = K.OrderRow and K.CodeRow = K1.CodeRow)

if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка правил'', percents = 33'
        execute(@strProgressExec)
end

-------------\
truncate table #t_temp
-- РАЗМНОЖАЕМ СТРОКИ С ФИЛЬТРОМ, с учетом МАСКИ

declare @LF int, @LC int, @OrderCol tinyint, @Dict varchar(254), @DictCol varchar(254), @DictField varchar(254), 
   @Field varchar(50), @i int, @Fields varchar(254), @Cols varchar(254), @Col varchar(50), 
  @CodeCol varchar(254), @FieldCol varchar(254), @LinkCol int, @LT int, @option_import_report int, @px_comment varchar(1000)

    
insert #t_temp
  select * from #t_KS2 where [Filter] <> '' or Mask <> ''

delete @t_table
insert @t_table
select * from #t_temp

delete #t_KS2 where [Filter] <> '' or Mask <> ''
declare @condFilter varchar(3000),@orderrow int,@condMaska varchar(1250), @lsf_left INT, @dBeginDate DATETIME, @iDiffDate INT, @atr_code VARCHAR(50)   
create table #t_KS1 (Link_Rule int, OrderRow int, val_type tinyint, [sign] char(2), Link_Form int, period_form smallint, period_type tinyint, period_year smallint, begin_date datetime, budg_code char(5), atr_code varchar(254), lsf int,
		Link_Table int, Link_Col int, Link_Row int, Code_Row varchar(50), Factor float, px float, Exec_Proc varchar(250), Filter varchar(1000), Filter_desc varchar(250), Mask varchar(1000), 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)

SELECT @dBeginDate = max(rsf.[Begin_Date])
FROM  #t_temp T 
   JOIN dbo.[REPORT_SAVED_FORMS] rsf ON T.[lsf] = rsf.[Link_Saved_Form]
WHERE lsf IS NOT null

SET @iDiffDate = DATEDIFF(DAY, '20111231', @dBeginDate)

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'
EXEC dbo.[BufferPush] @iDiffDate, 'RO_RAZMNOJ_KS_OUTSIDE'


while exists(select top 1 * from #t_temp)
begin
  select top 1 @LinkRule = Link_Rule, @atr_code = ISNULL([atr_code], ''), @px_comment = 
			case when px_comment like '%#%' then  REPLACE(REPLACE(REPLACE(REPLACE(px_comment, '@@OPTIONAL', ''), '@@', ''), '#',''), '"', '''')  else 'code' end, 
			@CondFilter ='('+rtrim([Filter])+')' + case when [rows] <> '' then ' and (' + [rows] + ')' else '' end ,@CondMaska =[Mask], @orderrow = orderrow, @lsf = lsf, @lt = lINK_tABLE, @lf = Link_Form from #t_temp order by orderrow desc

	
	set @lsf_left = 0
	select @lsf_left = lsf from #t_temp where @LinkRule = Link_Rule and part = 0 AND ISNULL([atr_code],'') = @atr_code
--print  dbo.RN_GET_ATR_VALUE(@lsf_left, B.code)
	-- атрибуты в фильтрах
	select  @CondFilter = REPLACE(@CondFilter, '$' + rtrim(B.code) + '$', '''' + dbo.RN_GET_ATR_VALUE(@lsf_left, B.code) + '''')
	from dbo.N_REPORT_ATRIBUTS_VIEW B 

	-- атрибуты в фильтрах
	select  @CondFilter = REPLACE(@CondFilter, '#' + rtrim(B.code) + '#', 'dbo.RN_GET_ATR_VALUE(A.lsf, ''' + RTRIM(B.Code) + ''')')
	from dbo.N_REPORT_ATRIBUTS_VIEW B 

	set @CondFilter = REPLACE(REPLACE(@CondFilter,'$ОТЧЕТ$', LTRIM(STR(@lf))),'$ТАБЛИЦА$',LTRIM(STR(@lt)))
	set @CondFilter = REPLACE(@CondFilter,'#ОТЧЕТ#', LTRIM(STR(@lsf_left)))	
	set @condMaska = REPLACE(@condMaska,'#ОТЧЕТ#', LTRIM(STR(@lsf_left)))	

	if @CondFilter = '()'
		set @CondFilter = '(1=1)'
      
  select top 1 @LinkTable = Link_Table  from #t_temp where Link_Rule = @LinkRule and Link_Table is NOT NULL and orderrow = @orderrow
  select top 1 @valtype=val_type from #report_tables RT join report_forms RF on RT.Link_Form = RF.Link_Form where link_table=@linkTable 
  if @ValType = 0 -- таблица статическая
  begin
       set @condMaska= RTRIM(case when @condMaska<>'' then '+'+REPLACE(REPLACE(REPLACE(@condMaska, 'CODE', 'B.CODE'), '.B.CODE', '.CODE'), 'COL(', 'dbo.RO_COL_Static(A.lsf, ' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')   else '' end)
       set @ExecStr=''
       set @ExecStr = 'insert #t_KS1 
		select Link_Rule, OrderRow, 0, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc,' + REPLACE(REPLACE(@px_comment, 'CODE', 'B.CODE'), 'COL(', 'dbo.RO_COL_Static(A.lsf, ' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,') + ', part, algorithm, cols, [rows], [Value], orderCol, ' + case when @condMaska = '' then '''''' else @condMaska end + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join #t_Rows_Static B on A.link_table = B.link_table
        where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and ' + REPLACE(@CondFilter, 'COL(', 'dbo.RO_COL_Static(A.lsf, ' + LTRIM(STR(@LinkTable)) + ', B.Link_Row,')
  end
  else begin -- таблица динамическая
    set @condMaska= RTRIM(case when @condMaska<>'' then '+'+REPLACE(REPLACE(@CondMaska, 'CODE', 'RD.Code_Row'), 'COL(', 'dbo.RO_COL_Dinamic(RD.Link_SF,' + LTRIM(STR(@LinkTable)) + ', RD.Code_Row,')   else '' end)

   SET @CondFilter = REPLACE(REPLACE(@CondFilter, 'CODE', 'RD.Code_Row'),'.RD.Code_Row','.Code')
   SET @CondFilter = REPLACE(REPLACE(@CondFilter, 'LEFT(RD1.Code_row,11)', 'RD1.csr'), 'LEFT(RD.Code_Row,11)', 'RD.csr')
   
   IF COL_LENGTH('tempdb..#report_dinamics', 'csr') IS NULL AND @CondFilter LIKE '%csr%'
   BEGIN
      ALTER TABLE #report_dinamics ADD csr CHAR(11)
      CREATE INDEX #ix_report_dinamics_csr ON #report_dinamics (link_col, csr)
      set @ExecStr = '
         UPDATE #report_dinamics
      SET csr = left(Code_Row,11)'
      EXECUTE (@ExecStr)
   END     

    set @ExecStr = '
        insert #t_KS1 
		select Link_Rule, OrderRow, 3, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, NULL, RD.Code_Row, Factor, px, Exec_Proc, Filter, Filter_desc, ' +  REPLACE(REPLACE(@px_comment,'code', 'RD.Code_Row'), 'COL(', '(select top 1 str_val from #report_dinamics  RF 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders =')  /* поле Mask  нам уже не нужно, но нужно отображаемая маска на слагаемое*/ + ' , part, algorithm, cols, [rows], [Value], orderCol, ' + REPLACE(case when @condMaska = '' then '''''' else @condMaska end,'.RD.Code_Row','.Code') + ', cOrderTable, cOrderCol, px_comment, [property]
        from #t_temp A left join 
        #report_dinamics RD on A.lsf = RD.Link_sf and A.Link_Col = RD.Link_Col '+
        'where A.orderrow='+LTRIM(STR(@orderrow))+ ' and A.Link_Rule = ' + LTRIM(STR(@LinkRule)) + ' and isnull(atr_code,'''') = ''' + @atr_code + ''' and ' + REPLACE(REPLACE(@CondFilter, 'COLS(','(select top 1 str_val from #report_dinamics  RF 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders ='), 'COL(','(select top 1 case when RC.Col_Type = 1 then str_val else float_val end from #report_dinamics  RF 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 =' + LTRIM(STR(@LinkTable))+' and RC.orders =') 

	if @condMaska = ''
        set @ExecStr = @ExecStr + ' IF @@rowcount=0 
        insert #t_KS1 
		select Link_Rule, OrderRow, 1, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, Link_Table, Link_Col, NULL, ''нет строк'', Factor, px, Exec_Proc, Filter, Filter_desc, '''' , part, algorithm, cols, [rows], [Value], orderCol, CodeRow, cOrderTable, cOrderCol, px_comment,[property]
        from #t_temp  where orderrow='+LTRIM(STR(@orderrow))+ ' and Link_Rule = ' + LTRIM(STR(@LinkRule))
    
  end

--print @ExecStr
 execute(@ExecStr)

--добавим недостающие слагаемые
--  INSERT #t_KS1
--        select Link_Rule, OrderRule, OrderRow,1, Sign, LinkTable, LinkCol, NULL, '', CodeRow, [Rows], 0, Exec_Proc, Exec_Proc_Desc, Filter, Mask, 0, A.ORDERS, Filter_Desc, Mask_Desc,isLeftPart
--        from #t_temp A where not Exists(select * from #t_ks1 B where B.link_rule=@LinkRule and B.OrderRow=@orderRow)

  delete #t_temp where Link_Rule = @LinkRule and orderrow = @orderrow AND isnull(atr_code,'') = @atr_code
end

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'

	update #t_KS1
	set CodeRow = K.CodeRow
	from (select * from #t_KS1 where CodeRow <> '') K
	where  #t_KS1.Code_Row = 'нет строк' and K.Link_Rule = #t_KS1.Link_Rule and K.orderCol = #t_KS1.orderCol

	insert #t_KS1
	select T.Link_Rule, T.OrderRow, 3, T.[sign],  T.Link_Form, T.period_form, T.period_type, T.period_year, T.begin_date, T.budg_code, T.atr_code, T.lsf, T.Link_Table, T.Link_Col, NULL, 'нет строк', T.Factor, T.px, T.Exec_Proc, T.Filter, T.Filter_desc, '' , T.part, T.algorithm, T.cols, T.[rows], T.[Value], T.orderCol, K.CodeRow, T.cOrderTable, T.cOrderCol, px_comment, [property]
	from (select distinct Link_Rule, orderCol, CodeRow from #t_KS1 where CodeRow <> '' ) K inner join @t_table T on K.Link_Rule = T.Link_Rule and K.orderCol = T.orderCol
	where T.val_type <> 0 and not exists(select top 1 * from #t_KS1 K1 where K1.Link_Rule = T.Link_Rule and K1.orderCol = T.orderCol and K1.orderrow = T.orderRow and K1.CodeRow = K.CodeRow)

	if @From = 1
		delete #t_ks1
		where isnull(CodeRow,'') = '' and (isnull(Code_Row,'') = '' or Code_Row = 'нет строк') and Link_Row is NULL and part = 0

	update #t_KS1
	set Code_Row = CodeRow, px_comment = ''
	where Code_Row = 'нет строк' and isnull(CodeRow, '') <>''


	update #t_KS1
	set Mask = case when Code_Row = 'нет строк' then 'нет строк для фильтра ' + Filter_desc else Code_Row end
	where Mask = ''


	update #t_KS1
	set px_comment = case when px_comment like '%#%' then '' else REPLACE(px_comment, '@@OPTIONAL', '') end

    insert #t_ks2
    select *
    from #t_ks1 

------------

if @cProgressTable <>'' begin
        set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка правил'', percents = 34'
        execute(@strProgressExec)
end


truncate table #t_temp

-- РАЗМНОЖАЕМ СТРОКИ БЕЗ ДИАПАЗОНА
insert #t_temp
  select * from #t_KS2 where  ((Link_Row is NULL and Val_Type = 0) or (Code_Row = '' and Val_Type = 3)) and [Rows] = '' 


delete #t_KS2 where ((Link_Row is NULL and Val_Type = 0) or (Code_Row = '' and Val_Type = 3)) and [Rows] = ''

-- для статических таблиц
insert #t_KS2 
	select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code, cOrderTable, cOrderCol, px_comment, [property]
	  from #t_temp A inner join #t_Rows_Static B on A.link_table = B.link_table
    
insert #t_KS2 
	select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, B.Link_Table, B.Link_Col, B.Link_Row, Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, C.Code, cOrderTable, cOrderCol, px_comment, [property]
  from #t_Rows_Static C, #t_KS2 B  
  where B.CodeRow = '' and C.Link_Table = (select top 1 Link_Table from #t_temp A1 where A1.Link_Rule = B.Link_Rule) 
    and not exists(select top 1 * from #t_temp A where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow)


-- для динамических таблиц
 insert #t_KS2
	select Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, A.Link_Table, A.Link_Col, NULL, B.Code_Row, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], orderCol, B.Code_Row, cOrderTable, cOrderCol, px_comment, [property]
     from #t_temp A inner join report_dinamics B on A.lsf = B.Link_SF and A.Link_Col = B.Link_Col



insert #t_KS2
		select B.Link_Rule, OrderRow, val_type, [sign], Link_Form, period_form, period_type, period_year, begin_date, budg_code, atr_code, lsf, B.Link_Table, B.Link_Col, NULL, B1.CodeRow, Factor, px, Exec_Proc, Filter, Filter_Desc, Mask , part, algorithm, cols, [rows], [Value], B.orderCol, B1.CodeRow, cOrderTable, cOrderCol, px_comment, [property]
  from #t_temp B join (select distinct Link_Rule, CodeRow, orderCol from #t_KS2 where CodeRow <> '' and Val_Type = 3) B1 on B.Link_Rule = B1.Link_Rule and B.orderCol = B1.orderCol
  where  B.CodeRow = '' and Val_Type = 3 
    and not exists(select top 1 * from #t_KS2 A where A.link_Rule = B.link_Rule and A.OrderRow = B.OrderRow and B.orderCol = A.orderCol)


update #t_KS2
set algorithm = 1
where Link_Rule not in (select Link_Rule from #t_KS2 where sign not in ('+', '-'))


insert #t_KS
select * from #t_KS2

drop table #t_temp
drop table #t_KS1
drop table #t_KS2

GO
GRANT ALL ON dbo.[RO_RAZMNOJ_KS_OUTSIDE] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_152_CKS]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_152_CKS]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2012

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_152_CKS]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn    INT,
        @lvcTXT      VARCHAR(8000),
        @lvcWord1    VARCHAR(8000),
        @lvcWord2    VARCHAR(8000),
        @lvcKBP      VARCHAR(50),
        @lvcVB       VARCHAR(50),
        @liORDER     INT,
        @liORDER_END INT,
        @i           INT,
        @vcUK        VARCHAR(50),
        @dDT         SMALLDATETIME,
        
        @vcComment   VARCHAR(8000),
        @vcChiefName VARCHAR(8000),
        @vcGlBuhName VARCHAR(8000)
        
SELECT @vcUK = dbo.[RA_GETWORDNUM]([TXT],3,'|')
FROM #IMPORT_TABLE
WHERE LEFT([TXT],3) = 'TO|'   
      
SELECT @lvcKBP = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
      LEFT([TXT],3) IN ('KБ=')

SELECT @lvcVB = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

IF @lvcKBP IS NULL
BEGIN
   SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],'')      
   FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
   WHERE [UK] = @vcUK and form_code = '0503152'
END

IF @lvcVB IS NULL 
BEGIN
   SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
   FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
   WHERE [UK] = @vcUK and form_code = '0503152'
END

IF @lvcKBP IS NULL
BEGIN
   SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_152' AND
         [CODE] = 'IMPORT_KBP_152'
END

IF @lvcVB IS NULL 
BEGIN
   SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_152' AND
         [CODE] = 'IMPORT_VB_152'
END

SELECT @dDT = CONVERT(SMALLDATETIME,dbo.[RA_GETWORDNUM]([TXT],5,'|'),104)
FROM #IMPORT_TABLE
WHERE LEFT([TXT],3) = 'KS|'   

CREATE TABLE #tabImportTemp ([TXT] VARCHAR(8000), [ORDER] INT IDENTITY(1,1))
        
INSERT #tabImportTemp([TXT]) VALUES('РД=1')        
INSERT #tabImportTemp([TXT])
SELECT dbo.[RA_GETWORDNUM]([TXT],2,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],3,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],5,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],6,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],7,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],8,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],9,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],10,'|')+'|' 
FROM #IMPORT_TABLE
WHERE LEFT([TXT],7) = 'KS_DOH|'
        
INSERT #tabImportTemp([TXT]) VALUES('РД=2')        
INSERT #tabImportTemp([TXT])
SELECT dbo.[RA_GETWORDNUM]([TXT],2,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],5,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],6,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],7,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],8,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],9,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],10,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],3,'|')+'|' 
FROM #IMPORT_TABLE
WHERE LEFT([TXT],7) = 'KS_RAS|'
        
INSERT #tabImportTemp([TXT]) VALUES('РД=3')        
INSERT #tabImportTemp([TXT])
SELECT dbo.[RA_GETWORDNUM]([TXT],5,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],6,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],7,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],8,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],9,'|')+'|'+ dbo.[RA_GETWORDNUM]([TXT],10,'|')+'|'+
       dbo.[RA_GETWORDNUM]([TXT],2,'|')+dbo.[RA_GETWORDNUM]([TXT],3,'|') + '|' 
FROM #IMPORT_TABLE
WHERE LEFT([TXT],7) = 'KS_IST|'
                
SELECT @vcChiefName = dbo.[RA_GETWORDNUM]([TXT],8,'|'),
       @vcGlBuhName = dbo.[RA_GETWORDNUM]([TXT],9,'|'),
       @vcComment = dbo.[RA_GETWORDNUM]([TXT],11,'|')
FROM #IMPORT_TABLE
WHERE LEFT([TXT],3) = 'KS|' 
                
DELETE #IMPORT_TABLE

/*
WHERE LEFT([TXT],3) IN ('FK|','TO|','KS|') OR
      LEFT([TXT],5) IN ('FROM|')
*/

INSERT #IMPORT_TABLE([TXT]) VALUES ('ВФ=0')
INSERT #IMPORT_TABLE([TXT]) VALUES (ISNULL(@lvcKBP,'KБП='))
INSERT #IMPORT_TABLE([TXT]) VALUES (ISNULL(@lvcVB,'ВБ='))
INSERT #IMPORT_TABLE([TXT]) VALUES ('КФ=0503152M')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ПРД=4')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ДФ=01.01.2012')
INSERT #IMPORT_TABLE([TXT]) VALUES ('ДТ=' + CONVERT(VARCHAR(50),@dDT,104))

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM #tabImportTemp
ORDER BY [ORDER]

DROP TABLE #tabImportTemp 

INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=4')
INSERT #IMPORT_TABLE([TXT]) VALUES ('Примечание||')
INSERT #IMPORT_TABLE([TXT]) VALUES ('РД=5')
INSERT #IMPORT_TABLE([TXT]) VALUES ('Необязательный комментарий|' + ISNULL(@vcComment,'') + '||')
INSERT #IMPORT_TABLE([TXT]) VALUES ('Начальник||' + ISNULL(@vcChiefName,'') + '|')
INSERT #IMPORT_TABLE([TXT]) VALUES ('Главный бухгалтер||' + ISNULL(@vcGlBuhName,'') + '|')


--SELECT * FROM #IMPORT_TABLE
     


EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                               @liRepeatRequest,
                                               @tIsAppend,
                                               @bDinamicRows,
                                               @iLINK_SELF,
                                               @tMode



RETURN @liReturn

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_152_CKS] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[I_REPORT_FORMULA_P4_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[I_REPORT_FORMULA_P4_PREPARE]

GO

CREATE PROCEDURE DBO.I_REPORT_FORMULA_P4_PREPARE
	@OUT_VAL 	VARCHAR(20) OUTPUT,
	@BDATE		DATETIME,
	@ENDDATE	DATETIME,
	@DEP_LINK	INT,
	@VARILSF	INT
AS BEGIN
	DECLARE @PEOPLE_COUNT VARCHAR(100)
	EXEC DBO.X_GET_TABLE_NAME @PEOPLE_COUNT OUTPUT
	EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0

DECLARE @FILTER_SUBDIV_NAME VARCHAR(254), @FILTER_SUBDIV_LINK INT
DECLARE @SUBDIV TABLE (LINK INT)

SET @FILTER_SUBDIV_NAME = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_FILTER_SUBDIV'))

IF @FILTER_SUBDIV_NAME IS NOT NULL
	SET @FILTER_SUBDIV_LINK = 
		( SELECT TOP 1 LINK FROM DBO.REPORT_KBK 
		WHERE ('№' + CONVERT(VARCHAR(3),PROPERTY) + ' - ' + NAME) = @FILTER_SUBDIV_NAME
			AND CODE_FORM='FILTER_NABOR' AND CODE='REPORTS_FILTER_SUBDIV')

DECLARE @BUFFER_SUBDIV VARCHAR(20)

IF @FILTER_SUBDIV_LINK IS NOT NULL 
BEGIN

	EXEC DBO.GETRANDSTR 20, @BUFFER_SUBDIV OUT

	INSERT INTO @SUBDIV (LINK) 
	SELECT LINK FROM DBO.RN_VIEW_FILTER WHERE LINK_SELF = @FILTER_SUBDIV_LINK

END

/**********************************************************************************************************************/
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
DECLARE @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @NAME VARCHAR(100)

INSERT INTO DBO.BUFFER (ID, LINK)
SELECT @BUFFER_SUBDIV, LINK FROM @SUBDIV WHERE @BUFFER_SUBDIV IS NOT NULL

DECLARE @CNT INT
SET @CNT = CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@D2, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))

/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #P4_PART1(COL	INT, VAL NUMERIC(18,1), VAL_STR VARCHAR(20))

INSERT INTO #P4_PART1 (COL, VAL_STR)
SELECT TOP 1 1 AS COL, OKVED FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK

/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
ELSE	
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))

/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
ELSE
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
	
DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@D1, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

CREATE TABLE #EMPL1 (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL1
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@BDATE, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2		

/* ДОГОВОРНИКИ */
DECLARE @M NUMERIC(18,2) 

IF @CNT > 15
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @CNT > 15
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)

INSERT INTO #P4_PART1 (COL, VAL)
SELECT 4 AS COL, ROUND(@M/@NDAYSFEBR,0)

---- ВСЕГО (СУММА ГРАФ 2,3,4)
--INSERT INTO #P4_PART1
--SELECT 1 AS COL, SUM(VAL) FROM #P4_PART1 WHERE COL > 1

/* КОЛ-ВО ОТРАБОТ. ЧАСОВ */
DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

/*КОЛИЧЕСТВО ОТРАБОТАННЫХ ЧЕЛОВЕКО-ЧАСОВ С НАЧАЛА ГОДА РАБОТНИКАМИ СПИСОЧНОГО СОСТАВА*/
INSERT INTO #P4_PART1 (COL, VAL)
SELECT [STATUS],  DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOURS],@ISMINUTES)),@ISMINUTES)
FROM
(
	SELECT 
		[STATUS] = (CASE WHEN F.[STATUS] <> 3 THEN 5 ELSE 6 END),
		[HOURS] = DBO.SA_GET_EMPL_WH(LINK, DEFAULT,DEFAULT,PERIOD_BEG,PERIOD_END,DEFAULT,DEFAULT) 
	FROM 
		#EMPL1 F
) A
GROUP BY [STATUS]

-- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
delete FROM 
	#EMPL1 
WHERE
	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
	AND PERIOD_END not in (SELECT min(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

/* ФОНД НАЧИСЛ З/ПЛАТЫ */
CREATE  TABLE #P4_S_J_C (SUMMA NUMERIC(20,1), STAT_OTCHET TINYINT, DEP_TYPE TINYINT, COL TINYINT, PERIOD_END DATETIME)

DECLARE @LINKEKR213 INT
SELECT @LINKEKR213 = LINK FROM DBO.DICTIONARY_ITEM WHERE CODE = '213'

CREATE TABLE #CJ (PERS_LINK INT, LINK_EMPL INT, LINK_PAYS INT, PERIOD_END DATETIME, SUMMA NUMERIC(18,2), STAT_OTCHET TINYINT, WAY_CALC TINYINT, DEP_TYPE TINYINT)

INSERT INTO #CJ (PERS_LINK, LINK_EMPL, LINK_PAYS, PERIOD_END, SUMMA, STAT_OTCHET, WAY_CALC, DEP_TYPE)
SELECT 
	PERS_LINK, LINK_EMPL, LINK_PAYS, 
	CASE WHEN WAY_CALC <> 15 THEN JC.PERIOD_BEGIN ELSE JC.DATE_BEGIN END, 
	SUMMA, STAT_OTCHET, WAY_CALC,
	CASE WHEN PERS_LINK IS NULL THEN 0 ELSE 5 END /* 5 - ФИЗ ЛИЦО */
FROM
	DBO.CALCULATE_JURNAL JC 
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK 
WHERE
	P.[OBJECT] = 1 /* ТОЛЬКО НАЧИСЛЕНИЯ */
	AND (P.WAY_CALC <> 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1)
 		OR P.WAY_CALC = 15 AND YEAR(JC.DATE_BEGIN)=  YEAR(@D1) AND MONTH(JC.DATE_BEGIN) <= MONTH(@D1))	
	AND P.STAT_OTCHET <> 3
	AND JC.LINK_DEP = @DEP_LINK

----------- суммы договорников, которые являются сотрудниками помеячаем считать как для сотрудников
UPDATE J
SET LINK_EMPL = E.LINK, DEP_TYPE = 0
FROM #CJ J INNER JOIN #EMPL E ON E.PERS_LINK = J.PERS_LINK AND J.[PERIOD_END] BETWEEN E.PERIOD_BEG AND E.PERIOD_END
		
------------
INSERT INTO #P4_S_J_C 
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, COALESCE(F.COL,0), J.[PERIOD_END]
FROM #CJ J INNER JOIN (SELECT LINK, (CASE WHEN STATUS=3 THEN 9 ELSE 8 END) AS COL, PERIOD_BEG, PERIOD_END FROM #EMPL1) F 
		ON J.LINK_EMPL = F.LINK AND YEAR(J.[PERIOD_END]) * 100 + MONTH(J.[PERIOD_END]) 
				BETWEEN YEAR(F.PERIOD_BEG) * 100 + MONTH(F.PERIOD_BEG) AND YEAR(F.PERIOD_END) * 100 + MONTH(F.PERIOD_END)

------------		
INSERT INTO #P4_S_J_C
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, 0, PERIOD_END
FROM #CJ WHERE LINK_EMPL IS NULL


	/* COL8! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 8, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND  
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL9! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 9, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=9 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL10! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 10, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE STAT_OTCHET=1 AND DEP_TYPE=5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
	/* COL11! С НАЧАЛА ГОДА ЗА I КВАРТАЛ, I ПОЛУГОДИЕ, 9 МЕСЯЦЕВ, ГОД */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 11, SUM(SUMMA)/1000 FROM #P4_S_J_C
			WHERE STAT_OTCHET=2 -- СОЦВЫПЛАТЫ
				AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				--AND MONTH(@ENDDATE) % 3 = 0


/* РАЗД. 3 - ДВИЖЕНИЕ РАБОТНИКОВ */
	/* ROW 21 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 21, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE

	/* ROW 22 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 22, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE
				AND I.STAFF_LINK IN ( SELECT LINK_UP FROM STAFF WHERE DATE_BEGIN >= @DBYEAR)

	/* ROW 23 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 23, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE

	/* ROW 24 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 24, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND REASON IN (SELECT LINK FROM DICTIONARY_PUV WHERE CODE = '0402')
	
	/* ROW 26 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 26, COUNT(*) 
		FROM 
			DBO.ITEM_DIS_FACE I 
			INNER JOIN DBO.DICTIONARY_PUV DP ON DP.LINK = I.REASON
			LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
		WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND DP.CODE IN ('0300','0707','2030','2016','0000')
	
	/* ROW 27 */
	INSERT INTO #P4_PART1 (COL, VAL) 
	SELECT 27, @CNT

	--СВОБОДНЫЕ СТАВКИ
	INSERT INTO #P4_PART1 (COL, VAL)
	SELECT 28, SUM(S.FREE_STAKES)
	FROM DBO.DICTIONARY_STAFF_FN(@ENDDATE) S 
		INNER JOIN DBO.DICTIONARY_SUBDIVISION_FN(@ENDDATE) D ON D.LINK = S.SUBDIV_LINK
	WHERE 
		S.DELETED = 0 AND S.DEP_LINK = @DEP_LINK
		AND D.DELETED = 0
		AND (
				@BUFFER_SUBDIV IS NULL
				OR
				@BUFFER_SUBDIV IS NOT NULL AND S.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
			)				
--select * from #P4_PART1
DROP TABLE #P4_S_J_C

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
DECLARE @RESULT_TABLE VARCHAR(100)
EXEC DBO.X_GET_TABLE_NAME @RESULT_TABLE OUTPUT

EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0
EXEC ('SELECT * INTO ' + @RESULT_TABLE + ' FROM #P4_PART1 ')
EXEC DBO.BUFFERPUSH -151, @RESULT_TABLE
	SET @OUT_VAL = ''
DROP TABLE #P4_PART1
END





GO


GRANT EXECUTE ON dbo.[I_REPORT_FORMULA_P4_PREPARE] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_obiazn_zap]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_obiazn_zap]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_obiazn_zap]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
	declare @table varchar(100), @RunStr varchar(8000), @cCode VARCHAR(50), @vcDate VARCHAR(100), @vcResh VARCHAR(1000), @i INT, @vcI VARCHAR(10) 

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT * from ' + @table
	execute(@RunStr)
   
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT * from ' + @table
	execute(@RunStr)

	create table #table (COL1 varchar(8000), COL2 varchar(8000), DATE varchar(8000), COL6 varchar(8000), COL7 FLOAT, COL8 VARCHAR(8000), CODE varchar(50), DEL bit, orders int IDENTITY(1,1))   
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT COL1,COL2,RTRIM(COL3) + ''.'' + RTRIM(COL4) + ''.'' + RTRIM(COL5),COL6,COL7,COL8,CODE,DEL from ' + @table
	insert #table (COL1,COL2,DATE,COL6,COL7,COL8,CODE,DEL) execute(@RunStr)
   
   CREATE TABLE #res(COL1 VARCHAR(50), COL2 VARCHAR(1000))
   INSERT #res (COL1, COL2)
   SELECT DISTINCT COL1, COL2 FROM #table
   
   DECLARE cur CURSOR LOCAL STATIC FOR SELECT DISTINCT DATE, COL6 FROM #table WHERE Date <> '99.99.9999' AND COL6 <> '99999999' 
   
   OPEN cur
   
   FETCH NEXT FROM cur INTO @vcDate, @vcResh
   
   SET @i = 1
   SET @vcI = LTRIM(RTRIM(STR(@i)))
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
      SET @RunStr = 'ALTER TABLE #res ADD COL_D_' + @vcI + ' VARCHAR(100) ALTER TABLE #res ADD COL_R_' + @vcI + ' VARCHAR(100) ALTER TABLE #res ADD COL_S_' + @vcI + ' NUMERIC(20,2)'
      EXECUTE (@RunStr)

      SET @RunStr = 'UPDATE R ' + 
      'SET  COL_D_' + @vcI + ' = ''' + @vcDate + ''', ' +
           'COL_R_' + @vcI + ' = ''' + @vcResh + ''' ' + 
      'FROM #Res R'
      EXECUTE (@RunStr)    
      
      SET @RunStr = 'UPDATE R ' + 
      'SET COL_S_' + @vcI + ' = COL7 ' + 
      'FROM #Res R JOIN #table T ON R.COL1 = T.COL1 AND T.DATE = ''' + @vcDate + ''' AND T.COL6 = ''' + @vcResh + ''''
      EXECUTE (@RunStr)     

      SET @i = @i + 1
      SET @vcI = LTRIM(RTRIM(STR(@i)))
      
      FETCH NEXT FROM cur INTO @vcDate, @vcResh
   END

   ALTER TABLE #res ADD COL_ITOG NUMERIC(20,2)
   
   UPDATE R
   SET COL_ITOG = COL7
   FROM #RES R JOIN #table T ON R.COL1 = T.COL1 AND T.DATE = '99.99.9999' AND T.COL6 = '99999999'

   IF COL_LENGTH('tempdb..#res', 'COL_D_1') IS NULL
   BEGIN
      SET @RunStr = 'ALTER TABLE #res ADD COL_D_1 VARCHAR(100) ALTER TABLE #res ADD COL_R_1 VARCHAR(100) ALTER TABLE #res ADD COL_S_1 NUMERIC(20,2)'
      EXECUTE (@RunStr)
   END
   
   SELECT * FROM #res
   
   DROP TABLE #table
   DROP TABLE #res
   
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT * from ' + @table
	execute(@RunStr)
   
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT * from ' + @table
	execute(@RunStr)
   
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
	set @RunStr = 'SELECT * from ' + @table
	execute(@RunStr)               

GO
GRANT ALL ON dbo.[RO_PRINT_obiazn_zap] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
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_SAVE_REPORT_COLOUMNS]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[I_REPORT_SAVE_REPORT_COLOUMNS]
END

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   PROCEDURE dbo.I_REPORT_SAVE_REPORT_COLOUMNS
	@varKSintLINK	int	OUTPUT,
	@varKSpORDERS	tinyint = null,
	@varKSpNAME		varchar(250) = '',
	@varKSpLINK_TABLE	int	= null,
	@varKSpIsExported	tinyint = 0,
	@varKSpCol_Type	tinyint = 0,
	@varKSExport_Order	tinyint = 0,
	@varKScalc_orders	tinyint = 0,
	@varKSVal_Len	int = 0,
	@varKSIsEdited	tinyint = 0,
	@varKSDictionary varchar(100) = NULL,
	@varKSDictionary_Columns_List varchar(250) = NULL,
	@varKSDictionary_Fields_List varchar(250) = NULL,
	@input_mask varchar(200)=null,
	@property int=null,
	@str_property varchar(1000)=null,
   @varKScDictionary_Where varchar(1000) = null
AS


IF @varKSIsEdited = 0
	SET @varKScalc_orders = 0
IF isnull((select val_type from report_tables where link_table = @varKSpLINK_TABLE), 0) = 1
	SET @varKSIsEdited = 1

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT 5000 -- Время ожидания разблокировки ресурсов 5 сек.

DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int

BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.
	
	IF @varKSintLINK is null  OR @varKSintLINK = 0
	BEGIN
		INSERT INTO REPORT_COLOUMNS (Orders, Name, Link_Table, IsExported, Col_Type, Export_Order, calc_orders, Val_Len, IsEdited, Dictionary, Dictionary_Columns_List, Dictionary_Fields_List,input_mask,property,str_property, Dictionary_Where)
			VALUES (@varKSpORDERS, @varKSpNAME, @varKSpLINK_TABLE, @varKSpIsExported, @varKSpCol_Type, @varKSExport_Order, @varKScalc_orders, @varKSVal_Len, @varKSIsEdited, @varKSDictionary, @varKSDictionary_Columns_List, @varKSDictionary_Fields_List,@input_mask,@property,@str_property, @varKScDictionary_Where)
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
      	ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.

			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE REPORT_COLOUMNS
			SET Orders = @varKSpORDERS,
			    Name = @varKSpNAME,
			    Link_Table = @varKSpLINK_TABLE,
			    IsExported = @varKSpIsExported,
			    Col_Type = @varKSpCol_Type,
			    Export_Order = @varKSExport_Order,
			    calc_orders = @varKScalc_orders,
			    Val_Len = @varKSVal_Len,
			    IsEdited = @varKSIsEdited,
			    Dictionary = @varKSDictionary,
			    Dictionary_Columns_List = @varKSDictionary_Columns_List,
			    Dictionary_Fields_List = @varKSDictionary_Fields_List,
                input_mask=@input_mask,
                property=@property,
                str_property=@str_property,
             Dictionary_Where = @varKScDictionary_Where
		WHERE LINK_COL = @varKSintLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
      	ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.

			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
      	ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.

			RETURN 2
		END
	END

COMMIT TRAN
RETURN 0

GO
GRANT ALL ON dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] 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].[i_del_records_REPORT_SAVED_FORMS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[i_del_records_REPORT_SAVED_FORMS]
GO





/*
c Кейсистемс (Keysystems), 2005
*/

CREATE  PROCEDURE dbo.i_del_records_REPORT_SAVED_FORMS
		@varKSiLink	int
AS
if coalesce((select max(IsRO) from report_saved_forms where link_saved_form = @varKSiLink),0)>0 
	return -1

DECLARE @t_Org TABLE (Link_Org INT, Link_Budg INT)   
SET LOCK_TIMEOUT -1
SET IMPLICIT_TRANSACTIONS ON
DECLARE 
	@varKStrancount	int,
	@varKSRowCount	int,
	@varKSEventStr	varchar (200),
	@varKSLink_Task	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
BEGIN

	DECLARE @lcOrgEvent VARCHAR(60), @varKSLinkOrg INT, @iLinkBudg INT, @dBEGIN_DATE DATETIME, @iLINK_FORM INT, @tPERIOD_TYPE TINYINT, @vcAtrCode VARCHAR(254) 

	Select @varKSLinkOrg = LINK_ORGANIZATION, @iLinkBudg = link_type_svod, @dBEGIN_DATE = [Begin_Date], @iLINK_FORM = [Link_Form], @tPERIOD_TYPE = [Period_Type], @vcAtrCode = [atr_code]
	  FROM REPORT_SAVED_FORMS WHERE link_saved_form = @varKSiLink

	Set @lcOrgEvent = ''
	Select @lcOrgEvent = '; Организация: ' + LTRIM(RTRIM(CODE)) + ' ' + LTRIM(RTRIM(NAME)) + ';'
	From Departments Where link = @varKSLinkOrg

	select @varKSLink_Task = link_task from user_info
	select @varKSEventStr = 'Форма: ' + rtrim(code) + @lcOrgEvent + ' Период: ' + 
		(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 = @varKSiLink

--	DELETE FROM REPORT_SAVED_FORMS
--		WHERE Link_Saved_form = @varKSiLink
   UPDATE dbo.report_saved_forms 
   SET del = 1, modify_date = GETDATE()
   WHERE Link_Saved_form = @varKSiLink
   
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 1
	END
	
	exec RO_GENERATEEVENT 'Удаление сохраненного отчета', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSiLink

END

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

SET IMPLICIT_TRANSACTIONS OFF   
IF ISNULL((SELECT val_int FROM dbo.[REPORT_OPTIONS] ro WHERE razdel = 'COMMON' AND Code = 'RETURN_STATUS'), 0) = 1
   AND NOT EXISTS(SELECT * 
                  FROM dbo.[REPORT_SAVED_FORMS] rsf 
                  WHERE rsf.[Link_Form] = @iLINK_FORM 
                        AND rsf.[Link_Organization] = @varKSLinkOrg 
                        AND isnull(rsf.[Link_Type_Svod], 0) = ISNULL(@iLinkBudg, 0)
                        AND rsf.[Begin_Date] = @dBEGIN_DATE
                        AND rsf.[Period_Type] = @tPERIOD_TYPE
                        AND rsf.[atr_code] = @vcAtrCode AND rsf.del = 0) 
BEGIN
    -- вернуть предыдущие статусы подведомственных организаций
   INSERT @t_Org (link_org, link_budg)
   SELECT link_report_org, link_report_budg
   FROM dbo.[REPORT_SVOD_TREE] rst
   WHERE link_self IN (SELECT Link
                        FROM dbo.report_svod_tree 
                       WHERE  link_report_org = @varKSLinkOrg 
                              AND ISNULL([LINK_REPORT_BUDG],0) = isnull(@iLinkBudg, 0) 
                              AND [Link_History] = dbo.[RO_SVOD_TREE_Link_History](@dBEGIN_DATE))
    
   UPDATE RSF
   SET [IsRO] = [IsRO_Set]
   FROM dbo.report_saved_forms RSF
   WHERE rsf.begin_date = @dBEGIN_DATE AND rsf.Link_Form = @iLINK_FORM
         AND rsf.Period_Type = @tPERIOD_TYPE AND rsf.atr_code = @vcAtrCode
         AND EXISTS(SELECT * FROM @t_Org O WHERE O.[Link_Org] = RSF.Link_Organization AND isnull(O.[Link_Budg], 0) = ISNULL(RSF.Link_Type_Svod,0))

END 

-- удалить отчеты из корзины, если превышена норма
DECLARE @CountReport INT, @cStr VARCHAR(254), @modify_date DATETIME, @nvExecStr NVARCHAR(1000)  

exec dbo.X_GET_OPTION 'REPORT_ORTION_RECYCLE_COUNT', 0, @cStr OUTPUT

SET @CountReport = CONVERT(INT, @cStr)

IF ISNULL((SELECT COUNT(*) FROM dbo.report_saved_forms WHERE del = 1), 0) > @CountReport
BEGIN
   set @nvExecStr = 'SELECT top ' + LTRIM(STR(@CountReport)) + ' @modify_date = modify_date FROM dbo.report_saved_forms WHERE del = 1 ORDER BY MODIFY_date desc'
   
   EXEC sp_executesql @nvExecStr, N'@modify_date datetime output', @modify_date = @modify_date OUTPUT
    
   DELETE dbo.[REPORT_SAVED_FORMS]
   WHERE del = 1 AND modify_date < @modify_date 
END	
  
RETURN 0








GO
GRANT ALL ON [i_del_records_REPORT_SAVED_FORMS] 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.[XD_DEP_KBK_PROC]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.XD_DEP_KBK_PROC

GO


CREATE	PROCEDURE XD_DEP_KBK_PROC @iDepLink int
AS
SELECT	CHECKED = convert(bit, 0),
		LINK = K.LINK, 
		KBK_LINK = K.LINK, 
		KBK_CODE = K.code, 
		KBK_NAME = K.Name, 
		USED_ALL   = K.USED_ALL,
		OSN		   = isnull(DKBK.OSN,0),
		DKBK.DEP_LINK

FROM BI_DICTION_KBK K 
left join dbo.DEPARTMENT_KBK DKBK on DKBK.KBK_LINK = K.LINK and DKBK.DEP_LINK = @iDepLink
where USED_ALL = 1 or DKBK.DEP_LINK is not null

return 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REP_SVOD1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_SVOD1]

GO

CREATE   PROCEDURE [dbo].[SD_REP_SVOD1]
	@varKSstart_date DATETIME, 
 	@varKSEND_DATE DATETIME,	
	@varKScVal1 char(1), @varKSnOtborLink1 int,		
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@varKScVal3 char(1), @varKSnOtborLink3 int,
	@CVAL4 CHAR(1), @NOTBORLINK4 INT	/* ОТБОР КАТЕГОРИЙ ДОЛЖНОСТЕЙ */,
	@Sort1 tinyint, @Sort2 tinyint,
	@ALL_DEP tinyint = NULL,
	@nCheck1 int = 1	/* Показывать начисления */,
	@nCheck2 int = 1	/* Показывать удержания */,
	@nCheck3 int = 1	/* Показывать отчисления */,
	@detailed_SFIN int = 0	/* Детализация по источникам финансирования */,
	@detailed_EKR int = 0	/* Детализация по ЭКР */,
	@AS_SALARY TINYINT = 0 /*Рассчитывать как ведомость на выплату*/	
AS
BEGIN

	--DECLARE @AS_SALARY TINYINT
	--SET @AS_SALARY = 0

	SET @Sort1 = COALESCE(@Sort1,0)
	SET @Sort2 = COALESCE(@Sort2,0)
	SET @ALL_DEP = COALESCE(@ALL_DEP,0)

	DECLARE @varKSSTART_YEAR DATETIME
	SELECT @varKSSTART_YEAR = dbo.DateBeginOfYear(@varKSstart_date)


	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	EXEC BufferClear
	DECLARE @varKSVKR_ID VARCHAR(100), @varKScWhere VARCHAR(1000)
	IF LEN(@varKScVal2) = 0 BEGIN
		SET @varKSVKR_ID = NULL
	END	 
	ELSE BEGIN
		SET @varKSVKR_ID = 'SALARY_SVOD1_VKR'
		SET @varKScWhere = 'LINK_UP = ' + STR(@varKSnOtborLink2)
		EXEC BufferPushTable 'OBJECT_VAR_SAL_SFIN', @varKSVKR_ID, 'RECORD', @varKScWhere
	END

	---
	create table #otbor_ekr (link int)
	insert into #otbor_ekr (link)
	select RECORD from dbo.OBJECT_VAR_KOSGU WHERE LEN(@varKScVal3) = 0 OR LINK_UP = @varKSnOtborLink3

	---
	DECLARE @varKSnYear INT
	SET @varKSnYear = YEAR(@varKSSTART_YEAR)

	CREATE TABLE #varKSEMPLS (LINK_EMPL INT)
	CREATE TABLE #varKSEMPLS1 (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT)
	CREATE TABLE #varKSEMPLS2 (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT)
	
	IF LEN(@varKScVal1) <> 0 
		INSERT INTO #varKSEMPLS (LINK_EMPL)
		SELECT DISTINCT RECORD 
		FROM
			dbo.OBJECT_VAR_EMPL A 
			LEFT JOIN DBO.SA_EMPLS_INFO(@varKSEND_DATE, DEFAULT) K ON K.empl_link = A.RECORD
		WHERE 
			LINK_UP = @varKSnOtborLink1
			AND
			(	
				LEN(@CVAL4) = 0 
				OR 
				K.KAT_LINK IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
			)
	ELSE
		INSERT INTO #varKSEMPLS (LINK_EMPL)
		SELECT DISTINCT E.LINK
		FROM 
			dbo.EMPL E 
			LEFT JOIN DBO.SA_EMPLS_INFO(@varKSEND_DATE, DEFAULT) K ON K.empl_link = E.LINK
		WHERE 
			((DEP_LINK = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
			AND
			(	
				LEN(@CVAL4) = 0 
				OR 
				K.KAT_LINK IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
			)		

	CREATE CLUSTERED INDEX #varKSEMPLS_INDEX1 ON #varKSEMPLS (LINK_EMPL)
	---

	--	
	DECLARE @varKSDATE_01 DATETIME
	SET @varKSDATE_01 = DATEADD(DAY, -1, @varKSstart_date)

	--Временная рамка с начала года
	DECLARE @DATE_BEG DATETIME, @DATE_END DATETIME, @DATE_BEG_PREV_YEAR DATETIME
	SET @DATE_BEG = CASE WHEN @varKSSTART_YEAR < @varKSstart_date THEN @varKSSTART_YEAR ELSE @varKSstart_date END
	SET @DATE_END = (CASE WHEN @varKSDATE_01 > @varKSEND_DATE THEN @varKSDATE_01 ELSE @varKSEND_DATE END)
	SET @DATE_BEG_PREV_YEAR = dbo.DateBeginOfYear(@varKSSTART_YEAR-1)

	--Ведомости на выплату зарплаты
	CREATE TABLE #VEDOM_ZP (LINK INT)
	
	INSERT INTO #VEDOM_ZP (LINK)
	SELECT 
		D.LINK 
	FROM 
		dbo.SDOC D 
		INNER JOIN dbo.SDOC_VEDOM V ON V.LINK_UP = D.LINK 
	WHERE 
		LINK_DEP = @DEP_LINK
		AND @AS_SALARY = 1 
		AND TYP_PAYMENT = 1
		AND D.DATE_CALC BETWEEN @DATE_BEG_PREV_YEAR AND @DATE_END

	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	
	DECLARE @LINK_EKR_211 INT, @LINK_EKR_212 INT, @LINK_EKR_213 INT
	SET @LINK_EKR_211 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
	SET @LINK_EKR_212 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
	SET @LINK_EKR_213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

	--Кусок журнала операций
	CREATE TABLE #SJC (LINK_EMPL INT, LINK_PAYS INT, SNAME VARCHAR(15), [NAME] VARCHAR(100), TYP_OPER TINYINT, WAY_CALC TINYINT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2), PERIOD_BEGIN DATETIME, PERIOD_END DATETIME, LINK_DEP INT, [DAYS] INT)
	INSERT INTO #SJC 
		(LINK_EMPL, LINK_PAYS, SNAME, [NAME], TYP_OPER, WAY_CALC, LINK_VKR, LINK_EKR, summa, PERIOD_BEGIN, PERIOD_END, LINK_DEP, [DAYS])
	SELECT 
		SJC.LINK_EMPL,  SJC.LINK_PAYS, 
		P.SNAME, P.[NAME] + CASE WHEN ISNULL(A.LINK,0) > 0 AND (YEAR(PERIOD_BEGIN)* 100 + MONTH(PERIOD_BEGIN)) <> (YEAR(DATE_BEGIN)* 100 + MONTH(DATE_BEGIN)) THEN ' (в. ' + CONVERT(VARCHAR(4),YEAR(PERIOD_BEGIN)) + '/' +  + RIGHT(CONVERT(VARCHAR(3),100 + MONTH(PERIOD_BEGIN)),2) + ' за ' + CONVERT(VARCHAR(4),YEAR(DATE_BEGIN)) + '/' +  + RIGHT(CONVERT(VARCHAR(3),100 + MONTH(DATE_BEGIN)),2) + ')' ELSE '' END, 
		P.[OBJECT], P.WAY_CALC, 
		SJC.LINK_VKR, 
		--ISNULL(SJC.LINK_EKR,P.LINK_EKR), 
		CASE WHEN P.[OBJECT] = 3 THEN 
				CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
					CASE WHEN COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) = @LINK_EKR_211 THEN @LINK_EKR_213 ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) END
				ELSE 
					CASE WHEN COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) IN (@LINK_EKR_211, @LINK_EKR_212) THEN @LINK_EKR_213 ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) END				
				END
			ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR)
		END,	
		SJC.summa, 
		CASE WHEN COALESCE(A.LINK,0) = 0 THEN SJC.PERIOD_BEGIN ELSE (CASE WHEN SJC.DATE_BEGIN < SJC.PERIOD_BEGIN THEN SJC.DATE_BEGIN ELSE SJC.PERIOD_BEGIN END) END, 
		CASE WHEN COALESCE(A.LINK,0) = 0 THEN SJC.PERIOD_END ELSE (CASE WHEN SJC.DATE_END < SJC.PERIOD_END THEN SJC.DATE_END ELSE SJC.PERIOD_END END) END, 
		SJC.LINK_DEP, SJC.[DAYS]
	FROM
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL SJC ON SJC.LINK_PAYS = P.LINK
		LEFT JOIN #VEDOM_ZP A ON A.LINK = SJC.LINK_DOC
	WHERE
		((SJC.LINK_DEP = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
		AND -- отбор по источникам
		(
			@varKSVKR_ID IS NULL
			OR SJC.LINK_VKR IN (SELECT LINK FROM dbo.BufferGetTableByID(@varKSVKR_ID))
		)
		AND -- отбор по статьям
		( LEN(@varKScVal3) = 0 OR SJC.LINK_EKR IN (SELECT LINK FROM #otbor_ekr))
		AND
		(

			(
			--P.[OBJECT] = 2 AND COALESCE(A.LINK,0) = 0 AND YEAR(SJC.PERIOD_BEGIN) = YEAR(SJC.DATE_BEGIN) AND SJC.PERIOD_BEGIN >= @DATE_BEG AND SJC.PERIOD_END <= @DATE_END
			-- удержания. так красивей, но с остатком не стыкуется
			--всё, кроме выплаты зарплаты берем только по дате расчёта
			NOT (P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0) AND SJC.PERIOD_BEGIN >= @DATE_BEG AND SJC.PERIOD_END <= @DATE_END			
			OR 
			--удержания. ДЛЯ ВЕДОМОСТЕЙ ОПЕРАЦИИ БЕРЕМ ПО ПЕРИОДУ РАСЧЕТА
			P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0 AND (SJC.DATE_BEGIN >= @DATE_BEG AND SJC.DATE_BEGIN <= @DATE_END)
			)
		OR
			(	
				P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0
				AND
				YEAR(SJC.DATE_BEGIN) = YEAR(@DATE_BEG)-1 --Выплаты зарплаты за прошлый год, сделанные в этом году
				AND 
				YEAR(SJC.PERIOD_BEGIN) = YEAR(@DATE_BEG) AND MONTH(SJC.PERIOD_BEGIN) <= MONTH(@DATE_BEG)			
			)
		)	

	--
	CREATE CLUSTERED INDEX #SJC_INDEX1 ON #SJC (LINK_EMPL)	

	--
	CREATE TABLE #T1( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	--Начисленно и удержано с начала года до тек. месяца
	INSERT INTO #T1
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSSTART_YEAR 
		AND SJC.PERIOD_END <= @varKSDATE_01
		AND SJC.TYP_OPER IN (1,2)
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		SJC.TYP_OPER, SJC.WAY_CALC
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	INSERT INTO #T1
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T1 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------
	CREATE TABLE #T2( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	--Начисленно и удержано с начала года по тек. месяц
	INSERT INTO #T2
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSSTART_YEAR
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND SJC.TYP_OPER IN (1,2)
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END),		
		SJC.TYP_OPER, SJC.WAY_CALC
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0		
	
	INSERT INTO #T2
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T2 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------
	CREATE TABLE #T3( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	----Все операции тек месяца
	INSERT INTO #T3 
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 	
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END),
		SJC.TYP_OPER, SJC.WAY_CALC
	
	INSERT INTO #T3
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T3 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------ Информация об остатках ----------------------------------
	CREATE TABLE #SAL_REMAIN (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT, SUMMA NUMERIC(18,2), NDFL NUMERIC(18,2) )

	INSERT INTO #SAL_REMAIN (LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA, NDFL)
	SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUM(SUMMA), SUM(NDFL)
	FROM
	( 
		SELECT 
			SR.LINK_EMPL, 
			LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SR.LINK_VKR ELSE 0 END), 
			LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SR.LINK_EKR ELSE 0 END),		
			SUMMA = SR.SUMMA, 
			NDFL = SR.NDFL
		FROM 
			dbo.SAL_REMAIN SR INNER JOIN #varKSEMPLS E ON SR.LINK_EMPL = E.LINK_EMPL
		WHERE 
			YEAR_SAL = @varKSnYear 
			AND (@varKSVKR_ID IS NULL OR LINK_VKR IN (SELECT LINK FROM dbo.BufferGetTableByID(@varKSVKR_ID) ))
			AND ( LEN(@varKScVal3) = 0 OR SR.LINK_EKR IN (SELECT LINK FROM #otbor_ekr))
		
		--Выплаты за прошлый год на погашение остатка прошлого года
		UNION ALL
		SELECT 
			SJC.LINK_EMPL, 
			LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
			LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 	
			-SUMMA,
			NDFL = 0
		FROM 
			#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
		WHERE
			@AS_SALARY = 1
			AND 
			YEAR(SJC.PERIOD_BEGIN) = YEAR(@DATE_BEG_PREV_YEAR)
	) T	
	GROUP BY 
		LINK_EMPL, LINK_VKR, LINK_EKR
	HAVING
		SUM(SUMMA) <> 0 OR SUM(NDFL) <> 0	


	-----------------------
	DECLARE @varKSCNT_N INT, @varKSCNT_U INT, @varKSCNT_O INT
	
	--
	CREATE TABLE #TMP_N (LINK_DEP1 INT, LINK_EMPL1 INT, NN VARCHAR(30), SN NUMERIC(20,2), LINK_VKR_N INT, LINK_EKR_N INT, way_calc tinyint, p tinyint )
	
	INSERT INTO #TMP_N 
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, SJC.SNAME, SUMMA, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		SJC.way_calc, 0
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.TYP_OPER = 1 
		AND SJC.PERIOD_BEGIN >= @varKSstart_date AND SJC.PERIOD_END <= @varKSEND_DATE
		AND @nCheck1 = 1
				
	--UNION ALL
	/*Для вывода дней больничных в своде по организациям ЦБ*/
	--SELECT 
	--	SJC.LINK_DEP, SJC.LINK_EMPL, SJC.SNAME, [DAYS], 
	--	LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
	--	LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
	--	SJC.way_calc, 1
	--FROM 
	--	#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	--WHERE 
	--		SJC.TYP_OPER = 1 and SJC.way_calc in (13,20)
	--	AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
	--	AND @nCheck1 = 1		

	SET @varKSCNT_N = (SELECT COUNT(DISTINCT NN) FROM #TMP_N )

	------
	--UPDATE #TMP_N
	--SET  
	--	NN = rtrim(ltrim(NN))
	--	+ (CASE WHEN p=1 THEN ' Дни' ELSE '' END)
	--WHERE 
	--	LINK_EKR_N is not null and way_calc in (13,20) AND @ALL_DEP = 1
	------

	CREATE TABLE #TMP_U (LINK_DEP2 INT, LINK_EMPL2 INT, NU VARCHAR(254), SU NUMERIC(20,2), LINK_VKR_U INT, LINK_EKR_U INT)
	INSERT INTO #TMP_U
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, SJC.[NAME], SJC.SUMMA,
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END)		
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			TYP_OPER = 2
		AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
		AND @nCheck2 = 1
		AND SJC.SUMMA <> 0
	
	SET @varKSCNT_U = (SELECT COUNT(DISTINCT NU) FROM #TMP_U )
	------
	
	CREATE TABLE #TMP_O (LINK_DEP3 INT, LINK_EMPL3 INT, NNO VARCHAR(254), SO NUMERIC(20,2), LINK_VKR_O INT, LINK_EKR_O INT)
	INSERT INTO #TMP_O 
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, SJC.[NAME], SJC.SUMMA,
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			TYP_OPER = 3
		AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
		AND @nCheck3 = 1
		AND SJC.SUMMA <> 0		

	SET @varKSCNT_O = (SELECT COUNT(DISTINCT NNO) FROM #TMP_O )

	INSERT INTO #varKSEMPLS2
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #T1 WHERE WAY_CALC = 0 AND LINK_EMPL IS NOT NULL AND SUMMA <> 0 
	UNION
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #T2 WHERE WAY_CALC = 0 AND LINK_EMPL IS NOT NULL AND SUMMA <> 0
	UNION
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #SAL_REMAIN WHERE (SUMMA <> 0 OR NDFL <> 0)
	UNION
	SELECT DISTINCT LINK_EMPL1, LINK_VKR_N, LINK_EKR_N FROM #TMP_N WHERE SN <> 0
	UNION
	SELECT DISTINCT LINK_EMPL2, LINK_VKR_U, LINK_EKR_U FROM #TMP_U WHERE SU <> 0
	UNION
	SELECT DISTINCT LINK_EMPL3, LINK_VKR_O, LINK_EKR_O FROM #TMP_O WHERE SO <> 0

	--
	CREATE INDEX #varKSEMPLS2_INDEX1 ON #varKSEMPLS2 (LINK_EMPL, LINK_VKR, LINK_EKR)	

	------------------------------------------------------------------------------
	CREATE TABLE #REST_B1(
		LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT,
		BEG_PAY NUMERIC(20,2), BEG_TAX NUMERIC(20,2), 
		BEG_R NUMERIC(20,2), BEG_NDFL NUMERIC(20),
		END_PAY NUMERIC(20,2), END_TAX NUMERIC(20,2),	
		CURR_PAY NUMERIC(20,2), CURR_TAX NUMERIC(20,2),	
		[CURR_DED] NUMERIC(20,2)
	)

	INSERT INTO #REST_B1
	SELECT 
		DF.LINK_EMPL, DF.LINK_VKR, DF.LINK_EKR,
		 
		[BEG_PAY] = ISNULL(T11.SUMMA, 0.00), --Начисленно до тек. месяца
		[BEG_TAX] = ISNULL(T12.SUMMA, 0.00), --Удержано до тек. месяца

		[BEG_R] = ISNULL(DSR.SUMMA, 0.00), --Остаток на нач. года начисления
		[BEG_NDFL] = ISNULL(DSR.NDFL, 0.00), --Переплата на нач. года удержания

		[END_PAY] = ISNULL(T21.SUMMA, 0.00), --Нач. с нач. года по тек месяц
		[END_TAX] = ISNULL(T22.SUMMA, 0.00), --Удерж. с нач. года по тек месяц
		
		[CURR_PAY] = ISNULL(T31.SUMMA, 0.00), --Начисленно в тек месяце
		[CURR_TAX] = ISNULL(T32.SUMMA, 0.00),  --Удержано в тек месяце
		[CURR_DED] = ISNULL(T33.SUMMA, 0.00) --Отч. в тек месяце

	FROM 
		#varKSEMPLS2 DF
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T1 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T11 ON DF.LINK_EMPL = T11.LINK_EMPL AND DF.LINK_VKR = T11.LINK_VKR AND DF.LINK_EKR = T11.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T1 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T12 ON DF.LINK_EMPL = T12.LINK_EMPL AND DF.LINK_VKR = T12.LINK_VKR AND DF.LINK_EKR = T12.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA), NDFL = SUM(NDFL) FROM #SAL_REMAIN GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) DSR ON DF.LINK_EMPL = DSR.LINK_EMPL AND DF.LINK_VKR = DSR.LINK_VKR AND DF.LINK_EKR = DSR.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T2 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T21 ON DF.LINK_EMPL = T21.LINK_EMPL AND DF.LINK_VKR = T21.LINK_VKR AND DF.LINK_EKR = T21.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T2 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T22 ON DF.LINK_EMPL = T22.LINK_EMPL AND DF.LINK_VKR = T22.LINK_VKR AND DF.LINK_EKR = T22.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T31 ON DF.LINK_EMPL = T31.LINK_EMPL AND DF.LINK_VKR = T31.LINK_VKR AND DF.LINK_EKR = T31.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T32 ON DF.LINK_EMPL = T32.LINK_EMPL AND DF.LINK_VKR = T32.LINK_VKR AND DF.LINK_EKR = T32.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 3 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T33 ON DF.LINK_EMPL = T33.LINK_EMPL AND DF.LINK_VKR = T33.LINK_VKR AND DF.LINK_EKR = T33.LINK_EKR

	CREATE TABLE #REST_B(
		LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT, 
		REST_BEG NUMERIC(20,2), 
		REST_D NUMERIC(20,2),
		CURR_PAY NUMERIC(20,2), CURR_TAX NUMERIC(20,2),	
		[CURR_DED] NUMERIC(20,2)
	)
	
	INSERT INTO #REST_B
	SELECT 
		LINK_EMPL, LINK_VKR, LINK_EKR, 
		BEG_PAY - BEG_TAX + BEG_R AS REST_BEG, --сальдо на начало мес
		END_PAY - END_TAX + BEG_R AS REST_D, --сальдо на конец мес
		CURR_PAY, 
		CURR_TAX,
		CURR_DED
	FROM 
		#REST_B1
	WHERE 
		(BEG_PAY - BEG_TAX + BEG_R) <> 0
		OR (END_PAY - END_TAX + BEG_R) <> 0
		OR CURR_PAY <> 0
		OR CURR_TAX <> 0
		OR CURR_DED <> 0


	INSERT INTO #varKSEMPLS1
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #REST_B
	UNION
	SELECT DISTINCT LINK_EMPL1, LINK_VKR_N, LINK_EKR_N FROM #TMP_N WHERE SN <> 0
	UNION
	SELECT DISTINCT LINK_EMPL2, LINK_VKR_U, LINK_EKR_U FROM #TMP_U WHERE SU <> 0
	UNION
	SELECT DISTINCT LINK_EMPL3, LINK_VKR_O, LINK_EKR_O FROM #TMP_O WHERE SO <> 0

	--
	CREATE CLUSTERED INDEX #varKSEMPLS1_INDEX1 ON #varKSEMPLS1 (LINK_EMPL, LINK_VKR, LINK_EKR)	


	CREATE TABLE #RES0
	(
		LINK_DEP INT,
		LINK_EMPL INT,
		LINK_VKR INT,
		LINK_EKR INT, 
		SVD_TN VARCHAR(15), 
		SVD_FIO VARCHAR(254),
		SVD_PODR VARCHAR(254),
		SUBDIV_CODE VARCHAR(10),
		S_SN NUMERIC(20,2), S_SU NUMERIC(20,2), S_SO NUMERIC(20,2),
		SVD_Saldo NUMERIC(20,2), REST_END NUMERIC(20,2),
		POST_CODE VARCHAR(10),
		POST_NAME VARCHAR(254)
	)
	INSERT INTO #RES0
	SELECT 
		EP.DEP_LINK,
		[LINK_EMPL] = EP.LINK,
		E.LINK_VKR, 
		E.LINK_EKR,
		[TN] 		= EP.TAB,
		[FIO] 		= dbo.ku_GetPersFio(EP.PERS_LINK),
		[SUBDIV] 	= EP.SUBDIV_NAME,
		[SUBDIV_CODE] = EP.SUBDIV_CODE,
		[CURR_PAY] = ISNULL(RB.CURR_PAY, 0.00),
		[CURR_TAX] = ISNULL(RB.CURR_TAX, 0.00),
		[S_SO] = ISNULL(RB.CURR_DED, 0.00),
		[SVD_Saldo] = ISNULL(RB.REST_BEG, 0.00),
		[REST_END] = ISNULL(RB.REST_D, 0.00),
		POST_CODE, POST_NAME 
	FROM 
		DBO.KU_EMPL_PLACING EP 
		INNER JOIN #varKSEMPLS1 E ON EP.LINK = E.LINK_EMPL
		LEFT OUTER JOIN #REST_B RB ON EP.LINK = RB.LINK_EMPL AND RB.LINK_VKR = E.LINK_VKR AND RB.LINK_EKR = E.LINK_EKR
	WHERE
		((EP.DEP_LINK = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
	
	DECLARE 
		@varKSTABLE_PAY VARCHAR(120), @varKSTABLE_TAX VARCHAR(120), @varKSTABLE_DED VARCHAR(120), 
		@varKSTABLE_OUT VARCHAR(120), @varKSTABLE_OUT2 VARCHAR(120)
	EXEC X_GET_TABLE_NAME @varKSTABLE_PAY OUTPUT
	SELECT @varKSTABLE_TAX = @varKSTABLE_PAY + '_1', @varKSTABLE_OUT = @varKSTABLE_PAY + '_2', 
		@varKSTABLE_OUT2 = @varKSTABLE_PAY + '_3',
		@varKSTABLE_DED = @varKSTABLE_PAY + '_4'

	IF @ALL_DEP = 0 BEGIN
		EXEC M_CROSS_TABLE
			'LINK_EMPL1, LINK_VKR_N, LINK_EKR_N',
			'NN', 'VARCHAR(254)',
			'SN', 'NUMERIC(20,2)', 'SUM(SN) AS SN',
			'#TMP_N', @varKSTABLE_PAY

		EXEC M_CROSS_TABLE
			'LINK_EMPL2, LINK_VKR_U, LINK_EKR_U',
			'NU', 'VARCHAR(254)',
			'SU', 'NUMERIC(20,2)', 'SUM(SU) AS SU',
			'#TMP_U', @varKSTABLE_TAX
	
		EXEC M_CROSS_TABLE
			'LINK_EMPL3, LINK_VKR_O, LINK_EKR_O',
			'NNO', 'VARCHAR(254)',
			'SO', 'NUMERIC(20,2)', 'SUM(SO) AS SO',
			'#TMP_O', @varKSTABLE_DED
		
		EXEC ( '
		SELECT  T1.*, ISNULL(F.CODE,''Все'') AS SFIN_CODE, ISNULL(G.CODE,''Все'') AS EKR_CODE, T2.*, T3.*, T4.* INTO ' + @varKSTABLE_OUT2 + ' 
		FROM 
			#RES0 T1
			LEFT JOIN DBO.SAL_SFIN F ON F.LINK = T1.LINK_VKR
			LEFT JOIN DBO.KOSGU G ON G.LINK = T1.LINK_EKR
			LEFT OUTER JOIN ' + @varKSTABLE_PAY + ' T2 ON T1.LINK_EMPL = T2.LINK_EMPL1 AND T1.LINK_VKR = T2.LINK_VKR_N AND T1.LINK_EKR = T2.LINK_EKR_N
			LEFT OUTER JOIN ' + @varKSTABLE_TAX + ' T3 ON T1.LINK_EMPL = T3.LINK_EMPL2 AND T1.LINK_VKR = T3.LINK_VKR_U AND T1.LINK_EKR = T3.LINK_EKR_U
			LEFT OUTER JOIN ' + @varKSTABLE_DED + ' T4 ON T1.LINK_EMPL = T4.LINK_EMPL3 AND T1.LINK_VKR = T4.LINK_VKR_O AND T1.LINK_EKR = T4.LINK_EKR_O
		')
		
	END
	ELSE BEGIN

		EXEC M_CROSS_TABLE
			'LINK_DEP1, LINK_VKR_N, LINK_EKR_N',
			'NN', 'VARCHAR(30)',
			'SN', 'NUMERIC(20,2)', 'SUM(SN) AS SN',
			'#TMP_N', @varKSTABLE_PAY

		EXEC M_CROSS_TABLE
			'LINK_DEP2, LINK_VKR_U, LINK_EKR_U',
			'NU', 'VARCHAR(254)',
			'SU', 'NUMERIC(20,2)', 'SUM(SU) AS SU',
			'#TMP_U', @varKSTABLE_TAX
	
		EXEC M_CROSS_TABLE
			'LINK_DEP3, LINK_VKR_O, LINK_EKR_O',
			'NNO', 'VARCHAR(254)',
			'SO', 'NUMERIC(20,2)', 'SUM(SO) AS SO',
			'#TMP_O', @varKSTABLE_DED

		EXEC ( '
		SELECT  T1.*,  ISNULL(F.CODE,''Все'') AS SFIN_CODE, ISNULL(G.CODE,''Все'') AS EKR_CODE, T2.*, T3.*, T4.* INTO ' + @varKSTABLE_OUT2 + ' 
		FROM 
			(Select LINK_DEP, LINK_VKR, LINK_EKR, S_SN= SUM(S_SN), S_SU= SUM(S_SU), S_SO= SUM(S_SO), SVD_Saldo= SUM(SVD_Saldo), REST_END= SUM(REST_END) FROM #RES0 GROUP BY LINK_DEP, LINK_VKR, LINK_EKR) T1 
		LEFT JOIN DBO.SAL_SFIN F ON F.LINK = T1.LINK_VKR
		LEFT JOIN DBO.KOSGU G ON G.LINK = T1.LINK_EKR			
		LEFT OUTER JOIN ' + @varKSTABLE_PAY + ' T2 ON T1.LINK_DEP = T2.LINK_DEP1 AND T1.LINK_VKR = T2.LINK_VKR_N AND T1.LINK_EKR = T2.LINK_EKR_N
		LEFT OUTER JOIN ' + @varKSTABLE_TAX + ' T3 ON T1.LINK_DEP = T3.LINK_DEP2 AND T1.LINK_VKR = T3.LINK_VKR_U AND T1.LINK_EKR = T3.LINK_EKR_U
		LEFT OUTER JOIN ' + @varKSTABLE_DED + ' T4 ON T1.LINK_DEP = T4.LINK_DEP3 AND T1.LINK_VKR = T4.LINK_VKR_O AND T1.LINK_EKR = T4.LINK_EKR_O
		')

	END

	DECLARE @varKSSQL_STR VARCHAR(4000), @varKSFIELD_NAME VARCHAR(100), @varKSI int
	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_N BEGIN
		SET @varKSFIELD_NAME= 'NN_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_PAY 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SN_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_N=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NN_0 VARCHAR(254), SN_0 NUMERIC(20,2) ')
	END
		

	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_U BEGIN
		SET @varKSFIELD_NAME= 'NU_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_TAX 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SU_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_U=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NU_0 VARCHAR(254), SU_0 NUMERIC(20,2) ')
	END

	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_O BEGIN
		SET @varKSFIELD_NAME= 'NNO_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_DED 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SO_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_O=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NNO_1 VARCHAR(254) DEFAULT '''', SO_1 NUMERIC(20, 2) DEFAULT 0')
	END

	DECLARE @SCRIPT varchar(1000)

	IF @ALL_DEP = 0 begin

		set @SCRIPT = 'SELECT * FROM ' + @varKSTABLE_OUT2 + ' 
		ORDER BY ' + 
			LTRIM(RTRIM(CASE @Sort1 
				WHEN 1 THEN 'SUBDIV_CODE'
				WHEN 2 THEN 'SVD_PODR'
				WHEN 3 THEN 'SVD_TN' 
				WHEN 4 THEN 'SVD_FIO'
				ELSE ''
			END)) + 

			LTRIM(RTRIM(CASE @Sort2 
				WHEN 2 THEN (CASE WHEN @Sort1 <> 3 THEN ',SVD_TN' ELSE '' END)
				WHEN 3 THEN (CASE WHEN @Sort1 <> 4 THEN ',SVD_FIO' ELSE '' END)
				ELSE ''
			END))
			
			+ ',SFIN_CODE, EKR_CODE'

		EXEC (@SCRIPT)
	end
	ELSE
		EXEC (
		' SELECT DISTINCT R.*, DEP_NAME= D.[NAME], GRP_NAME = COALESCE(GRP.GRP_NAME,''Без группы'')  FROM ' + @varKSTABLE_OUT2+' R '
		+ ' INNER JOIN DEPARTMENTS D on R.LINK_DEP = D.LINK
		LEFT JOIN (select GRP_NAME= G.[NAME], D_LINK= REF.DEP_LINK
			from DEPARTMENT_GROUPS G inner join DEPARTMENT_GROUPS_REF REF on G.LINK = REF.GROUP_LINK
			where G.LINK = (SELECT MAX(REF1.GROUP_LINK) from DEPARTMENT_GROUPS_REF REF1 where REF1.DEP_LINK = REF.DEP_LINK)) GRP on D.LINK = GRP.D_LINK'
		+ ' order by COALESCE(GRP.GRP_NAME,''Без группы''), D.[NAME],SFIN_CODE, EKR_CODE'
		)

	EXEC (' DROP TABLE ' + @varKSTABLE_PAY)
	EXEC (' DROP TABLE ' + @varKSTABLE_TAX)
	EXEC (' DROP TABLE ' + @varKSTABLE_OUT2)
	EXEC BufferClear
END




GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD1] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_UPDATE_G_PROV_INVOICE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_UPDATE_G_PROV_INVOICE]

GO
CREATE PROCEDURE dbo.BK_UPDATE_G_PROV_INVOICE
	(@intDOC_LINK	INT,
	@intSELLER	INT = NULL ,
	@intBUYER	INT = NULL ,
	@intSHIPPER	INT = NULL ,
	@intRECEIVER	INT = NULL ,
	@PRODUCER	INT = NULL ,
	@strPAY_NUM	VARCHAR(30) = '',
	@dPAY_DATE	DATETIME = NULL ,
	@intOSNOV	INT = NULL ,
	@nTAX_RATE	NUMERIC(5, 2) = 0,
	@intINBOOK	TINYINT = 0,
	@SEL_SHIP	TINYINT = NULL ,
	@BUY_RECIVE	TINYINT = NULL ,
	@strCOR_NUM	VARCHAR(30) = '',
	@dCOR_DATE	DATETIME = NULL,
	@TAX_SUM	NUMERIC(28, 4) = 0
	)
AS
BEGIN
	DECLARE
		@intERROR	int,
		@intRowCount	int,
		@trancount	int,
		@intObjectLink int,
		@strEventText	varchar (254)

	--- Проверка входных значений ---
	SET @intDOC_LINK = (SELECT LINK FROM dbo.G_PROV WITH (NOLOCK) WHERE LINK = @intDOC_LINK)

	SET @intSELLER = (SELECT LINK FROM dbo.DEPARTMENTS WITH (NOLOCK) WHERE LINK = @intSELLER)
	SET @intBUYER = (SELECT LINK FROM dbo.DEPARTMENTS WITH (NOLOCK) WHERE LINK = @intBUYER)
	SET @intSHIPPER = (SELECT LINK FROM dbo.DEPARTMENTS WITH (NOLOCK) WHERE LINK = @intSHIPPER)
	SET @intRECEIVER = (SELECT LINK FROM dbo.DEPARTMENTS WITH (NOLOCK) WHERE LINK = @intRECEIVER)
	SET @PRODUCER = (SELECT LINK FROM dbo.DEPARTMENTS WITH (NOLOCK) WHERE LINK = @PRODUCER)
	SET @intOSNOV = (SELECT LINK FROM dbo.OSNOV WITH (NOLOCK) WHERE LINK = @intOSNOV)

	SELECT @nTAX_RATE = ISNULL (@nTAX_RATE, 0),
		@intINBOOK = ISNULL (@intINBOOK, 0),
		@strCOR_NUM = ISNULL (@strCOR_NUM, ''),
		@strPAY_NUM = ISNULL (@strPAY_NUM, ''),
		@SEL_SHIP = ISNULL (@SEL_SHIP, 0),
		@BUY_RECIVE = ISNULL (@BUY_RECIVE, 0),
		@TAX_SUM = ISNULL (@TAX_SUM, 0)


	IF @intDOC_LINK IS NULL
		RETURN 2	

	SET @trancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	UPDATE dbo.G_PROV_INVOICE 
	SET	SELLER = @intSELLER,
		BUYER = @intBUYER,
		SHIPPER = @intSHIPPER,
		RECEIVER = @intRECEIVER,
		PRODUCER = @PRODUCER, 
		PAY_NUM = @strPAY_NUM,
		PAY_DATE = @dPAY_DATE,
		OSNOV = @intOSNOV,
		TAX_RATE = @nTAX_RATE,
		INBOOK = @intINBOOK, 
		COR_NUM = @strCOR_NUM,
		COR_DATE = @dCOR_DATE,
		SEL_SHIP = @SEL_SHIP,
		BUY_RECIVE = @BUY_RECIVE,
		TAX_SUM = @TAX_SUM
	WHERE DOC_LINK = @intDOC_LINK

	SELECT @intERROR = @@ERROR, @intRowCount = @@ROWCOUNT

	IF @intRowCount = 0 AND @intERROR = 0
	BEGIN
		INSERT INTO dbo.G_PROV_INVOICE
			(DOC_LINK,
			SELLER,
			BUYER,
			SHIPPER,
			RECEIVER,
			PRODUCER,
			PAY_NUM,
			PAY_DATE,
			OSNOV,
			TAX_RATE,
			INBOOK,
			COR_NUM,
			COR_DATE,
			SEL_SHIP,
			BUY_RECIVE,
			TAX_SUM)
		SELECT @intDOC_LINK,
			@intSELLER,
			@intBUYER,
			@intSHIPPER,
			@intRECEIVER,
			@PRODUCER, 
			@strPAY_NUM,
			@dPAY_DATE,
			@intOSNOV,
			@nTAX_RATE,
			@intINBOOK, 
			@strCOR_NUM,
			@dCOR_DATE,
			@SEL_SHIP,
			@BUY_RECIVE,
			@TAX_SUM

		SELECT @intERROR = @@ERROR
	END

	IF @intERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	IF @@TRANCOUNT > @trancount
		COMMIT TRAN
	RETURN 0
END



GO


GRANT EXECUTE ON dbo.[BK_UPDATE_G_PROV_INVOICE] 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_FILL_WITH_CODEROW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_FILL_WITH_CODEROW]
GO

/*******************************************************************************
	c Кейсистемс (Keysystems), 2006
*******************************************************************************/
CREATE       procedure dbo.RN_FILL_WITH_CODEROW
	@LSF int, -- линк сохраненного отчета	
    @LF int, --линк отчета
	@OrderTable TINYINT-- порядковый номер таблицы
AS
    declare @im varchar(4000),@code_form varchar(20),@start_date datetime
    select @code_form=code,@start_date=start_date from dbo.report_forms where link_form=@LF

	declare @cstr_where nvarchar(4000),@cstr nvarchar(4000),@auto_spr varchar(100),@auto_code varchar(200),@auto_name varchar(2000),@auto_code_str varchar(1000),@auto_check varchar(2000),@link_table int, @auto_long_name varchar(8000), @script_str varchar(8000), @auto_parent varchar(8000), @split varchar(1000)
   declare @count_parent int, @parent varchar(1000), @substr varchar(1000), @parent_left varchar(1000), @parent_right varchar(1000), @tmp INT, @begin_date datetime, @end_date DATETIME  
	select @script_str = script_str from dbo.report_tables where link_form=@lf and orders = @OrderTable
   --заполнение справочников по новому
	set @cstr_where=''
  create table #AddCode (Code varchar(50), code_self varchar(50))
  CREATE TABLE #CodeDate (Code VARCHAR(50), begin_date DATETIME, end_date DATETIME)
  CREATE INDEX #ix_ADDcode ON #AddCode (CODE)
  CREATE INDEX #ix_CodeDate ON #CodeDate (CODE) 

	declare @count_check int,@i int,@check varchar(1000),@check_left varchar(1000),@check_right varchar(1000),@dict varchar(1000)
   IF charindex('AUTO_SPR_',@script_str)>0
	BEGIN
   			select top 1 @link_table=link_table from dbo.report_tables where link_form=@LF and orders=@OrderTable

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_FORM=',@auto_spr output
				--нет кода справочника
				IF @auto_spr=''
					return 

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_CODE=',@auto_code output
				IF @auto_code=''
					set @auto_code='T.CODE'

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_NAME=',@auto_name output
				if @auto_name=''
					set @auto_name=''''''

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_CODE_STR=',@auto_code_str output
				if @auto_code_str=''
					set @auto_code_str=''''''
				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_CHECK=',@auto_check output
      
				set @count_check=dbo.rn_getwordcount(@auto_check,'|')
				set @i=1
				set @dict=''
				while @i<=@count_check
					begin
						set @check=dbo.rn_getwordnum(@auto_check,@i,'|')
						set @check_left=dbo.rn_getwordnum(@check,1,'#')
						set @check_right=dbo.rn_getwordnum(@check,2,'#')
						IF @check_left like ('[0-9][0-9]') or @check_left like ('[0-9]')
							begin
								--условие формируем сами
								select @dict=rtrim(dictionary) from dbo.report_coloumns where link_table=@link_table and orders=cast(@check_left as int)
								--справочник не найден, пропускаем проверку
								if @dict<>''
									begin
										set @cstr_where=@cstr_where+' and exists(select code from '+@dict+' SPR where '+@check_right+'=SPR.code)'
									end
							end
						else
							begin
								set @cstr_where=@cstr_where+' and '+@check
							end				
						SET @i=@i+1
					end

       -- теперь добавляем коды, получаемы при досчете дерева
            exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_PARENT=',@auto_parent output
            exec dbo.rn_get_formula_code_row @link_Table,'SPLIT=',@split output
            if @auto_parent <> '' and @split <> ''
            begin
				   set @cstr='insert #AddCode (code, code_self)
				   select   code, ''''
				   from #t_CodeRow T where not exists(select code from report_kbk B where code_form='''+@auto_spr+''' and '+@auto_code+'=B.code)'+ @cstr_where
			   --	print  @cstr			
			   exec sp_executesql @cstr
   			   set @count_parent=dbo.rn_getwordcount(@auto_parent,'|')
				   set @i=1
				   while @i<=@count_parent
					   begin
						   set @parent=dbo.rn_getwordnum(@auto_parent,@i,'|')
						   set @parent_left=dbo.rn_getwordnum(@parent,1,'#')
						   set @parent_right=dbo.rn_getwordnum(@parent,2,'#')
                     set @dict = ''
                     set @substr = ''
                     select @dict=rtrim(dictionary) from dbo.report_coloumns where link_table=@link_table and orders=cast(@parent_left as int)
                     set @tmp = charindex('#', @split, charindex('COL' + RTRIM(@parent_left),@split)) - charindex('=', @split, charindex('COL' + RTRIM(@parent_left),@split)) - 1
                     if @tmp > 0
                        set @substr = substring(@split, charindex('=', @split, charindex('COL' + RTRIM(@parent_left),@split)) + 1, @tmp)
                     else
                        set @substr = substring(@split, charindex('=', @split, charindex('COL' + RTRIM(@parent_left),@split)) + 1, 1000)
                     set @substr = REPLACE(@substr, 'CODE_ROW', 'T.CODE')
                     if @dict <> '' and @substr <> ''
                     begin
		                  set @cstr='update T
		                  set code_self = isnull(' + REPLACE(@parent_right, 'XXX', '(select top 1 Code from ' + @Dict + ' D1 where D1.link = D.link_self )') + ','''')
		                  from #AddCode T left join ' + @Dict + ' D on ' + @substr + ' = D.Code where 
                          T.Code_self = '''' '
		
		                  exec sp_executesql @cstr

                        WHILE @@ROWCOUNT > 0
                        begin
		                     set @cstr='insert #AddCode (code, code_self)
		                     select distinct T.code_self, isnull(' + REPLACE(REPLACE(@parent_right, 'Code', 'Code_Self'), 'XXX', '(select top 1 Code from ' + @Dict + ' D1 where D1.link = D.link_self )') + ','''')
		                     from #AddCode T left join ' + @Dict + ' D on ' + REPLACE(@substr, 'T.Code', 'T.Code_self') + ' = D.Code where ' +
                           ' not exists(select * from #AddCode T1 where  T1.Code = T.code_self ) and T.code_self <> '''''
	                        exec sp_executesql @cstr
                        end
                     end
   					   SET @i=@i+1
                     update #AddCode set Code_self = '' where Code= Code_Self
					   END
                exec dbo.[RO_FILL_WITH_CODE_ROW_DATE] @split, '#AddCode', @link_table
                set @cstr='delete #AddCode where Code = ''''
               insert report_kbk (code_form,code,name,property,add_info,code_str, begin_date, end_date)
				   select distinct '''+@auto_spr+''','+@auto_code+','+@auto_name+',0,'''','+@auto_code_str +', CD.begin_date, CD.end_date
				   from #AddCode T left join #CodeDate CD on T.Code = CD.Code 
               where not exists(select code from report_kbk B where code_form='''+@auto_spr+''' and '+@auto_code+'=B.code)'+ @cstr_where
			   	--print  @cstr			
				   exec sp_executesql @cstr
                set @cstr='update k1
				   set link_self = k.link
				   from report_kbk k1 join  #AddCode T on  k1.code_form = ''' + @auto_spr + ''' and T.Code = k1.code
                     join report_kbk k on k.code_form = ''' + @auto_spr + ''' and k.code = T.code_self'
			   --	print  @cstr			
				   exec sp_executesql @cstr
          -----------------------------------------------------  
            end 
            else BEGIN
               exec dbo.[RO_FILL_WITH_CODE_ROW_DATE] @split, '#t_CodeRow', @link_table
				   set @cstr='insert report_kbk (code_form,code,name,property,add_info,code_str, begin_date, end_date)
				   select '''+@auto_spr+''','+@auto_code+','+@auto_name+',0,'''','+@auto_code_str +', CD.begin_date, CD.end_date
				   from #t_CodeRow T  left join #CodeDate CD on T.Code = CD.Code
               where not exists(select code from report_kbk B where code_form='''+@auto_spr+''' and '+@auto_code+'=B.code)'+ @cstr_where
			   	--print  @cstr			
				   exec sp_executesql @cstr	
            END
            
            -----------------------------
            ----------------------------
            

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_NAME_UPD=',@auto_name output
				IF @auto_name<>''
					begin
						set @cstr='exec dbo.ro_get_name_spr '+str(@link_table)+','+@auto_name 
					--print @cstr
						exec sp_executesql @cstr
					end

				exec dbo.rn_get_formula_code_row @link_Table,'AUTO_SPR_LONG_NAME_UPD=',@auto_long_name output
				IF @auto_long_name<>''
					begin
						set @cstr='exec dbo.ro_get_name_spr '+str(@link_table)+','+@auto_long_name 
					--	print @cstr
						exec sp_executesql @cstr
					END
            
               
			   drop table #AddCode
            
            EXEC dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = @auto_spr, @tOnlyAdd = 1
	return

	end
--	if charindex('SPLIT=', @script_str) > 0 and charindex('AUTO_SPR_',@script_str) = 0
	exec dbo.rn_fill_with_coderow_for_old_form @LSF, @LF,@OrderTable
GO
GRANT ALL ON dbo.[RN_FILL_WITH_CODEROW] 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].[RO_PRINT_NO_ITOG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_NO_ITOG]
GO

/*

	c Кейсистемс (Keysystems), 2010
	Печать без подитогов, подразумевается что здесь 3 таблицы: Доходы, Расходы, Источники
*/


CREATE       PROCEDURE dbo.RO_PRINT_NO_ITOG
	@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, @codeForm varchar(30) -- 1 - без подитогов, 0 - подитоги не удаляются
DECLARE @vrKSiOnlyRash INT  

set @varKSiParam = 0
set @vrKSiOnlyRash = 0

if object_id('tempdb..#Param_Print') is NOT NULL
BEGIN 
	select @varKSiParam = convert(int, Value) from #Param_Print where Param = 'NoPoditog'
   select @vrKSiOnlyRash = convert(int, Value) from #Param_Print where Param = 'NoItog_Rash'
   IF @vrKSiOnlyRash = 1
   BEGIN
      SET  @varKSiParam = 0
   END    
END    

IF @LSF is NULL
	return -1

declare @iLF int, @iLT int, @cRunStr varchar(8000), @cRunStr1 varchar(8000), @dBeginDate DATETIME, @iDiffDate INT 
select @iLF = Link_Form, @dBeginDate = begin_date from report_saved_forms where Link_Saved_Form = @LSF

SET @iDiffDate = DATEDIFF(DAY, '20111231', @dBeginDate)

EXEC dbo.[BufferClear] 'RO_RAZMNOJ_KS_OUTSIDE'
EXEC dbo.[BufferPush] @iDiffDate, 'RO_RAZMNOJ_KS_OUTSIDE'

select @codeForm = code from report_forms where link_form = @iLF

if isnull(@WEB_excel, 0) <> 1
	select '' col1 

------------------------------------------------------------------------------------------------
-- ТАБЛИЦА ДОХОДОВ

select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 1
set @cRunStr = '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)'
set @cRunStr1 = 'insert #doh (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code'

select @cRunStr = @cRunStr + ',COL' + LTRIM(STR(orders))+ case Col_Type when 0 then ' float' else ' varchar(' + case when val_len > 0 then LTRIM(STR(val_len+10)) else '254' end + ')' end,
	@cRunStr1 = @cRunStr1 + ',COL' + LTRIM(STR(orders))
from report_coloumns
where Link_Table = @iLT
order by orders

set @cRunStr = @cRunStr + ') ' + @cRunStr1 + ') exec dbo.rn_get_all_adm_table ' + LTRIM(STR(@LSF)) + ', 1, ' + LTRIM(STR(@bDeleteEmptyRows)) + ', ' + lTRIM(STR(@AtrInOnePage)) + ', 1 '
if substring(@codeForm, 5, 1) = '3'
begin
   set @cRunStr1 = 'select * from #doh D' + case when @varKSiParam = 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)) + ')
	   or code like ''%85000000000000000%''' else '' end
end
else begin
   set @cRunStr1 = 'select * from #doh D' + case when @varKSiParam = 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
end

print @cRunStr + @cRunStr1 + '
 drop table #doh'

if @codeForm not like '0503138%'
	execute(@cRunStr + @cRunStr1 + ' drop table #doh')

------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДОВ

declare @OT_rash tinyint
set @OT_rash = case when @codeForm not like '0503138%' then 2 else 1 end
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = @OT_rash
set @cRunStr = '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)'
set @cRunStr1 = 'insert #rash (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code'

select @cRunStr = @cRunStr + ',COL' + LTRIM(STR(orders))+ case Col_Type when 0 then ' float' else ' varchar(' + case when val_len > 0 then LTRIM(STR(val_len+10)) else '254' end + ')' end,
	@cRunStr1 = @cRunStr1 + ',COL' + LTRIM(STR(orders))
from report_coloumns
where Link_Table = @iLT
order by orders

set @cRunStr = @cRunStr + ') ' + @cRunStr1 + ') exec dbo.rn_get_all_adm_table ' + LTRIM(STR(@LSF)) + ', ' + LTRIM(STR(@OT_rash)) + ', ' + LTRIM(STR(@bDeleteEmptyRows)) + ', ' + lTRIM(STR(@AtrInOnePage)) + ', 1 '
set @cRunStr1 = 'select * from #rash' + case when @varKSiParam = 1 OR @vrKSiOnlyRash = 1 then ' where right(rtrim(code),3) not in (''200'',''000'',''210'',''220'',''230'',''240'',''250'',''260'',''300'',''500'',''600'') 
	or code like ''%9600000000000000%'' or code like ''%7900000000000000%''' else '' end

print @cRunStr + @cRunStr1 + ' drop table #rash'
execute(@cRunStr + @cRunStr1 + ' drop table #rash')
-------------------------------------------------------------------------------------------------
-- ТАБЛИЦА ИСТОЧНИКОВ
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 3
set @cRunStr = '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)'
set @cRunStr1 = 'insert #ist (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code'

select @cRunStr = @cRunStr + ',COL' + LTRIM(STR(orders))+ case Col_Type when 0 then ' float' else ' varchar(' + case when val_len > 0 then LTRIM(STR(val_len+10)) else '254' end + ')' end,
	@cRunStr1 = @cRunStr1 + ',COL' + LTRIM(STR(orders))
from report_coloumns
where Link_Table = @iLT
order by orders

set @cRunStr = @cRunStr + ') ' + @cRunStr1 + ') exec dbo.rn_get_all_adm_table ' + LTRIM(STR(@LSF)) + ', 3, ' + LTRIM(STR(@bDeleteEmptyRows)) + ', ' + lTRIM(STR(@AtrInOnePage)) + ', 1 '

set @cRunStr1 = 'select * from #ist'  + case when @varKSiParam = 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


print @cRunStr + @cRunStr1 + ' drop table #ist'
if @codeForm not like '0503138%'
	execute(@cRunStr + @cRunStr1 + ' drop table #ist')

-------------------------------------------------------------------------------------------------
-- ТАБЛИЦА КОНСОЛИДИРОВАННЫХ РАСЧЕТОВ, ЕСЛИ ОНА ЕСТЬ
set @iLT = (select Link_Table from report_tables where Link_Form = @iLF and orders = 4)
if @iLT is NOT NULL
begin
   set @cRunStr = 'create table #kons(checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50)'
   set @cRunStr1 = 'insert #kons (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code'

   select @cRunStr = @cRunStr + ',COL' + LTRIM(STR(orders))+ case Col_Type when 0 then ' float' else ' varchar(' + case when val_len > 0 then LTRIM(STR(val_len+10)) else '254' end + ')' end,
	   @cRunStr1 = @cRunStr1 + ',COL' + LTRIM(STR(orders))
   from report_coloumns
   where Link_Table = @iLT
   order by orders

   set @cRunStr = @cRunStr + ') ' + @cRunStr1 + ') exec dbo.rn_get_all_adm_table ' + LTRIM(STR(@LSF)) + ', 4, ' + LTRIM(STR(@bDeleteEmptyRows)) + ', ' + lTRIM(STR(@AtrInOnePage)) + ', 1 '
   set @cRunStr1 = 'select * from #kons' 

   execute(@cRunStr + @cRunStr1 + ' drop table #kons')
end

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 ALL ON dbo.[RO_PRINT_NO_ITOG] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_WEB_DEL_SIGN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_DEL_SIGN]
GO




/*
© Кейсистемс (Keysystems), 2006
	Вызов в тонком процедуры изменения статуса
*/
CREATE  PROCEDURE dbo.RO_WEB_DEL_SIGN
	@varKStableName varchar(100), -- таблица с линками отчетов для внутридокументной проверки
	@varDocCode	varchar(30) = NULL, -- код объекта
	@cText varchar(254) = '' output, -- список возвращаемых полей
   @WEB tinyint = 1 
AS
	set @cText  = 'Результат'

	declare @ExecStr varchar(8000), @varKSLink_Task int, @varKSintLINK int, @varKSEventStr varchar(1000), @uid int
	create table #ListForms(lsf int, [uid] int default(0))
   declare @t_not_access table (lsf int)
   set @uid = dbo.AdminGetUidBySid(suser_sid())
   
   if NOT (IS_MEMBER('db_owner') = 1) AND ISNULL((SELECT val_int FROM dbo.report_options WHERE [Razdel] = 'ECP' AND Code = 'NotDel'), 0) = 1
   begin
      select 'Удалять подписи запрещено' as Res
      return 0
   end
	
	if RTRIM(ISNULL(@varKStableName,'')) <> '' and (select object_id('tempdb..' + @varKStableName)) is NOT NULL
	begin
      if  COL_LENGTH('tempdb..' + @varKStableName, 'uid') is NULL
      begin
		   set @ExecStr = 'insert #ListForms (lsf, uid) select *, ' + LTRIM(STR(@uid)) + ' from ' + @varKStableName + ' drop table ' + @varKStableName
      end
      else begin
         set @ExecStr = 'insert #ListForms (lsf, uid) select * from ' + @varKStableName + ' drop table ' + @varKStableName
      end
		execute(@ExecStr)
	end
   else begin
      return -1
   end

   insert @t_not_access (lsf)
   select link_saved_form
   from dbo.report_saved_forms RSF join #ListForms L on RSF.link_saved_form = L.lsf
   where dbo.RO_ACCESS_SAVED_FORM (Link_Saved_Form, @WEB) & 2 = 0

   delete #ListForms
   where lsf in (select lsf from @t_not_access)

	select @varKSLink_Task = link_task from user_info

	if (select count(*) from report_sign S join #ListForms L on S.lsf = L.lsf and (L.uid = 0 or S.sid = dbo.AdminGetSidByUid(L.Uid))) > 0 or exists(select top 1 * from @t_not_access)
      delete S from report_sign S join #ListForms L on S.lsf = L.lsf and (L.uid = 0 or S.sid = dbo.AdminGetSidByUid(L.Uid))
   else begin
      if not exists(select * from #ListForms where uid = 0)
         select 'Нет вашей подписи' as Res
      else
         select 'Нет подписи' as Res
      return 0
   end
      
   
   declare cur_lsf cursor local static for select lsf, [uid] from #ListForms

   open cur_lsf

   fetch next from cur_lsf into @varKSintLINK, @uid

   while @@fetch_status = 0
   begin
	   select @varKSEventStr = 'Для Отчета: ' + rtrim(RF.code) + ' ' + atr + ' Период: ' + 
			   convert(char(4),year(BEGIN_DATE)) + ' год ' + 
			   case period_Type when 2 then convert(char(1),period_number) + ' квартал'
				   when 4 then convert(char(2),period_number) + ' месяц'
			   ELSE '' end + ' Версия:' +  convert(char(3),RSF.version) + ' Организация: ' + D.Code + ' Бюджет: ' + B.Name
	   from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
		   left join departments D on D.link = RSF.link_organization 
		   left join kl_budg_type B on B.link = RSF.link_type_svod
	   where link_saved_form = @varKSintLINK

      if @uid <> 0
         select @varKSEventStr = 'Подпись пользователя ' + isnull(FIO, '') + ' ' + isnull(Name,'') + ' ' + @varKSEventStr
         from dbo.db_users
         where uid = @uid

	   exec WF_GENERATEEVENT 'Удаление подписи', @varKSEventStr, @varKSLink_Task, 'REPORT_SIGN', @varKSintLINK

      fetch next from cur_lsf into @varKSintLINK, @uid
   end

   close cur_lsf
   deallocate cur_lsf
	drop table #ListForms
	
   set @varKSEventStr = ''
   select @varKSEventStr = @varKSEventStr + RTRIM(RF.Code) + ' ' + RTRIM(atr) + ', '
   from report_saved_forms RSF 
        join @t_not_access A on RSF.link_saved_form = A.lsf
        left join report_forms RF on RSF.link_form = RF.Link_Form 

   if @varKSEventStr <> ''
   begin
      set @varKSEventStr = 'Удаление подписи из-за отсутствия прав не произошло для следующих отчетов: ' + LEFT(@varKSEventStr, LEN(@varKSEventStr) - 1)
   end
   else
     set @varKSEventStr = 'Удаление подписей с отчетов завершено'
   select @varKSEventStr as Res

GO
GRANT EXECUTE ON dbo.[RO_WEB_DEL_SIGN] 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].[RO_WEB_VR_USER_2011_SAVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_WEB_VR_USER_2011_SAVE]
GO






CREATE       PROCEDURE dbo.RO_WEB_VR_USER_2011_SAVE
	@iLinkSF	int output,
	@bExcess tinyint = 0 output,	-- FOR WEB only
	@cText	varchar(50) = '' output	-- FOR WEB only

AS

SET @bExcess = 0
SET @cText='Результат'

-- Проверяем существование врем. таблицы с описанием
if object_id('tempdb..#RO_VR_USER_2011_WEB') is NULL
	return -1

declare @Link int, @iRes int, @Link_Tree int, @Name varchar(254), @Long_Name varchar(8000)


select	@Link = Link,
	@Name = Name,
	@Long_Name = Long_Name,
   @Link_Tree = Link_Tree
from #RO_VR_USER_2011_WEB

if isnull(@Link_Tree, 0) = 0
begin
	select 'Нет прав на дерево организаций и бюджетов' as Res
	set @bExcess = 1
end


exec @iRes = dbo.RO_KBK_SAVE_FOR_ORG @Link, @Link_Tree,@Name, @Long_Name

if @iRes <> 0
begin
	select 'Ошибка сохранения' as Res
	set @bExcess = 1
end
else
	select 'Успешно сохранен' as Res



GO
GRANT ALL ON dbo.[RO_WEB_VR_USER_2011_SAVE] 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].[RO_IMPORT_REPORT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_IMPORT_REPORT]
GO

/*
c Кейсистемс (Keysystems), 2006
	Импорт отчетов
*/

CREATE PROCEDURE dbo.[RO_IMPORT_REPORT]
   @varKStableName VARCHAR(100), -- имя временной таблицы, где хранится содержимое файла (структура: (orders int, txt varchar(1000), NameFile varchar(128)))
   @Res	          VARCHAR(50) = '' OUTPUT,-- FOR WEB only
   @WEB	          BIT	= 1,		-- Тонкий клиент, иначе со Свода-КС
   @bExcess        TINYINT = 0 output,	-- FOR WEB only
   @RepeatRequest	 INT = NULL,	-- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @ltCalcItog     TINYINT = 0, -- 1 - Расчет итогов после импорта, 0 - иначе.
   @tIsAppend      TINYINT = 0, -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
   @tDemoMode      TINYINT = 0, -- Режим импорта 0 - обычный, 1 - демо.
   @tADEMode       TINYINT = 0,  -- Режим автономной обработки документа : 
                                --    0 - выкл., 
                                --    1 - Если отчет существует, перезаписываем его,
                                --    2 - Если отчет существует, создаем новую версию отчета,
                                --    3 - Если отчет существует, не принимаем новый отчет
	@tCheckKS		tinyint = 0	-- проверять КС при импорте
AS
SET NOCOUNT ON

DECLARE @liError        INT,
        @lvcError       VARCHAR(1000),
        @liLSF          INT,
        @ldBEGIN        DATETIME,
        @ldEND          DATETIME,
        @vcFileName    VARCHAR(128), 
        @lcCodeForm     CHAR(20), 
        @i              INT,
	     @liLINK_FORM    INT,
        @iLINK_SAVED_FORM INT, 
        @lvcEXPORT_PROC VARCHAR(1000),
        @ltPRD          TINYINT,
        @iORDER_START   INT,
        @iORDER_END     INT,
        @iLINK_SELF     INT,
        @tMode          TINYINT,
        @iDEMO_IMPORT_COUNT INT,
		@lExecStr		NVARCHAR(4000),
      @cCODE_FORM    VARCHAR(30),
      @tImportType   TINYINT,
      @cAdm          CHAR(3),
      @iOrderAdm     tinyint  


SELECT @Res = 'Результат',
       @bExcess = 0,
       @tMode = 0

IF OBJECT_ID('tempdb..#t_Result') IS NOT NULL
BEGIN
	DROP TABLE #t_Result
END

CREATE TABLE #tabImportOptions([OPTION]     VARCHAR(20),
                               [VALUE_INT]  INT)

CREATE TABLE #t_Result([TXT] VARCHAR(8000), 
                       [ERROR] BIT DEFAULT(0), 
                       [ORDERS] INT IDENTITY(1,1))

CREATE TABLE #tabImportFile ([ORDERS] INT, 
                             [TXT]    VARCHAR(8000), 
                             [FileName] VARCHAR(128))

CREATE TABLE #t_RepeatRequest ([RES]     VARCHAR(50), 
                               [bExcess] TINYINT)

CREATE TABLE #tabLSF([LSF] INT)

DECLARE @t_ADM_IMPORT TABLE (ADM CHAR(3))
CREATE TABLE #t_ADM_IMPORT_TABLE  ([TXT]   VARCHAR(8000), 
                                    [ORDER] INT)

INSERT #tabImportOptions([OPTION],[VALUE_INT]) VALUES ('ADE_MODE',@tADEMode)


IF @tDemoMode = 1
BEGIN
   
   IF dbo.[XA_GET_VAR]('DEMO_IMPORT_COUNT',0x01,1) IS NULL
   BEGIN
      EXEC dbo.[XA_SAVE_VAR] 'DEMO_IMPORT_COUNT',1,0x01,1   
   END
   ELSE BEGIN
      SET @iDEMO_IMPORT_COUNT = CAST(dbo.[XA_GET_VAR]('DEMO_IMPORT_COUNT',0x01,1) AS INT)+ 1
      EXEC dbo.[XA_SAVE_VAR] 'DEMO_IMPORT_COUNT',@iDEMO_IMPORT_COUNT,0x01,1
   END

   EXEC dbo.[RA_IMPORT_FORM_INIT_DEMO]
   SET @tMode = 1
END

-- Повторный вызов с отклонением импорта.
IF @RepeatRequest < 0 
BEGIN
	IF OBJECT_ID('tempdb..#t_RepeatRequest') IS NOT NULL
	BEGIN      
		set @lExecStr = 'DELETE [A]
      FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
      JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[LINK_SELF] = [B].[LINK_SELF]
      WHERE [B].[LINK_SAVED_FORM] = -@RepeatRequest'

		exec sp_executesql @lExecStr,  N'@RepeatRequest int', @RepeatRequest = @RepeatRequest

		INSERT #t_RepeatRequest ([RES],
                               [bExcess])	
      VALUES ('Результат', 
              1)
	END

	INSERT #t_Result ([TXT], [ERROR]) VALUES ('Импорт не произошел', 1)
END
ELSE BEGIN   
   IF @RepeatRequest > 0 AND EXISTS(SELECT *
                                    FROM dbo.[REPORT_IMPORT_SAVED_FORMS]
                                    WHERE [LINK_SAVED_FORM] = @RepeatRequest)
   BEGIN
	  if object_id('tempdb..#IMPORT_TABLE') is NOT NULL drop table #IMPORT_TABLE
      DECLARE curImportSavedForm INSENSITIVE CURSOR FOR
         SELECT [B].[LINK_SAVED_FORM],
                [C].[EXPORT_PROC]               
         FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]   
         JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[LINK_SELF] = [B].[LINK_SELF]
         JOIN dbo.[REPORT_FORMS]              [C] ON [B].[LINK_FORM] = [C].[LINK_FORM]
         WHERE [A].[LINK_SAVED_FORM] = @RepeatRequest
     
      OPEN curImportSavedForm
      
      FETCH NEXT 
      FROM curImportSavedForm
      INTO @iLINK_SAVED_FORM,
           @lvcEXPORT_PROC

      WHILE @@FETCH_STATUS=0
      BEGIN
--		SET @lvcEXPORT_PROC = 'EXEC dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE] ' + STR(@WEB) + ', ' + ISNULL(CONVERT(VARCHAR(10), @iLINK_SAVED_FORM), 'NULL') + ', ' + ISNULL(CONVERT(VARCHAR(10), @tIsAppend), 'NULL') +  + ',DEFAULT,DEFAULT,' + LTRIM(STR(@tMode))

       SET @i = CHARINDEX('#', @lvcEXPORT_PROC)
   	   IF  @i > 0
   	   BEGIN
			SET @lvcEXPORT_PROC = 'CREATE TABLE #IMPORT_TABLE([TXT]   VARCHAR(8000), [ORDER] INT IDENTITY(1,1)) EXEC ' + RIGHT(RTRIM(@lvcEXPORT_PROC), LEN(RTRIM(@lvcEXPORT_PROC)) - @i) + ' ' + STR(@WEB) + ', ' + ISNULL(CONVERT(VARCHAR(10), @iLINK_SAVED_FORM),	 'NULL') + ', ' + ISNULL(CONVERT(VARCHAR(10), @tIsAppend), 'NULL') + ',DEFAULT,DEFAULT, ' + LTRIM(STR(@tMode))
   	   END
   	   ELSE BEGIN
   		   SET @lvcEXPORT_PROC = 'EXEC dbo.[RA_IMPORT_FORM_REPEAT_REQUEST_MULTIPLE] ' + STR(@WEB) + ', ' + ISNULL(CONVERT(VARCHAR(10), @iLINK_SAVED_FORM), 'NULL') + ', ' + ISNULL(CONVERT(VARCHAR(10), @tIsAppend), 'NULL') +  + ',DEFAULT,DEFAULT,' + LTRIM(STR(@tMode))
   	   END

         EXEC(@lvcEXPORT_PROC)

         FETCH NEXT 
         FROM curImportSavedForm
         INTO @iLINK_SAVED_FORM,
              @lvcEXPORT_PROC
      END

      CLOSE curImportSavedForm
      DEALLOCATE curImportSavedForm

	 IF EXISTS(SELECT TOP 1 * FROM #t_RepeatRequest) -- может быть такая ситуация: выблрали дерево, но отчет там уже существует и нужно перезаписать отчет
	 BEGIN
		   SELECT @Res     = [RES],
                 @bExcess = [bExcess]
           FROM #t_RepeatRequest
	  END
		ELSE BEGIN
			  set @lExecStr = 'DELETE [A]
			  FROM dbo.[REPORT_IMPORT_SAVED_FORMS] [A]
			  JOIN dbo.[REPORT_IMPORT_SAVED_FORMS] [B] ON [A].[LINK_SELF] = [B].[LINK_SELF]
			  WHERE [B].[LINK_SAVED_FORM] = @RepeatRequest'
			exec sp_executesql @lExecStr,  N'@RepeatRequest int', @RepeatRequest = @RepeatRequest
		END
--      exec xa_watchi '@lvcEXPORT_PROC',@lvcEXPORT_PROC
   END
   ELSE BEGIN
	   IF OBJECT_ID('tempdb..' + @varKStableName) is NULL
      BEGIN
      	SELECT 'Отстутствует таблица с данными!'
      	RETURN -1
      END
      
      INSERT #tabImportFile 
      EXECUTE('SELECT [ORDERS], [TXT], [FileName] FROM ' + @varKStableName  + ' DROP TABLE ' + @varKStableName)        

      SELECT @iORDER_START = NULL,
             @iORDER_END = NULL

--      SELECT @iORDER_START = MIN([ORDERS])
--      FROM #tabImportFile  
--      WHERE LEFT([TXT],2)='#%'

      WHILE EXISTS(SELECT * FROM #tabImportFile)
      BEGIN     
         CREATE TABLE #IMPORT_TABLE([TXT]   VARCHAR(8000), 
                                    [ORDER] INT IDENTITY(1,1))
                                    
         IF @iORDER_START IS NULL
         BEGIN
            SELECT @iORDER_START = MIN([ORDERS])
            FROM #tabImportFile  
         END
         SET @iORDER_END = NULL
         SELECT @iORDER_END = MIN([ORDERS])
         FROM #tabImportFile  
         WHERE LEFT([TXT],2)='#%' AND
               [ORDERS] > @iORDER_START AND
               (SELECT COUNT(*) 
                FROM #tabImportFile
                WHERE LEFT([TXT],5) = 'КОДФ=' OR TXT LIKE 'КФ=%') > 1

         IF @iORDER_END IS NULL
         BEGIN
            SELECT @iORDER_END = MAX([ORDERS])+1
            FROM #tabImportFile
         END

         TRUNCATE TABLE #IMPORT_TABLE

         INSERT #IMPORT_TABLE([TXT])
         SELECT [TXT]
         FROM #tabImportFile 
         WHERE [ORDERS] BETWEEN @iORDER_START AND (@iORDER_END-1)
         ORDER BY [ORDERS]
    
         SELECT TOP 1 @vcFileName = [FileName]
         FROM #tabImportFile
         WHERE [ORDERS] BETWEEN @iORDER_START AND (@iORDER_END-1)

         DELETE #tabImportFile
         WHERE [ORDERS] BETWEEN @iORDER_START AND (@iORDER_END-1)
         
--         SELECT * FROM #IMPORT_TABLE                                    
--         SELECT * FROM #tabImportFile
--         SELECT @iORDER_START, @iORDER_END
--
        SET @iORDER_START = @iORDER_END

         -- Разбор загловочной части отчета, получение всех его свойств кроме данных (в REPORT_IMPORT_SAVED_FORMS).         
         SELECT @i = dbo.[RA_GET_ERRORS_LOG_ORDER]() + 1,
                @iLINK_SAVED_FORM = NULL

         EXEC dbo.[RA_IMPORT_FORM_ANALYZE] @iLINK_SAVED_FORM OUTPUT,
                                           DEFAULT,
                                           @vcFileName,2

	      SELECT @liLINK_FORM = [LINK_FORM]
	      FROM dbo.[REPORT_IMPORT_SAVED_FORMS]
	      WHERE [LINK_SAVED_FORM]=@iLINK_SAVED_FORM
   
			set @lExecStr = 'DELETE dbo.[REPORT_IMPORT_SAVED_FORMS] WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM'
		   exec sp_executesql @lExecStr,  N'@iLINK_SAVED_FORM int', @iLINK_SAVED_FORM = @iLINK_SAVED_FORM

         -- Очистка журнала ошибок dbo.[RA_IMPORT_FORM_ANALYZE]
         EXEC dbo.[RA_ERRORS_LOG_CLEAR] DEFAULT,DEFAULT,@i     
	   
		   IF @liError < 0
		   BEGIN
		      INSERT #t_Result([TXT],[ERROR]) 
            VALUES ('Предварительный анализ формы. Ошибка : ' + 
                    dbo.[RA_GET_ERROR_MESSAGE]('RA_IMPORT_FORM_GET_LINK_FORM',@liError),1)
		   END
		   ELSE BEGIN
            
            SELECT @lvcEXPORT_PROC = [EXPORT_PROC], @cCODE_FORM = [ExportCode] 
            FROM dbo.[REPORT_FORMS]
            WHERE [LINK_FORM] = @liLINK_FORM

            set @iOrderAdm = 2
            
            if @cCODE_FORM IN ('264')
               set @iOrderAdm = 1
            
  			   IF @cCODE_FORM IN ('214', '217','224','234','227','228','237','238','264','277','284','484', '117')
            BEGIN 
               SELECT @tImportType = [VAL_INT] FROM dbo.[REPORT_OPTIONS] WHERE [RAZDEL] = 'FORM_117' AND [CODE] = 'IMPORT_TYPE_117'
               IF @tImportType = 2 -- с единым кодом администратора
               BEGIN
                  UPDATE #IMPORT_TABLE
                  SET TXT = case when @iOrderAdm = 2 then dbo.[RA_GETWORDNUM](TXT, 1,'|') + '|000|' + SUBSTRING(TXT, CHARINDEX('|', TXT)+ 5, 8000)
                                 else '000|' + SUBSTRING(TXT, CHARINDEX('|', TXT)+ 1, 8000) end
                  WHERE TXT like '%|%' AND  dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|')) = 1 AND LEN(dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|')) = 3 AND dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|') NOT IN ('000', '***') 
               END
               ELSE BEGIN
                  INSERT @t_ADM_IMPORT (ADM) 
                  SELECT DISTINCT dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|')
                  FROM #IMPORT_TABLE
                  WHERE TXT like '%|%' AND  dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|')) = 1 AND LEN(dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|')) = 3 AND dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|') NOT IN ('000', '***')
         
                  execute('INSERT #t_ADM_IMPORT_TABLE (TXT, [ORDER]) SELECT TXT, [ORDER] FROM #IMPORT_TABLE')
                  IF (SELECT COUNT(*) FROM @t_ADM_IMPORT) = 1
                     DELETE @t_ADM_IMPORT -- если только один администратор, то итоговые строки можно грузить
               END                  
            END                                  

            SET @i = CHARINDEX('#', @lvcEXPORT_PROC)
			   IF  @i > 0
			   BEGIN       			      
  				   SET @lvcEXPORT_PROC = 'EXEC ' + RIGHT(RTRIM(@lvcEXPORT_PROC), LEN(RTRIM(@lvcEXPORT_PROC)) - @i) + 
  				                         ' ' + STR(@WEB) + ', ' + isnull(convert(varchar(10), @RepeatRequest), 'NULL') + 
  				                         ', ' + ISNULL(CONVERT(VARCHAR(10), @tIsAppend), 'NULL') + ',DEFAULT,DEFAULT,' + LTRIM(STR(@tMode))
			   END
			   ELSE BEGIN
				   SET @lvcEXPORT_PROC = 'EXEC dbo.[RA_IMPORT_FORM_STANDART] ' + 
				                         STR(@WEB) + ', ' + ISNULL(CONVERT(VARCHAR(10), @RepeatRequest), 'NULL') + ', ' + 
				                         ISNULL(CONVERT(VARCHAR(10), @tIsAppend), 'NULL') + ',DEFAULT, ' + ISNULL(CONVERT(VARCHAR(10), @iLINK_SELF), 'NULL')+','+LTRIM(STR(@tMode))
			   END

            
            IF EXISTS(SELECT * FROM @t_ADM_IMPORT) -- нужно разбить по администраторам
            BEGIN
               WHILE EXISTS(SELECT * FROM @t_ADM_IMPORT)
               BEGIN
                  TRUNCATE TABLE #IMPORT_TABLE
                                     
                  SELECT top 1 @cAdm = ADM FROM  @t_ADM_IMPORT
                  DELETE @t_ADM_IMPORT WHERE ADM = @cAdm
                  
                  INSERT #IMPORT_TABLE ([TXT])
                  SELECT [TXT]
                  FROM #t_ADM_IMPORT_TABLE
                  WHERE [TXT] NOT LIKE '%|%' OR dbo.[RA_GETWORDNUM](TXT, @iOrderAdm,'|') = @cAdm   
                  ORDER BY [ORDER]

                  EXECUTE(@lvcEXPORT_PROC)   
                  
               END  
               TRUNCATE TABLE #t_ADM_IMPORT_TABLE              
            END
            ELSE BEGIN  
               --print @lvcEXPORT_PROC
               EXECUTE(@lvcEXPORT_PROC)
            END            

			   IF EXISTS(SELECT TOP 1 * FROM #t_RepeatRequest)
			   BEGIN
				   SELECT @Res     = [RES],
                      @bExcess = [bExcess]
               FROM #t_RepeatRequest

               IF @iLINK_SELF IS NULL AND
                  ISNUMERIC(dbo.[RA_GETWORDNUM](REPLACE(@Res,'Результат @ ',''),1,'#'))=1
               BEGIN
                  SET @iLINK_SELF = CAST(dbo.[RA_GETWORDNUM](REPLACE(@Res,'Результат @ ',''),1,'#') AS INT)
               END

			   END
         END        
         
         IF OBJECT_ID('tempdb..#IMPORT_TABLE') IS NOT NULL
         BEGIN
            DROP TABLE #IMPORT_TABLE
         END

   	   INSERT #t_Result ([TXT]) VALUES ('')         
      END         
   END

   DECLARE curLSF CURSOR FOR
      SELECT [LSF]
      FROM #tabLSF
   
   OPEN curLSF
   
   FETCH NEXT
   FROM curLSF
   INTO @liLSF
   
   WHILE @@FETCH_STATUS = 0
   BEGIN
      EXEC dbo.[RN_SPLIT_CODE_ROW] @liLSF

      IF @ltCalcItog = 1
      BEGIN
          EXEC dbo.[RA_GET_LSF_PERIOD] @liLSF,
                                       @ldBEGIN OUTPUT,
                                       @ldEND OUTPUT
    
          EXEC dbo.[RI_REPORT_FORMULA_CALCULATE_ITOG] @ldBEGIN, @ldEND, @liLSF
      END         


      FETCH NEXT
      FROM curLSF
      INTO @liLSF
   
   END      

   CLOSE curLSF
   DEALLOCATE curLSF

   IF OBJECT_ID('tempdb..#tabADE_LSF') IS NOT NULL
   BEGIN
      INSERT #tabADE_LSF([LSF])    
      SELECT [LSF]
      FROM #tabLSF   
   END

   IF @tMode = 1 
   BEGIN
      SET @iLINK_SAVED_FORM = NULL

      SELECT @iLINK_SAVED_FORM = MIN([LSF])
      FROM #tabLSF           
      
      IF @iLINK_SAVED_FORM IS NOT NULL
      BEGIN
         SET @Res = @Res + ' @ ' + LTRIM(STR(@iLINK_SAVED_FORM))
         set @lExecStr = 'DELETE [A]
         FROM dbo.[REPORT_SAVED_FORMS] [A]
         JOIN #tabLSF                  [B] ON [A].[LINK_SAVED_FORM]=[B].[LSF]
         WHERE [A].[LINK_SAVED_FORM] <> @iLINK_SAVED_FORM'
			exec sp_executesql @lExecStr,  N'@iLINK_SAVED_FORM int', @iLINK_SAVED_FORM = @iLINK_SAVED_FORM
      END
   END
END

if object_id('tempdb..#t_Result_b') is NOT NULL
begin
	insert #t_Result_b (TXT)
	SELECT [TXT]
	FROM #t_Result 
	ORDER BY [ORDERS]
end
else begin
	SELECT [TXT]
	FROM #t_Result 
	ORDER BY [ORDERS]
end

DROP TABLE #t_Result
--DROP TABLE #tabImportFile
DROP TABLE #t_RepeatRequest 	   
DROP TABLE #tabImportOptions
DROP TABLE #t_ADM_IMPORT_TABLE

	if @tCheckKS = 1
	begin
		exec dbo.RO_CHECK_KS @varKStableName = '#tabLSF'
	end
	else
		DROP TABLE #tabLSF
GO
GRANT ALL ON dbo.[RO_IMPORT_REPORT] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select export_proc,* from report_forms where export_proc like '%#%'

select * from report_saved_forms
select * from report_forms where link_form=1939

select distinct dbo.ra_getwordnum(export_proc,2,'#') from report_forms where export_proc like '%#%'



*/

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[X_FORM_SAVE_DICTIONARY]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[X_FORM_SAVE_DICTIONARY]

GO





/*
© Кейсистемс (Keysystems), 2005
*/
CREATE     PROCEDURE dbo.X_FORM_SAVE_DICTIONARY


	@varKScCode varchar(30),	
	@varKShostCode varchar(30) = null,
	@varKSTestCode bit = 1,
	@varKSWithDel bit = 0
AS
BEGIN
	IF @varKShostCode is null
		SET @varKShostCode = @varKScCode
	DECLARE
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSCurNAME	varchar(254),
		@varKSRefLINK	int,
		@varKSCurCODE	varchar(30),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(100),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(8000),
		@varKSCur_Str	varchar(8000),
		@varKSADDTYPE	varchar(100),
		@varKScResCode	varchar(100),
		@varKSOLDPartNum int,
		@varKSRefDict	varchar(30),
		@varKSRefField	varchar(30),
		@varKSObjectName	varchar(254)

	DECLARE 
		@varKSpartParams	varchar(8000),
		@varKSpartTest	varchar(8000),
		@varKSpartDiction	varchar(8000),
		@varKSpartDictionApp	varchar(8000),
		@varKSpartDictionRef	varchar(8000),
		@varKSpartDictionDep	varchar(8000),
		@varKSpartDictionSubdivHead	varchar(8000),
		@varKSSaveMethod		varchar(8000),
		@varKSchrCodeType	varchar(100),
		@varKSchrNameType	varchar(100),
		@varKSchrCodeName	varchar(100),
		@varKSchrNameName	varchar(100)


	SELECT @varKSnLink = LINK, @varKSObjectName = NAME FROM S_OBJECTS WHERE CODE = @varKScCode

PRINT '---------------'+@varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END
	Select @varKSType=NAME FROM S_OBJECTS WHERE CODE=@varKScCode
	print '('+@varKSType+')'

	DECLARE SEL_CURSOR CURSOR STATIC LOCAL
	FOR SELECT LINK, CODE, NAME
		FROM S_OBJECTS SO
		WHERE LINK_SELF=@varKSnLink AND (SELECT CODE FROM S_OBJECTS WHERE LINK=SO.LINK_CLASS)='EDIT_FIELD_CLASS'
		ORDER BY ORDERS

SET	@varKSpartParams		= ''
SET	@varKSpartTest	= ''
SET	@varKSpartDictionApp	= ''
SET	@varKSpartDictionRef	= ''
SET	@varKSpartDictionDep	= ''
SET	@varKSpartDictionSubdivHead	= ''
SET	@varKSchrCodeType	= ''
SET	@varKSchrNameType	= ''
SET	@varKSchrCodeName	= ''
SET	@varKSchrNameName	= ''
SET	@varKSSaveMethod		= ''
	SET @varKSSel_Str=
'
/*
© Кейсистемс (Keysystems), 2005
*/
--Процедура сформирована с помощью X_FORM_SAVE_DICTIONARY (Сергеев С.Н.)
--'+LTRIM(convert(char, getdate()))+'
PROCEDURE dbo.X_SAVE_'+@varKScCode
	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSCurNAME
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @varKSCurNAME = RTRIM(@varKSCurNAME)
		EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		IF Convert(int, @varKSInALIAS)&1 = 1 AND @varKSStorage IN ('DICTION_APP', 'DICTION_REF', 'DICTION', 'Z_DICT_OPER', 'S_PERIOD', 'S_ACCOUNTS', 'PAYS_DICTION', 'DICTION_KLADR', 'DICTION_DEP', 'DICTION_TAB', 'SUBDIV_HEAD')
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSRefField OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TYPE_FIELD_DICT', @varKSType OUTPUT
			SET @varKSType = UPPER(LTRIM(RTRIM(@varKSType)))
			IF @varKSType='DATETIME'
				SET @varKSADDTYPE=',104'
			ELSE
				SET @varKSADDTYPE=''

DECLARE	@varKSCNE	varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT

			SET @varKSINFO=convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

			PRINT convert(char(30), @varKSShortCode)+convert(char(30), @varKSType)+@varKSINFO
		
			IF 
				@varKSStorage='DICTION' OR 
				(@varKSStorage ='DICTION_APP' AND @varKSRefDict = '') 
				OR (@varKSStorage = 'DICTION_REF' AND @varKSRefField='LINK') 
				OR (@varKSStorage = 'Z_DICT_OPER' AND @varKSRefField='OPER') 
				OR (@varKSStorage = 'S_PERIOD' AND @varKSRefField='PERIOD')
				OR (@varKSStorage = 'S_ACCOUNTS' AND @varKSRefField='LINK') 
				OR (@varKSStorage = 'PAYS_DICTION' AND @varKSRefField='LINK') 
				OR (@varKSStorage = 'DICTION_KLADR' AND @varKSRefField='LINK')
				OR (@varKSStorage = 'DICTION_DEP' AND @varKSRefField='LINK') 
				OR (@varKSStorage = 'SUBDIV_HEAD' AND @varKSRefField='LINK') 
				OR (@varKSStorage = 'DICTION_TAB' AND @varKSRefField='LINK')
			BEGIN
				IF @varKSShortCode is null or @varKSShortCode = ''
					print 'SHORTCODE не определено!!!'
				IF @varKSType is null or @varKSType = ''
					IF 
						@varKSStorage = 'DICTION_REF' AND @varKSRefField='LINK' 
						OR @varKSStorage = 'Z_DICT_OPER' AND @varKSRefField='OPER' 
						OR @varKSStorage = 'S_PERIOD' AND @varKSRefField='PERIOD'
						OR (@varKSStorage = 'S_ACCOUNTS' AND @varKSRefField='LINK')
						OR @varKSStorage = 'PAYS_DICTION' AND @varKSRefField='LINK'
						OR (@varKSStorage = 'DICTION_KLADR' AND @varKSRefField='LINK')
						OR (@varKSStorage = 'SUBDIV_HEAD' AND @varKSRefField='LINK') 
						OR (@varKSStorage = 'DICTION_DEP' AND @varKSRefField='LINK') 
						OR (@varKSStorage = 'DICTION_TAB' AND @varKSRefField='LINK')
						SET @varKSType = 'int'
					ELSE
						print 'TYPE_FIELD не определено!!!'
				SET @varKSpartParams = @varKSpartParams + ',' + CHAR(13) + CHAR(10) + '	@varKSpar' + @varKSShortCode + ISNULL(SPACE(15-LEN(@varKSShortCode)),'     ') + @varKSType + ' = null'
				SET @varKSOLDPartNum = FLOOR(LEN(@varKSSaveMethod)/200)
				IF 
					(@varKSStorage = 'DICTION_REF' AND @varKSRefField='LINK') 
					OR (@varKSStorage = 'Z_DICT_OPER' AND @varKSRefField='OPER')
					OR (@varKSStorage = 'S_PERIOD' AND @varKSRefField='PERIOD')
					OR (@varKSStorage = 'DICTION_APP' AND @varKSType = 'DATETIME')
					OR (@varKSStorage = 'S_ACCOUNTS' AND @varKSRefField='LINK')  
					OR (@varKSStorage = 'PAYS_DICTION' AND @varKSRefField='LINK')
					OR (@varKSStorage = 'DICTION_KLADR' AND @varKSRefField='LINK')
					OR (@varKSStorage = 'DICTION_DEP' AND @varKSRefField='LINK') 
					OR (@varKSStorage = 'SUBDIV_HEAD' AND @varKSRefField='LINK') 
					OR (@varKSStorage = 'DICTION_TAB' AND @varKSRefField='LINK') 
					SET @varKSSaveMethod = @varKSSaveMethod + ', SQLNULL(' + @varKSShortCode + ')'
				ELSE
					SET @varKSSaveMethod = @varKSSaveMethod + ', ' + @varKSShortCode
				IF FLOOR(LEN(@varKSSaveMethod)/200) > @varKSOLDPartNum
					SET @varKSSaveMethod = @varKSSaveMethod + '"+"'

			END

			IF @varKSShortCode is null OR LTRIM(@varKSShortCode)=''
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			ELSE
			BEGIN
				IF @varKSStorage='DICTION_APP' AND @varKSRefDict=''
					SET @varKSpartDictionApp = @varKSpartDictionApp + 
'
	--'+@varKSCurNAME+'
	SET @varKSstrVALUE = Convert(varchar(7000), @varKSpar' + @varKSShortCode + @varKSADDTYPE + ')
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_APP @varKSparLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSstrVALUE
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'DICTION_REF' AND @varKSRefField='LINK'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_REF @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'Z_DICT_OPER' AND @varKSRefField='OPER'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_Z_DICT_OPER @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'S_PERIOD' AND @varKSRefField='PERIOD'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_Z_DICTION_PERIOD @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
			
				IF @varKSStorage = 'S_ACCOUNTS' AND @varKSRefField='LINK' 
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	-- ACCOUNTS - '+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.KM_UPDATE_DIC_ACCOUNTS @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

				IF @varKSStorage = 'PAYS_DICTION' AND @varKSRefField='LINK'

					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	if @varKSpar' + @varKSShortCode + ' is not null begin
		EXECUTE @varKSERROR = X_UPDATE_PAYS_DICTION @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
		IF @varKSERROR <> 0
			RETURN @varKSERROR
	end

	else begin
		delete from pays_diction where LINK_DICTION = @varKSparLINK
	end
'
				IF @varKSStorage = 'DICTION_KLADR' AND @varKSRefField='LINK'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_KLADR @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

				IF @varKSStorage = 'DICTION_DEP' AND @varKSRefField='LINK'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_DEP @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

				IF @varKSStorage = 'SUBDIV_HEAD' AND @varKSRefField='LINK'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_SUBDIV_HEAD @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

				IF @varKSStorage = 'DICTION_TAB' AND @varKSRefField='LINK'
					SET @varKSpartDictionRef = @varKSpartDictionRef +
'
	--'+@varKSCurNAME+'
	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION_TAB @varKSparLINK, @varKSpar' + @varKSShortCode + ', '+LTRIM(STR(@varKSCurLINK))+'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'


				IF @varKSStorage = 'DICTION' AND (@varKSRefField='CODE')
				BEGIN
					SET @varKSchrCodeName = @varKSShortCode
					SET @varKSchrCodeType = @varKSType
				END
				IF @varKSStorage = 'DICTION' AND (@varKSRefField='NAME')
				BEGIN
					SET @varKSchrNameName = @varKSShortCode
					SET @varKSchrNameType = @varKSType
				END
			END
		END
			
			IF Convert(int, @varKSInALIAS)&2 = 2 AND (@varKSStorage='DICTION' OR (@varKSStorage ='DICTION_APP' AND @varKSRefDict = '') OR (@varKSStorage = 'DICTION_REF' AND @varKSRefField='LINK') OR (@varKSStorage = 'Z_DICT_OPER' AND @varKSRefField='OPER') OR (@varKSStorage = 'S_PERIOD' AND @varKSRefField='PERIOD')
				OR (@varKSStorage = 'S_ACCOUNTS' AND @varKSRefField='LINK'))
			BEGIN
				SET @varKSpartTest = @varKSpartTest + '	IF @varKSpar' + @varKSShortCode + ' IS NULL'
				IF @varKSStorage IN( 'DICTION_REF', 'DICTION_KLADR', 'PAYS_DICTION', 'DICTION_DEP', 'DICTION_TAB')
					SET @varKSpartTest = @varKSpartTest + ' OR @varKSpar' + @varKSShortCode + ' = 0'
				ELSE
				BEGIN
					SET @varKSpartTest = @varKSpartTest + 
					CASE 
					WHEN LEFT(@varKSType, 7) = 'NUMERIC'
					  THEN ' OR @varKSpar' + @varKSShortCode	+ ' = 0.0'
					WHEN @varKSType = 'DATETIME'
					  THEN ' OR @varKSpar' + @varKSShortCode	+ ' = ''19000101'''
					WHEN @varKSType IN ('INT', 'TINYINT', 'BIGINT', 'SMALLINT', 'MONEY', 'SMALLMONEY')
					  THEN ' OR @varKSpar' + @varKSShortCode	+ ' = 0'
					WHEN LEFT(@varKSType, 7) = 'VARCHAR' OR LEFT(@varKSType, 4) = 'CHAR'
					  THEN ' OR @varKSpar' + @varKSShortCode	+ ' = '''''
					END
				END
				SET @varKSpartTest = @varKSpartTest + 
'
	BEGIN
		ROLLBACK
		RETURN 5
	END
'
			END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSCurNAME
	END
	

	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR

	
	SET @varKScResCode = 'X_SAVE_' + @varKScCode
	IF object_id(@varKScResCode) is not null
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str

	SET @varKSSel_Str = @varKSSel_Str +
'
	@varKSparLINK	int	OUTPUT'
	IF @varKSchrCodeType<>''
	BEGIN
		SET @varKSSel_Str = @varKSSel_Str 
	END
	SET @varKSSel_Str = @varKSSel_Str + @varKSpartParams + 
'
AS
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,
		@varKSEventText	varchar(254)
SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
'
+CASE WHEN @varKSchrCodeType<>'' AND @varKSTestCode = 1 AND @varKScCode <> 'DICTIONARY_CHIN' THEN
'	--Проверка кода на уникальность
	EXECUTE @varKSERROR = X_TEST_DICTION_CODE @varKSparLINK, ' + LTRIM(STR(@varKSnLink)) + ', @varKSpar' + @varKSchrCodeName + '
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
	ELSE ''
	END + 
'	--Проверка обязательных реквизитов
'+	@varKSpartTest +
'	--Вставка в DICTION
'+
	CASE WHEN @varKScCode <> @varKShostCode THEN '' ELSE 
'	EXECUTE @varKSERROR = dbo.X_UPDATE_DICTION @varKSparLINK OUTPUT, ' + LTRIM(STR(@varKSnLink)) + ', '+
		CASE WHEN @varKSchrCodeType<>'' THEN '@varKSpar'+@varKSchrCodeName ELSE 'NULL' END +','+
		CASE WHEN @varKSchrNameType<>'' THEN '@varKSpar'+@varKSchrNameName ELSE 'NULL' END +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
END +
'
	--Вставка в DICTION_APP'
 + @varKSpartDictionApp +
'
	--Вставка в DICTION_REF и прочие ссылки'
 + @varKSpartDictionRef +
'
	--Отражение в системном журнале

	SET @varKSEventText = '''+RTRIM(@varKSObjectName)+''' + '' '' + '+
		CASE WHEN @varKSchrCodeType<>'' THEN ' RTRIM(CONVERT(VARCHAR(50),@varKSpar'+@varKSchrCodeName+'))' ELSE 'NULL' END +'+'' ''+'+
		CASE WHEN @varKSchrNameType<>'' THEN ' RTRIM(CONVERT(VARCHAR(7000), @varKSpar'+@varKSchrNameName + '))' ELSE 'NULL' END +'
	EXECUTE dbo.WF_GENERATEEVENT ''Сохранение строки справочника'', @varKSEventText, ' + LTRIM(STR(@varKSnLink)) + ', ''DICTION'', @varKSparLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0
'
	
	
	EXECUTE (@varKSSel_Str)
	DECLARE @varKSprocname varchar(254), @varKSmakeby varchar(254)
	SELECT @varKSprocname = 'X_SAVE_'+@varKScCode, @varKSmakeby = 'EXECUTE dbo.X_FORM_SAVE_DICTIONARY ''' + @varKScCode+''', '+case when @varKShostCode is null then 'null, ' else ''''+@varKShostCode+''', ' end + convert(varchar, @varKSTestCode)
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKSprocname, @varKSmakeby

	


	SET @varKSSaveMethod = SUBSTRING(@varKSSaveMethod, 2, 1000)
	UPDATE OBJECT_VALUES
	SET VALUE = 'X_SAVE(''X_SAVE_'+@varKScCode+''', m.cAlias,"'+@varKSSaveMethod+'"' + ',"'+@varKScCode+'")',
		INHERITED = 0
	WHERE OBJECT = @varKSnLink
			AND PROPERTY = (SELECT LINK FROM S_PROPERTY WHERE CODE = 'SAVE_OBJECT_METHOD')
			AND (VALUE IS NULL OR VALUE = '')

	UPDATE S_DBObjects SET Rights = 0xA WHERE Object=@varKSnLink AND DBObject=@varKScResCode
	IF @@ROWCOUNT = 0	
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScResCode, 0xA)
	IF object_id('X_DELETE_'+@varKScCode) is null AND @varKSWithDel = 1
	BEGIN
		SET @varKSSel_Str = 
'CREATE PROCEDURE dbo.X_DELETE_'+@varKScCode+'
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = '''+RTRIM(@varKSObjectName)+''' + '' '' + CODE + '' '' + NAME FROM dbo.DICTION WITH (UPDLOCK) WHERE LINK = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.DICTION WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = '''+@varKScCode+'''
		EXECUTE dbo.WF_GENERATEEVENT ''Удаление из справочника'', @varKSEventText, @varKSObjectLink, ''DICTION'', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0'
		EXECUTE(@varKSSel_Str)
		
		
		SET @varKScResCode = 'X_DELETE_'+@varKScCode
		UPDATE S_DBObjects SET Rights = 0x10 WHERE Object=@varKSnLink AND DBObject=@varKScResCode
		IF @@ROWCOUNT = 0	
			INSERT INTO S_DBObjects(Object, DBObject, Rights)
				VALUES (@varKSnLink, @varKScResCode, 0x10)
	END
END

GO


GRANT EXECUTE ON dbo.[X_FORM_SAVE_DICTIONARY] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_FORM_33]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_FORM_33]
END
GO
/*******************************************************************************

	© Кейсистемс (Keysystems), 2011

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RO_EXPORT_FORM_33]
	@iLINK_SAVED_FORM INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

DECLARE @vcExec VARCHAR(8000), @vcNameFileArh VARCHAR(1000), @vcFILE_NAME1 varchar(1000), @vcNameFileArh1 VARCHAR(1000), @vcVidFO VARCHAR(10), @vcPostFix VARCHAR(10), @vcExportCode VARCHAR(30),
   @vcCodeForm VARCHAR(100), @iLinkOrg INT, @vcCB VARCHAR(1000), @vcFIO VARCHAR(1000), @vcPost VARCHAR(1000), @iLSF INT 

DECLARE @tabFileExport TABLE ([TXT]	        VARCHAR(800), 
							         [NAMEFILE]    VARCHAR(100), 
                              [NAMEFILEARH] VARCHAR(100),
							         [ORDERS]      INT IDENTITY(1,1))    
DECLARE @tabLSF TABLE([LINK_SAVED_FORM] INT)                              
SET NOCOUNT ON

DECLARE @tPERIODIC      TINYINT,
        @tPERIOD_TYPE   TINYINT,
        @tPERIOD_NUMBER TINYINT,
        @bIsQuart       BIT

SELECT @vcCodeForm = rf.[Code],
       @iLinkOrg = rsf.[Link_Organization],
       @tPERIODIC = rf.[Periodic],
       @tPERIOD_TYPE = rsf.[Period_Type],
       @tPERIOD_NUMBER = rsf.[Period_Number]
FROM dbo.[REPORT_SAVED_FORMS] rsf
      JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rsf.[Link_Form]
WHERE rsf.[Link_Saved_Form] = @iLINK_SAVED_FORM

SET @bIsQuart = CASE 
                   WHEN @tPERIOD_TYPE = 4 AND @tPERIOD_NUMBER % 3 = 0 THEN 1
                   ELSE 0
                END

SELECT @vcCB = RTRIM(r.[cb_name])  
               + CASE WHEN r.[cb_ogrn] = '' THEN '' ELSE ', ' + RTRIM(r.[cb_ogrn]) END
               + CASE WHEN r.[cb_inn] = '' THEN '' ELSE ', ' + RTRIM(r.[cb_inn]) END
               + CASE WHEN r.[cb_kpp] = '' THEN '' ELSE ', ' + RTRIM(r.[cb_kpp]) END
               + CASE WHEN r.[cb_address] = '' THEN '' ELSE ', ' + RTRIM(r.[cb_address]) END,
       @vcFIO = r.[ul_fio],
       @vcPost = r.[ul_post]
FROM dbo.[RT_VIEW_WEB_BOSS] r
WHERE r.[link] = @iLinkOrg      

EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          



IF @iMODE = 2
BEGIN  
   IF @bIsQuart = 1 
   BEGIN
      SET @vcFILE_NAME = REPLACE(@vcFILE_NAME,'M','Q')
            
      UPDATE #FileExportReport
      SET TXT = 'ПРД=4'
      WHERE TXT = 'ПРД=3'
   END

   UPDATE #FileExportReport
   SET TXT = 'ИСТ=' + RIGHT('0' + LTRIM(RTRIM(dbo.[RA_GETWORDNUM](TXT, 2, '='))),3)
   WHERE TXT LIKE 'ИСТ=%'
   
   set @vcVidFO = isnull(dbo.RN_GET_ATR_VALUE(@iLINK_SAVED_FORM,'REPORTS_ATR_VID'),'')
   
   SET @vcPostFix = CASE @vcVidFO WHEN '2' THEN 'd'
                                 WHEN '3' THEN 't'
                                 WHEN '4' THEN 'z'
                                 WHEN '5' THEN 'c'
                                 WHEN '6' THEN 'i'
                                 WHEN '7' THEN 'm'
                                 ELSE '' END   

   IF (@vcPostFix = 't' and LEFT(@vcCodeForm, 7) IN ('0503737')) 
         OR (@vcPostFix IN ('t') and LEFT(@vcCodeForm, 7) IN ('0503768'))
   BEGIN
      IF OBJECT_ID('tempdb..#tabExportLog') IS NOT NULL
      BEGIN 
         INSERT #tabExportLog([TXT])
         SELECT 'Для формы ' + RTRIM(@vcCodeForm) + ' не может быть указан вид финансового обеспечения с кодом ' + @vcVidFO

         INSERT #tabExportLog([TXT])
         SELECT 'Выгрузка отменена'
      END 
      RETURN -1
   END 

   SELECT TOP 1  @vcNameFileArh = [NameFileArh]
   FROM #FileExportReport
   
   IF @bIsQuart = 1 
   BEGIN
      SET @vcNameFileArh = REPLACE(@vcNameFileArh,'M','Q')      
   END

   SELECT @vcFILE_NAME = REPLACE(@vcFILE_NAME, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
         @vcNameFileArh = REPLACE(SUBSTRING(@vcNameFileArh, 2, 17) + 'F_' + SUBSTRING(@vcNameFileArh,19,10), RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
         @vcExportCode = RTRIM(rf.[ExportCode])
   FROM dbo.[REPORT_SAVED_FORMS] rsf
         JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rsf.[Link_Saved_Form] =  @iLINK_SAVED_FORM
   
   UPDATE #FileExportReport
   SET [NameFile] = @vcFILE_NAME,
         [NameFileArh] = @vcNameFileArh

   UPDATE #FileExportReport
   SET [TXT] = REPLACE([TXT], @vcExportCode, @vcExportCode + @vcPostFix)
   WHERE TXT LIKE 'КОДФ=%'        

   IF LEFT(@vcCodeForm, 7) IN ('0503730', '0503830')
   BEGIN
      UPDATE #FileExportReport
      SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
      WHERE TXT = 'ТБ=02'      

      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                           AND orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                           AND [TXT] > '470|')       

   END   
   
   IF LEFT(@vcCodeForm, 7) IN ('0503773', '0503779')
   BEGIN
      set @vcVidFO = isnull(dbo.RN_GET_ATR_VALUE(@iLINK_SAVED_FORM,'REPORTS_ATR_VID_773'),'')
      set @vcPostFix = @vcVidFO

      SELECT @vcFILE_NAME = REPLACE(@vcFILE_NAME, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
            @vcNameFileArh = REPLACE(LEFT(@vcNameFileArh, 17) + 'F_' + SUBSTRING(@vcNameFileArh,20,10), RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
            @vcExportCode = RTRIM(rf.[ExportCode])
      FROM dbo.[REPORT_SAVED_FORMS] rsf
            JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rsf.[Link_Form]
      WHERE rsf.[Link_Saved_Form] =  @iLINK_SAVED_FORM
      
      UPDATE #FileExportReport
      SET [NameFile] = @vcFILE_NAME,
            [NameFileArh] = @vcNameFileArh

      UPDATE #FileExportReport
      SET [TXT] = REPLACE([TXT], @vcExportCode, @vcExportCode + @vcPostFix)
      WHERE TXT LIKE 'КОДФ=%'        
   END 

   IF LEFT(@vcCodeForm, 7) IN ('0503773')
   BEGIN
/*      
      --SELECT * FROM #FileExportReport
      SELECT [TXT],[ORDERS]
      INTO #tab773
      FROM #FileExportReport
      WHERE [ORDERS] <= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = 'ТБ=02') + 1
                        
      DELETE #FileExportReport
      FROM #FileExportReport
      WHERE [ORDERS] <= (SELECT [ORDERS]
                         FROM #FileExportReport
                         WHERE [TXT] = 'ТБ=02') + 1
      
      INSERT #FileExportReport([TXT])
      SELECT [TXT]
      FROM #tab773    
      WHERE orders = (SELECT MIN(orders)
                      FROM #tab773
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                           AND orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                           AND [TXT] > '470|')
      ORDER BY [ORDERS]
*/                            
      
      UPDATE #FileExportReport
      SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
      WHERE TXT = 'ТБ=02'      

      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                           AND orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                           AND [TXT] > '470|')
      IF @@ROWCOUNT = 0
      BEGIN
         UPDATE #FileExportReport
         SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
         WHERE [ORDERS] = (SELECT [ORDERS]
                           FROM #FileExportReport
                           WHERE TXT = 'ТБ=03') - 2 
      END
                           
      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=04<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                           AND [TXT] > '0|3'
                           AND [TXT] NOT LIKE '8|8%' ) - 1
           AND TXT LIKE '*|***%'                
                                  

      IF @@ROWCOUNT = 0
      BEGIN 
         UPDATE #FileExportReport
         SET [TXT] = '#<LN>#@<LN>ТБ=04<LN>#$<LN>' + [TXT]
         WHERE orders = (SELECT MIN(orders)
                         FROM #FileExportReport
                        WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
                              AND [TXT] > '0|3'
                              AND [TXT] NOT LIKE '8|8%' ) - 2       
      END 

      UPDATE  #FileExportReport
      SET TXT = REPLACE(TXT, '|-|-|', '|***|********|')
      WHERE RTRIM(TXT) LIKE '%|-|-|%|-|'                                   
                                  
   END    
    

--   IF LEFT(@vcCodeForm, 7) IN ('0503772')
--   BEGIN
--      UPDATE #FileExportReport
--      SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
--      WHERE TXT = 'ТБ=02'      
--
--      UPDATE #FileExportReport
--      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
--      WHERE orders = (SELECT MIN(orders)
--                      FROM #FileExportReport
--                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
--                           AND orders < (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=03')
--                           AND [TXT] > '470|')       
--   END    

   IF LEFT(@vcCodeForm, 7) IN ('0503771')
   BEGIN
            
      INSERT #FileExportReport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH], [ORDERS])
      SELECT  REPLACE([TXT], '#<LN>#@<LN>ТБ=02<LN>#$<LN>#<LN>#@<LN>ТБ=03<LN>#$<LN>***|**************|*|*****|***|', '***|****|*******|***|*|*****|***|'),
		        [NAMEFILE], 
              [NAMEFILEARH],
              [ORDERS] - 1
      FROM #FileExportReport
      WHERE TXT LIKE '#<LN>#@<LN>ТБ=02<LN>#$<LN>#<LN>#@<LN>ТБ=03<LN>#$<LN>***|**************|*|*****|***|%'

      
      UPDATE #FileExportReport
      SET [TXT] = REPLACE(REPLACE([TXT], '|000|', '|***|'),'000|0000|0000000|', '***|****|*******|')
      WHERE RTRIM(TXT) LIKE '%|000|%|-|-|000'

      UPDATE #FileExportReport
      SET [TXT] = LEFT([TXT],LEN([TXT])-CHARINDEX('|',REVERSE([TXT]))+1)
      WHERE [TXT] LIKE '%|%'

   END    


   IF LEFT(@vcCodeForm, 7) IN ('0503768')
   BEGIN
      UPDATE #FileExportReport
      SET [TXT] = REPLACE([TXT], 'ТБ=02', 'ТБ=03')
      WHERE TXT = 'ТБ=02'      

      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                            AND dbo.[RA_GETWORDNUM]([TXT],4, '|') > '250' and LEN(dbo.[RA_GETWORDNUM]([TXT],1, '|'))=1)
      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=03<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] LIKE  '#<LN>#@<LN>ТБ=02<LN>#$<LN>%')
                            AND LEFT([TXT],6) >= '01|450')       
                                   
                                   
   END
   
   IF LEFT(@vcCodeForm, 7) IN ('0503737')
   BEGIN
      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=02<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] = 'ТБ=01')
                            AND LEFT([TXT],3) > '104')

        

      UPDATE #FileExportReport
      SET [TXT] = '#<LN>#@<LN>ТБ=03<LN>#$<LN>' + [TXT]
      WHERE orders = (SELECT MIN(orders)
                      FROM #FileExportReport
                     WHERE orders > (SELECT orders FROM  #FileExportReport WHERE [TXT] LIKE  '#<LN>#@<LN>ТБ=02<LN>#$<LN>%')
                            AND LEFT([TXT],3) > '450')       
                                   
   END
   
   IF LEFT(@vcCodeForm, 7) IN ('0503769')
   BEGIN
      UPDATE #FileExportReport
      SET TXT = LEFT(TXT,22) + @vcVidFO + '|' +  REPLACE(SUBSTRING(TXT,23, 8000), '|0000|', '|****|')
      WHERE TXT LIKE '%|%|%' AND TXT NOT LIKE '%|88888|888%'
      
      DELETE #FileExportReport
      WHERE TXT LIKE '%|88888|888%'
            AND orders > (SELECT MAX(orders) FROM #FileExportReport WHERE TXT = 'ТБ=02')
            AND orders < (SELECT MAX(orders) FROM #FileExportReport WHERE TXT = 'ТБ=04')

      -- удаление строк итого по счету
       DELETE #FileExportReport
       WHERE LEFT(TXT,1)='2'


       UPDATE #FileExportReport
       SET TXT = REPLACE(REPLACE(REPLACE(TXT, '|88888|888', '|*|*****|***'), '|000|00000000000000|', '|***|**************|'),  '|0000|', '|****|')
       WHERE TXT LIKE '%|88888|888%'
      
     
       DELETE #FileExportReport
       WHERE TXT IN ('#', '#@', '#$', 'ТБ=02', 'ТБ=03', 'ТБ=04', 'ТБ=05')
           AND orders >= (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = '#' AND orders > (SELECT MIN(orders) FROM #FileExportReport WHERE TXT = 'ТБ=01'))
            AND orders < (SELECT MAX(orders) FROM #FileExportReport WHERE TXT = '#&') - 1

      -- добавляем итогов по счету
      INSERT #FileExportReport([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH], [ORDERS])
      SELECT '2'+SUBSTRING([txt],2,1)+'|***|**************|'+SUBSTRING(txt,23,17)+dbo.RN_GETWORDNUM([TXT],8,'|')+'|'+dbo.RN_GETWORDNUM([TXT],9,'|')+'|-|-|',
       [NAMEFILE], 
       [NAMEFILEARH],
       [ORDERS] 
      FROM #FileExportReport
      WHERE LEFT(TXT,1)='1'                                        

   END         

   IF LEFT(@vcCodeForm, 7) IN ('0503779')
   BEGIN
      UPDATE #FileExportReport
      SET TXT = REPLACE(TXT, '@a@', @vcVidFO)
      WHERE TXT LIKE '%|%' AND TXT NOT LIKE '88888888888888888888888888|%'

      UPDATE #FileExportReport
      SET TXT = REPLACE(TXT, '8|88888|888|', '*|*****|***|')
      WHERE TXT LIKE '8|88888|888|%'
   END       

   IF LEFT(@vcCodeForm, 7) IN ('0503772')
   BEGIN
      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  [TXT], 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders <= (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#$') 
      ORDER BY orders        

	  DECLARE @iOrder9 INT 
	  SELECT @iOrder9 = MAX(orders) FROM #FileExportReport WHERE [TXT] like '9|99999|999|%'

      --99999 может в форме не быть	
	  IF @iOrder9 IS NULL
		SELECT @iOrder9 = Min(orders) FROM #FileExportReport WHERE [TXT] ='#'


      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  [TXT], 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders > (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#$')
            AND TXT NOT LIKE '0|00011|000|%'
            AND TXT NOT LIKE '8|88888|888|%'
            AND orders <= @iOrder9
      ORDER BY orders
		
      UPDATE   @tabFileExport
      SET TXT = '000|0000|0000000|000|' + TXT
      WHERE TXT LIKE '%|%'

     
      UPDATE @tabFileExport
      SET TXT = REPLACE(REPLACE(REPLACE(TXT, '000|0000|0000000|000|', '***|****|*******|***|'), '|000|', '|***|'), '9|99999|999|', '*|*****|***|')
      WHERE RTRIM(TXT) LIKE '%|-|-|-|-|-|' AND SUBSTRING(TXT, 30, 3) in ('***', '999')

      
      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  TOP 1 '#<LN>#@<LN>ТБ=02<LN>#$<LN>#<LN>#@<LN>ТБ=03<LN>#$', 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport              

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  REPLACE([TXT], '0|00011|000|', '11|'), 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders > (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#$')
            AND TXT LIKE '0|00011|000|%'  
            AND orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')  
      ORDER BY orders  

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  REPLACE([TXT], '0|00011|000|', '**|'), 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders > (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#$')
            AND TXT LIKE '0|00011|000|%'  
            AND orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')  
      ORDER BY orders  
      

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  TOP 1 '#<LN>#@<LN>ТБ=04<LN>#$', 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport     

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  '***|**************|' + REPLACE([TXT], '8|88888|888|', '*|*****|***|'), 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders > (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#$')
            AND TXT LIKE '8|88888|888|%'  
            AND orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')  
      ORDER BY orders 

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  TOP 1 '#', 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport


      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  [TXT], 
		        [NAMEFILE], 
              [NAMEFILEARH]
      FROM #FileExportReport
      WHERE orders >= (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')  
      ORDER BY orders
      
      TRUNCATE TABLE #FileExportReport
      
      INSERT #FileExportReport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH], [ORDERS])
      SELECT  [TXT], 
		        [NAMEFILE], 
              [NAMEFILEARH],
              [ORDERS]
      FROM @tabFileExport
      ORDER BY orders


   END 

   IF LEFT(@vcCodeForm, 7) IN ('0503725')
   BEGIN
      INSERT @tabLSF([LINK_SAVED_FORM])
      SELECT [LINK]
      FROM dbo.[BufferGetTableByID]('REPORT_ATR_EXPORT')

      EXEC dbo.[BufferClear] 'REPORT_ATR_EXPORT'      
      
      IF ISNULL((SELECT COUNT(*) FROM @tabLSF),0) = 0
      BEGIN
         CREATE TABLE #tabLSF([ATR]             VARCHAR(8000),
                              [LINK_SAVED_FORM] INT)
         
         INSERT #tabLSF([ATR],
                        [LINK_SAVED_FORM])
         EXEC dbo.[RA_EXPORT_FORM_LIST_ATR] @iLINK_SAVED_FORM
         
         INSERT @tabLSF([LINK_SAVED_FORM])
         SELECT [LINK_SAVED_FORM]
         FROM #tabLSF
         
         DROP TABLE #tabLSF
      END 

      SET @vcVidFO = LEFT(isnull(dbo.RN_GET_ATR_VALUE(@iLINK_SAVED_FORM,'REPORTS_ATR_ACC_725'),''),1)
      SET @vcPostFix = CASE @vcVidFO WHEN '2' THEN 'd'
                                    WHEN '3' THEN 't'
                                    WHEN '4' THEN 'z'
                                    WHEN '5' THEN 'c'
                                    WHEN '6' THEN 'i'
                                    WHEN '7' THEN 'm'
                                    ELSE '' END
                                    
      SELECT @vcFILE_NAME1 = REPLACE(@vcFILE_NAME, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
            @vcNameFileArh1 = REPLACE(@vcNameFileArh, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
            @vcExportCode = RTRIM(rf.[ExportCode])
      FROM dbo.[REPORT_SAVED_FORMS] rsf
            JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rsf.[Link_Form]
      WHERE rsf.[Link_Saved_Form] =  @iLINK_SAVED_FORM                                       

      INSERT @tabFileExport ([TXT], 
							         [NAMEFILE], 
                              [NAMEFILEARH])
      SELECT  [TXT], 
		        @vcFILE_NAME1, 
              @vcNameFileArh1
      FROM #FileExportReport
      WHERE orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&') 
      ORDER BY orders       
      
      UPDATE @tabFileExport
      SET [TXT] = REPLACE([TXT], @vcExportCode, @vcExportCode + @vcPostFix)
      WHERE TXT LIKE 'КОДФ=%'      
      
      
      DECLARE curLSF CURSOR LOCAL STATIC FOR
	      SELECT [LINK_SAVED_FORM]
	      FROM @tabLSF
         WHERE [LINK_SAVED_FORM] <> @iLINK_SAVED_FORM
      OPEN curLSF

      FETCH NEXT FROM curLSF INTO @iLSF
      WHILE @@FETCH_STATUS = 0
      BEGIN
         TRUNCATE TABLE #FileExportReport
         EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLSF,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE 

         SET @vcVidFO = LEFT(isnull(dbo.RN_GET_ATR_VALUE(@iLSF,'REPORTS_ATR_ACC_725'),''),1)
         SET @vcPostFix = CASE @vcVidFO WHEN '2' THEN 'd'
                                       WHEN '3' THEN 't'
                                       WHEN '4' THEN 'z'
                                       WHEN '5' THEN 'c'
                                       WHEN '6' THEN 'i'
                                       WHEN '7' THEN 'm'
                                       ELSE '' END
                                       
         SELECT @vcFILE_NAME1 = REPLACE(@vcFILE_NAME, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
               @vcNameFileArh1 = REPLACE(@vcNameFileArh, RTRIM(rf.[ExportCode]),  RTRIM(rf.[ExportCode]) + @vcPostFix),
               @vcExportCode = RTRIM(rf.[ExportCode])
         FROM dbo.[REPORT_SAVED_FORMS] rsf
               JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rsf.[Link_Form]
         WHERE rsf.[Link_Saved_Form] =  @iLSF                                      

         IF EXISTS(SELECT * FROM @tabFileExport WHERE [NAMEFILE] =  @vcFILE_NAME1)
         BEGIN                        
            INSERT @tabFileExport ([TXT], 
							               [NAMEFILE], 
                                    [NAMEFILEARH])
            SELECT TOP 1 '#%',@vcFILE_NAME1, 
                                    @vcNameFileArh1
            FROM #FileExportReport                                                                       
            
            INSERT @tabFileExport ([TXT], 
							               [NAMEFILE], 
                                    [NAMEFILEARH])
            SELECT  [TXT], 
		              @vcFILE_NAME1, 
                    @vcNameFileArh1
            FROM #FileExportReport
            WHERE orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')
                  and orders >= (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] LIKE  'ОКАТО=%') 
            ORDER BY orders
         END
         ELSE BEGIN

            UPDATE #FileExportReport
            SET [TXT] = REPLACE([TXT], @vcExportCode, @vcExportCode + @vcPostFix)
            WHERE TXT LIKE 'КОДФ=%'      

            INSERT @tabFileExport ([TXT], 
							               [NAMEFILE], 
                                    [NAMEFILEARH])
            SELECT  [TXT], 
		              @vcFILE_NAME1, 
                    @vcNameFileArh1
            FROM #FileExportReport
            WHERE orders < (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')
            ORDER BY orders
         END    
                    
                                   
         FETCH NEXT FROM curLSF INTO @iLSF
      END     

 --не работает в 2008      
--      INSERT @tabFileExport ([TXT], 
--						            [NAMEFILE], 
--                              [NAMEFILEARH])
--      SELECT  [TXT], 
--	           T.[NAMEFILE], 
--              T.[NAMEFILEARH]
--      FROM #FileExportReport
--            JOIN (SELECT DISTINCT [NAMEFILE], [NAMEFILEARH] from @tabFileExport) T ON 1=1
--      WHERE orders >= (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')
--      ORDER BY orders
      
      DECLARE cur cursor LOCAL STATIC 
      FOR  SELECT DISTINCT [NAMEFILE], [NAMEFILEARH] from @tabFileExport
      
      OPEN cur
      FETCH NEXT FROM cur INTO @vcFILE_NAME1, @vcNameFileArh1
      
      WHILE @@FETCH_STATUS = 0
      BEGIN

         INSERT @tabFileExport ([TXT], 
						               [NAMEFILE], 
                                 [NAMEFILEARH])
         SELECT  [TXT], 
	              @vcFILE_NAME1, 
                 @vcNameFileArh1
         FROM #FileExportReport
         WHERE orders >= (SELECT MAX(orders) FROM #FileExportReport WHERE [TXT] = '#&')
         ORDER BY orders

         FETCH NEXT FROM cur INTO @vcFILE_NAME1, @vcNameFileArh1
      END            
      
      CLOSE cur
      DEALLOCATE cur 
      
      TRUNCATE TABLE  #FileExportReport   

      INSERT #FileExportReport ([TXT], 
						            [NAMEFILE], 
                              [NAMEFILEARH], [ORDERS])
      SELECT  [TXT], 
	           [NAMEFILE], 
              [NAMEFILEARH], [ORDERS]
      FROM @tabFileExport
      ORDER BY orders   
      
   END   

   UPDATE #FileExportReport
   SET [TXT] = REPLACE(TXT, '|0.00|', '|0|')
   WHERE [TXT] LIKE '%|0.00|%' 

   UPDATE #FileExportReport
   SET [TXT] = REPLACE(TXT, '|0.00|', '|0|')
   WHERE [TXT] LIKE '%|0.00|%' 

   UPDATE #FileExportReport
   SET [TXT] = 'Центр.бух.=' + ISNULL(@vcCB, '') +'<LN>Руководитель=' + isnull(@vcFIO, '') + '<LN>Должность=' + isnull(@vcPost, '') + '<LN>' + [TXT]
   WHERE TXT LIKE 'Исполнитель=%' 
         AND orders > (SELECT MAX(orders) FROM #FileExportReport WHERE TXT = '#&')    
       
END



GO
GRANT ALL ON dbo.RO_EXPORT_FORM_33 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].[I_REPORT_SAVE_FORM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[I_REPORT_SAVE_FORM]
GO

/*
© Кейсистемс (Keysystems), 2005
*/
-- Ефимов В.Н. 13.03.2008 - доработка отметки событий в журнале: указывать и организацию

CREATE                       procedure dbo.I_REPORT_SAVE_FORM
	@varKSintLINK	int	OUTPUT,
	@varKSLinkF		int,
	@varKSVers		smallint = 0,
	@varKSBDAte		datetime = null,
	@varKSpTYPE		tinyint = 0,
	@varKSPNomber	tinyint = 0,
	@varKSLinkOrg	int,
	@varKSisSvod		tinyint = 0,
	@varKSIsChAnalit	bit = 0,
	@varKSLRazdel	int = null,
	@varKSLCelSt		int = null,
	@varKSLRashod	int = null,
	@varKSIsRO		tinyint = 0,
	@varKSNote	varchar(4000) = '',
	@varKSResetIsRightKS	bit  = 1, -- сбрасывать ли признак Правильности КС, по умолчанию: сбрасывать
	@varKSLinkTypeSvod	int = NULL,
	@varKSCountSave			int = 0,
	@varKSIsExam		bit = 0,
	@varKSNewReport		bit = 0,
	@varAtributs		varchar(500) = ''
AS
SELECT @varKSBDAte = ISNULL(dbo.[RA_GET_BEGIN_DATE](YEAR(@varKSBDAte),@varKSpTYPE,@varKSPNomber),@varKSBDAte)

declare @start_date datetime,@end_date datetime, @oldIsRO tinyint
select @start_date=start_date,@end_date=end_date from report_forms where link_form=@varKSLinkF
IF (@varKSBDAte<@START_DATE OR @varKSBDAte>ISNULL(@END_DATE,'29990101')) and year(@varKSBDAte)>=2009
	return 11001


IF @varKSLinkTypeSvod=0 OR @varKSLinkTypeSvod=-1
    set @varKSLinkTypeSvod=null


declare @IsRightKS int,
			@EMail varchar(254),
			@Subject varchar(254),
			@Body varchar(254),
			@Template varchar(8000)
select @IsRightKS = IsRightKS, @oldIsRO = IsRO from report_saved_forms where link_saved_form = @varKSintLINK

IF @varAtributs='' 
begin
    set @varAtributs=dbo.rn_get_atr_val(0,@varKSLinkF,1)
	if not(@varKSintLINK is null OR @varKSintLINK = 0)
		set @varAtributs=dbo.rn_get_atr_val(@varKSintLINK,0,1)
end

IF exists(select top 1 * from report_saved_forms RSF 
				where RSF.Link_Form = @varKSLinkF
               AND RSF.del = 0 
					and RSF.Period_Number = @varKSPNomber 
					and RSF.Period_Type = @varKSpTYPE 
					and RSF.Begin_Date = @varKSBDAte 
					and Link_Organization = @varKSLinkOrg 
					and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  
					and Link_Saved_Form <> isnull(@varKSintLINK,0) 
					and RSF.ATR_CODE = @varAtributs
					--and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs 
					and Version = @varKSVers)
			and not(@varKSintLINK is null OR @varKSintLINK = 0)
         AND (select top 1 NEW_REPORT from dbo.I_REPORT_OPTIONS_COMMON) = 0
BEGIN
  		select @varKSVers = max(version)+1 from report_saved_forms WHERE
            del = 0 AND 
				Link_Form=@varKSLinkF and
				Begin_Date=@varKSBDAte and
				Period_type=@varKSpTYPE and 
				Period_Number=@varKSPNomber and
				Link_Organization=@varKSLinkOrg and
				--IsSvod = @varKSisSvod and
				IsChangeAnalit = @varKSIsChAnalit and
				isnull(Link_Type_Svod, 0) = isnull(@varKSLinkTypeSvod, 0)
                and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs

END             

         

if @varKSNewReport = 0 
and (
		(
			exists(select top 1 * from report_saved_forms RSF 
				where RSF.Link_Form = @varKSLinkF
               AND RSF.del = 0 
					and RSF.Period_Number = @varKSPNomber 
					and RSF.Period_Type = @varKSpTYPE 
					and RSF.Begin_Date = @varKSBDAte 
					and Link_Organization = @varKSLinkOrg 
					and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  
					and Link_Saved_Form <> isnull(@varKSintLINK,0) 
					and RSF.ATR_CODE = @varAtributs
					--and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs 
					and Version = @varKSVers)
			and not(@varKSintLINK is null OR @varKSintLINK = 0)
		)
		OR
		(
			(@varKSintLINK is null OR @varKSintLINK = 0)
			and exists(select top 1 * from report_saved_forms RSF 
				where RSF.Link_Form = @varKSLinkF 
               AND RSF.del = 0
					and RSF.Period_Number = @varKSPNomber 
					and RSF.Period_Type = @varKSpTYPE 
					and RSF.Begin_Date = @varKSBDAte 
					and Link_Organization = @varKSLinkOrg 
					and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  
					and Link_Saved_Form <> isnull(@varKSintLINK,0) 
					and RSF.ATR_CODE = @varAtributs
					--and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs
					)
			and (select top 1 NEW_REPORT from dbo.I_REPORT_OPTIONS_COMMON) = 1
		)
		OR
		(
			(@varKSintLINK is null OR @varKSintLINK = 0)
			and exists(select top 1 * from report_saved_forms RSF 
				where RSF.Link_Form = @varKSLinkF 
               AND RSF.del = 0
					and RSF.Period_Number = @varKSPNomber 
					and RSF.Period_Type = @varKSpTYPE 
					and RSF.Begin_Date = @varKSBDAte 
					and Link_Organization = @varKSLinkOrg 
					and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  
					and Link_Saved_Form <> isnull(@varKSintLINK,0) 
					and RSF.ATR_CODE = @varAtributs
					and Version = (select max(Version) from report_saved_forms RSF1
						where RSF1.Link_Form = @varKSLinkF 
                     AND RSF1.del = 0
							and RSF1.Period_Number = @varKSPNomber 
							and RSF1.Period_Type = @varKSpTYPE 
							and RSF1.Begin_Date = @varKSBDAte 
							and Link_Organization = @varKSLinkOrg 
							and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  
							and Link_Saved_Form <> isnull(@varKSintLINK,0) 
							and RSF1.ATR_CODE = @varAtributs)
					and dbo.RO_AccessStatus(dbo.RO_AccessStatusByLink(@varKSLinkF), RSF.IsRO,  0) = 0)
		)

	)
begin
	return 11000
end


SET LOCK_TIMEOUT 5000
SET IMPLICIT_TRANSACTIONS ON
DECLARE 
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSERROR		int,
	@varKSRowCount	int,
	@varKSEventStr	varchar (200),
	@varKSEventStr2	varchar (200),
	@varKSLink_Task	int,
	@varKSLink_last_event int

SET @varKStrancount = @@TRANCOUNT
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSintLINK is null  OR @varKSintLINK = 0
	BEGIN
		--обновим atr
			declare @cstr varchar(250),@cstr2 varchar(250)
			set @cstr=left(dbo.rn_get_atr_val(0,@varKSLinkF,0),250) 
			set @cstr2=left(dbo.rn_get_atr_val(0,@varKSLinkF,1),250) 

        		select @varKSVers = max(version)+1 from report_saved_forms WHERE
            del = 0 AND 
				Link_Form=@varKSLinkF and
				Begin_Date=@varKSBDAte and
				Period_type=@varKSpTYPE and 
				Period_Number=@varKSPNomber and
				Link_Organization=@varKSLinkOrg and
				--IsSvod = @varKSisSvod and
				IsChangeAnalit = @varKSIsChAnalit and
				isnull(Link_Type_Svod, 0) = isnull(@varKSLinkTypeSvod, 0)
                and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs
		    INSERT INTO REPORT_saved_forms (Link_Form, Version, Begin_Date, Period_type, Period_Number, Link_Organization, IsSvod, IsChangeAnalit, LinkRazdel, LinkCelSt, LinkRashod, IsRO, Owner_SID, Note, Link_Type_Svod, CountSave, IsExam,atr,atr_code,IsRO_Set)
			VALUES (@varKSLinkF, isnull(@varKSVers,0), @varKSBDAte, @varKSpTYPE, @varKSPNomber, @varKSLinkOrg, @varKSisSvod, @varKSIsChAnalit, @varKSLRazdel, @varKSLCelSt, @varKSLRashod, @varKSIsRO, suser_sid(), @varKSNote, @varKSLinkTypeSvod, @varKSCountSave,@varKSIsExam,@cstr,@cstr2,@varKSIsRO)
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		SET @varKSEventStr2 = 'Добавление сохраненной формы'
      
      INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
      VALUES (@varKSintLINK, SUSER_SID(), 'Создание отчета')

	END
	ELSE
	BEGIN
		--select @varKSVers = max(version)+1 from dbo.report_saved_forms RSF where RSF.Link_Form = @varKSLinkF and RSF.Period_Number = @varKSPNomber and RSF.Period_Type = @varKSpTYPE and RSF.Begin_Date = @varKSBDAte and Link_Organization = @varKSLinkOrg and isnull(Link_Type_Svod,0) = isnull(@varKSLinkTypeSvod,0)  and Link_Saved_Form <> isnull(@varKSintLINK,0) and dbo.rn_get_atr_val(link_saved_form,0,1)=@varAtributs
      IF @varKSResetIsRightKS = 1      
		   if not exists(select top 1 * from report_saved_forms where link_saved_form = @varKSintLINK and Begin_Date=@varKSBDAte and Period_type=@varKSpTYPE and Period_Number=@varKSPNomber and Link_Organization=@varKSLinkOrg and Link_Type_Svod = @varKSLinkTypeSvod)
         BEGIN          
			   EXEC dbo.RO_REPORT_MODIFY  @varKSintLINK
         END 

		UPDATE REPORT_saved_forms
			SET	Link_Form = @varKSLinkF, 
				Version=@varKSVers, 
				Begin_Date=@varKSBDAte,
				Period_type=@varKSpTYPE, 
				Period_Number=@varKSPNomber,
				Link_Organization=@varKSLinkOrg,
				IsSvod = @varKSisSvod,
				IsChangeAnalit = @varKSIsChAnalit,
				LinkRazdel = @varKSLRazdel,
				LinkCelSt = @varKSLCelSt,
				LinkRashod = @varKSLRashod,
				IsRO = @varKSIsRO,
				Note = @varKSNote,
				IsRightKS = case @varKSResetIsRightKS when 0 then @IsRightKS else 0 end,
				Link_Type_Svod = @varKSLinkTypeSvod,
				CountSave= @varKSCountSave,
				IsExam = @varKSIsExam,
            [IsRO_Set] = @varKSIsRO
		WHERE link_saved_form = @varKSintLINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END

		if @oldIsRO <> @varKSIsRO
		begin
			exec dbo.X_GET_OPTION 'RO_MAIL_NASTR_TEMPLATE',0,@Template output

			select @varKSLink_Task = link_task from user_info
			select @varKSEventStr = '"' + SO.Status_Name + '" на "' + SN.Status_Name + '" для Отчета: ' + rtrim(RF.code) + ' ' + atr + ' Период: ' + 
				convert(char(4),year(BEGIN_DATE)) + ' год ' + 
				case period_Type when 2 then convert(char(1),period_number) + ' квартал'
					when 4 then convert(char(2),period_number) + ' месяц'
				ELSE '' end + ' Версия:' +  convert(char(3),RSF.version) + ' Организация: ' + D.Code + ' Бюджет: ' + B.Name,
			@EMail = EMail, @Subject = 'У отчета ' + rtrim(RF.code) + ' стал статус "' + SN.Status_Name + '"',
			@Template = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Template,'[Код формы]', RTRIM(RF.code)),
																								'[Наименование формы]', RTRIM(RF.Name)),
																								'[Атрибут]', RTRIM(ISNULL(atr,''))),
																								'[Период]', 			case period_Type when 2 then convert(char(1),period_number) + ' квартал '
																															when 4 then convert(char(2),period_number) + ' месяц '
																														ELSE '' end + convert(char(4),year(BEGIN_DATE)) + ' год '),
																								'[Организация]', RTRIM(dbo.GetDepName(RSF.Link_Organization, RSF.begin_date))),
																								'[Бюджет]', RTRIM(B.Name)), 
																								'[Версия]', convert(char(3),RSF.version)),
																								'[Старый статус]', SO.Status_Name),
																								'[Новый статус]', SN.Status_Name),
																								'[Время]', convert(varchar(20), getdate(), 113)),
																								'[Комментарий формы]', RTRIM(ISNULL(RSF.Note,''))),
																								'[Пользователь]', SUSER_SNAME(SUSER_SID()) + ' ' + isnull(dbo.AdminGetUserFIO(dbo.AdminGetUidBySID(SUSER_SID())),''))																					
			from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form 
				left join departments D on D.link = RSF.link_organization 
				left join kl_budg_type B on B.link = RSF.link_type_svod
				left join report_status SO on @oldIsRO = SO.status
				left join report_status SN on SN.status = @varKSIsRO
			where link_saved_form = @varKSintLINK

			exec WF_GENERATEEVENT 'Смена статуса', @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSintLINK

			if isnull(@EMail, '') <> '' and @varKSIsRO in (2, 3, 5) 
				exec dbo.RO_MAIL_SEND @EMail, @Subject, @Template

         INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
         SELECT @varKSintLINK, SUSER_SID(), 'Смена статуса на "' + RTRIM((SELECT rs.[Status_Name]
                                                                      FROM dbo.[REPORT_STATUS] rs WHERE rs.[Status] =@varKSIsRO)) + '"'               
		end

		SET @varKSEventStr2 = 'Изменение сохраненной формы'
	END
	DECLARE @lcOrgEvent VARCHAR(100)
	Set @lcOrgEvent = ''
	Select @lcOrgEvent = '; Организация: ' + LTRIM(RTRIM(CODE)) + ' ' + Left(LTRIM(RTRIM(dbo.getDepName(@varKSLinkOrg,@varKSBDAte))),60) + ';'
	From Departments Where link = @varKSLinkOrg

	Set @lcOrgEvent = @lcOrgEvent + 'Бюджет: ' + 
		rtrim(isnull((select Name from kl_budg_type where link = @varKSLinkTypeSvod), '-')) + ';'

	select @varKSLink_Task = link_task from user_info
	select @varKSEventStr = 'Форма: ' + rtrim(code) + @lcOrgEvent + ' Период: ' + 
		(case RSF.IsSvod when 1 then 'свод за ' else '' end + convert(char(4),year(BEGIN_DATE)) + ' год ' + 
		 case period_Type when 2 then convert(char(1),period_number) + ' квартал'
			when 4 then convert(char(2),period_number) + ' месяц'
		 ELSE '' end) + ' Версия:' +  convert(char(3),RSF.version)
	from report_saved_forms RSF left join report_forms RF on RSF.link_form = RF.Link_Form where link_saved_form = @varKSintLINK

	exec RO_GENERATEEVENT @varKSEventStr2, @varKSEventStr, @varKSLink_Task, 'REPORT_SAVED_FORMS', @varKSintLINK
	-- сохраним ссылку на журнал в форме
	set @varKSLink_last_event = @@identity 
	update dbo.REPORT_saved_forms
	SET link_jurnal = @varKSLink_last_event
	where link_saved_form = @varKSintLINK
   
   IF ISNULL(@varKSNote, '') <> ''
   BEGIN 
      INSERT dbo.[REPORT_SAVED_FORMS_NOTE] (LINK_SAVED_FORM,SID, NOTE)
      VALUES (@varKSintLINK, SUSER_SID(), @varKSNote)
   END 

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO
GRANT ALL ON dbo.[I_REPORT_SAVE_FORM] 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.[RO_KBK_HIST_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RO_KBK_HIST_DELETE]

GO




/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].RO_KBK_HIST_DELETE
	@varKSparLINK_UP int
AS
DELETE FROM REPORT_KBK_HIST
WHERE LINK_UP = @varKSparLINK_UP 

DELETE dbo.report_kbk_cashe
WHERE LINK_UP = @varKSparLINK_UP


GO


GRANT EXECUTE ON dbo.[RO_KBK_HIST_DELETE] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_GET_STAGE_DATE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_GET_STAGE_DATE]

GO
CREATE PROCEDURE [DBO].SA_GET_STAGE_DATE (@LINK_EXPIR INT, @YEAR INT, @PERIOD_BEG DATETIME, @PERIOD_END DATETIME)
--Процедура выводит список сотрудников и дату, на которую наступает указанное количество лет указанного вида стажа в заданном периоде
AS

CREATE TABLE #T (EMPL_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, KOEFF NUMERIC(4,1), YEARS INT, MONTHS INT, [DAYS] INT)	

---
INSERT #T (EMPL_LINK, DATE_BEGIN, DATE_END, KOEFF, YEARS, MONTHS, [DAYS])
SELECT EO.EMPL_LINK, EO.DATE_BEGIN, EO.DATE_END, OK.KOEF, 0, 0, 0
FROM 
	DBO.OLDWORK_KOEF OK 
	LEFT JOIN DBO.EMPL_OLDWORK EO ON OK.OLDWORK_LINK=EO.LINK
WHERE
	OK.EXPIR_LINK = @LINK_EXPIR 
	AND OK.KOEF <> 0

---	
INSERT #T (EMPL_LINK, DATE_BEGIN, DATE_END, KOEFF, YEARS, MONTHS, [DAYS])
SELECT 
	IM.EMPL_LINK, DATE_BEGIN, DATE_END,	MK.KOEF, 0, 0, 0
FROM DBO.KU_ONLY_MOVES IM
	LEFT JOIN DBO.MOVE_KOEF MK ON MK.MOVE_LINK=IM.LINK
	LEFT JOIN DBO.EXPIR E ON MK.EXPIR_LINK=E.LINK
WHERE 
	MK.EXPIR_LINK = @LINK_EXPIR
	AND MK.KOEF <> 0

---
UPDATE #T SET DATE_END = '99991230' WHERE DATE_END >= '99991231'

---	
CREATE TABLE #R(EMPL_LINK INT, YEARS NUMERIC(18,2), MONTHS NUMERIC(18,2), [DAYS] NUMERIC(18,2), DATE_END DATETIME)	
INSERT INTO #R (EMPL_LINK, YEARS, MONTHS, [DAYS])
SELECT DISTINCT EMPL_LINK, 0, 0, 0 
FROM #T 
WHERE EMPL_LINK IS NOT NULL AND DATE_BEGIN IS NOT NULL
ORDER BY EMPL_LINK

DECLARE @EMPL_LINK INT, @DATE_BEGIN DATETIME, @DATE_END DATETIME, @KOEFF NUMERIC(4,1), @YEARS NUMERIC(18,2), @MONTHS NUMERIC(18,2), @DAYS NUMERIC(18,2)
DECLARE @Y NUMERIC(18,2), @M NUMERIC(18,2), @D NUMERIC(18,2)

DECLARE @CUR1 CURSOR
SET @CUR1 = CURSOR FORWARD_ONLY

FOR 
	SELECT EMPL_LINK, DATE_BEGIN, DATE_END, KOEFF, YEARS, MONTHS, [DAYS]
	FROM #T
	WHERE EMPL_LINK IS NOT NULL AND DATE_BEGIN IS NOT NULL
	ORDER BY EMPL_LINK, DATE_BEGIN

OPEN @CUR1
FETCH NEXT FROM @CUR1 INTO @EMPL_LINK, @DATE_BEGIN, @DATE_END, @KOEFF, @YEARS, @MONTHS, @DAYS
WHILE (@@FETCH_STATUS <> -1)
BEGIN
	IF (@@FETCH_STATUS <> -2)
	BEGIN

		SELECT 
			@Y = YEARS, @M = MONTHS, @D = [DAYS]
		FROM #R	WHERE EMPL_LINK = @EMPL_LINK

		IF @Y < 3
		BEGIN
		
			SELECT 
				@Y = @Y +((YEAR(@DATE_END+1) - YEAR(@DATE_BEGIN)) * @KOEFF),
				@M = @M + (MONTH(@DATE_END+1) - MONTH(@DATE_BEGIN)) * @KOEFF, 
				@D = @D + (DAY(@DATE_END+1) - DAY(@DATE_BEGIN)) * @KOEFF

			SELECT
				@Y = CONVERT(INT,@Y), 
				@M = @M + (@Y - CONVERT(INT,@Y)) * 12
	
			SELECT				
				@M = CONVERT(INT,@M), 
				@D = @D + (@M - CONVERT(INT,@M)) * 30

			SELECT
				@M = @M + CONVERT(INT,@D/30), 
				@D = CONVERT(INT,@D - CONVERT(INT,@D/30) * 30)
			
			SELECT
				@Y = @Y + CONVERT(INT,@M/12), 
				@M = CONVERT(INT,@M - CONVERT(INT,@M/12) * 12)			
	
			SELECT 
				@M = @M - 1, 
				@D = @D + 30 
			WHERE @D < 0
			
			SELECT
				@Y = @Y - 1, 
				@M = @M + 12 
			WHERE @M < 0

			UPDATE #R SET
				YEARS = @Y, MONTHS = @M, [DAYS] = @D, DATE_END = @DATE_END
			WHERE EMPL_LINK = @EMPL_LINK

		END

	END

	FETCH NEXT FROM @CUR1 INTO @EMPL_LINK, @DATE_BEGIN, @DATE_END, @KOEFF, @YEARS, @MONTHS, @DAYS
END

CLOSE @CUR1
DEALLOCATE @CUR1

SELECT 
	EMPL_LINK,
	TAB,
	FIO = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(E.FM)) + ' ' + LTRIM(RTRIM(E.IM)) + ' ' + LTRIM(RTRIM(E.OT)),'НЕ ЗАПОЛНЕНО'))),100 ),
	SUBDIV = SUBDIV_NAME,
	POST = POST_NAME,
	DATE_EV = CONVERT(VARCHAR(10),DATEADD(DAY,0-[DAYS],DATEADD(MONTH,0-MONTHS,DATEADD(YEAR,@YEAR-YEARS,R.DATE_END))),104)
FROM 
	#R R
	INNER JOIN DBO.SD_EMPL_FN(DEFAULT,@PERIOD_BEG,DEFAULT,DEFAULT) E ON R.EMPL_LINK = E.LINK
WHERE
	(@YEAR-YEARS + YEAR(R.DATE_END)) BETWEEN 1901 AND 9999
	AND	DATEADD(DAY,0-[DAYS],DATEADD(MONTH,0-MONTHS,DATEADD(YEAR,@YEAR-YEARS,R.DATE_END))) BETWEEN @PERIOD_BEG	AND @PERIOD_END
	AND E.DATE_END IS NULL
ORDER BY 
	SUBDIV_NAME, LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(E.FM)) + ' ' + LTRIM(RTRIM(E.IM)) + ' ' + LTRIM(RTRIM(E.OT)),'НЕ ЗАПОЛНЕНО'))),100 )

DROP TABLE #T
DROP TABLE #R

RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_GET_STAGE_DATE] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RO_PRINT_ONE_ATR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RO_PRINT_ONE_ATR]
GO

/*
© Кейсистемс (Keysystems), 2009
*/

CREATE PROCEDURE dbo.[RO_PRINT_ONE_ATR]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS
	if isnull(@WEB_excel, 0) <> 1
		select '' col1 
	declare  @atr varchar(254), @atr_value varchar(254), @iLF INT, @iLT INT, @tOT TINYINT, @vcTableName VARCHAR(100) , @vcExecStr VARCHAR(8000), @vcCol VARCHAR(800), @vcCol1 VARCHAR(800), @vcTableNameAll VARCHAR(100) 
   
   SELECT @iLF = link_form FROM dbo.[REPORT_SAVED_FORMS] rsf WHERE rsf.[Link_Saved_Form] = @LSF
   
   SELECT @atr = rf.[atributs]
   FROM dbo.[REPORT_FORMS] rf WHERE rf.[Link_Form] = @iLF
      
	set @atr_value = dbo.RN_GET_ATR_Value(@LSF, @atr)
   
   SET @vcCol = 'atr, DEL, CODE, checked, upd, link_row, orders, calc_orders, print_null, itog'
   SET @vcCol1 = 'atr, DEL, CODE, checked, upd, link_row, orders, calc_orders, print_null, 0 '
   
   SELECT @vcCol = @vcCol + ',COL' + LTRIM(RTRIM(STR(RC.orders))), @vcCol1 = @vcCol1 + ',COL' + LTRIM(RTRIM(STR(RC.orders)))
   FROM dbo.[REPORT_COLOUMNS] rc JOIN dbo.[REPORT_TABLES] rt ON rc.[Link_Table] = rt.[Link_Table]
   WHERE rt.[Link_Form] = @iLF AND rt.orders = 1
   
   DECLARE cur CURSOR LOCAL STATIC FOR
      SELECT link_table, orders 
      FROM dbo.[REPORT_TABLES] rt 
      WHERE rt.[Link_Form] = @iLF
      
   OPEN [cur]
   
   FETCH NEXT FROM cur INTO @iLT, @tOT
   
   WHILE @@fetch_status = 0
   BEGIN
      SET @vcTableName = ''
      exec dbo.ro_get_all_atr_table @LSF, @tOT, @bDeleteEmptyRows, @AtrInOnePage, @atr, 1, @vcTableName OUTPUT
     
      IF COL_LENGTH('tempdb..' + @vcTableName, 'itog') IS NULL
      BEGIN
            SET @vcExecStr = 'ALTER TABLE ' + @vcTableName + ' ADD itog tinyint'
            EXECUTE( @vcExecStr)
      END          
      
      
      IF ISNULL(@vcTableNameAll, '') = ''
         SET @vcTableNameAll = @vcTableName
      ELSE BEGIN           
         SET @vcExecStr = 'insert ' + @vcTableNameAll + ' (' + @vcCol + ') select ' + @vcCol1 + ' from ' + @vcTableName + ' drop table ' + @vcTableName
         EXEC (@vcExecStr)
      END          
       
      FETCH NEXT FROM cur INTO @iLT, @tOT
   END      
   
   close [cur]
   DEALLOCATE [cur]
   
   SET @vcExecStr = 'ALTER TABLE ' + @vcTableNameAll + ' ADD colatrname varchar(8000)'
   EXEC (@vcExecStr)

   
   SET @vcExecStr = 'update ' + @vcTableNameAll + ' set colatrname = B.name from [dbo].[BI_DICTION_ADMIN_BS] B where B.code = atr'
   PRINT @vcExecStr
   EXEC (@vcExecStr)
   
   SET @vcExecStr = 'select atr as colatr, colatrname,  ' + @vcCol + ' from ' + @vcTableNameAll + ' order by atr, code' 
   EXEC (@vcExecStr)

	if isnull(@WEB_excel, 0) <> 1
	select cells as style,style as value from report_print_style where 1=0 order by cells


GO
GRANT ALL ON dbo.[RO_PRINT_ONE_ATR] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT OFF
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KJ_ATT_OTZYV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KJ_ATT_OTZYV]

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE dbo.KJ_ATT_OTZYV
	@varLink	INT
AS

	DECLARE @WORK_DATE DATETIME
	SET @WORK_DATE = (SELECT WORKDATE FROM USER_INFO)
	
	SELECT	TOP 1
		@WORK_DATE DATE_WORK,
		KP.FIO,
		KP.NAME_PERS,
		KP.BIRTHDATE,
		DBO.KJ_GET_EDUC_EMPL(@varLink) AS UCH,
		RTRIM(LTRIM(KP.ACAD_DEGREE_NAME)) + ', ' + RTRIM(LTRIM(KP.ACAD_STATUS_NAME)) AS UCH_ST_ZV,
		KEP.POST_NAME AS POST,
		KEP.SUBDIV_NAME AS SUBDIV,
		IM.DATE_BEGIN,
		dbo.ku_GetEmplExpir(KEP.LINK,'YEAR','GEN',@WORK_DATE) AS OBW_EXPIR,
		dbo.ku_GetEmplExpir(KEP.LINK,'YEAR','GOS_NADB',@WORK_DATE) AS GS_EXPIR,
		EM_CH.CHIN_NAME AS KLAS_CHIN,
		EM_CH.DATE AS DATE_CHIN
	FROM	KU_EMPL_PLACING_FN(@WORK_DATE) KEP INNER JOIN KU_PERSON KP
		ON KEP.PERS_LINK = KP.LINK LEFT JOIN ITEM_MOVE IM
		ON KEP.LINK = IM.EMPL_LINK AND (IM.NEW_FACE = 0 OR IM.NEW_FACE = 1) AND IM.ACTIVE = 1 
							LEFT JOIN (
								SELECT EMPL_LINK, CHIN_NAME, DATE
								FROM KU_EMPL_CHIN WHERE DATE = (SELECT MAX(DATE)
												FROM KU_EMPL_CHIN
												WHERE @WORK_DATE >= DATE)
								   ) AS EM_CH
		ON KEP.LINK = EM_CH.EMPL_LINK
	WHERE	KEP.LINK = @varLink
		AND IM.DATE_BEGIN <= @WORK_DATE
	ORDER BY IM.DATE_BEGIN DESC


GO


GRANT EXECUTE ON dbo.[KJ_ATT_OTZYV] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KO_REP_MANAGER_COMMENT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KO_REP_MANAGER_COMMENT]

GO

CREATE PROCEDURE dbo.KO_REP_MANAGER_COMMENT
	@nSel_Spr1 int
AS
-- Сведения об уровне знаний, навыков и умений (профессиональном уровне) -----------
-- гражданского служащего и о возможности присвоения ему классного чина  -----------
DECLARE @RESULT TABLE (	[CHIEF]			VARCHAR(1000),
						[DATE]			DATETIME,
						[FIO]			VARCHAR(254),
						[UCH_ZAV]		VARCHAR(3000),	-- Сведения об образовании
						[PROF_KV]		VARCHAR(2000),	-- Сведения о проф.переподготовке и пов.квалификации
						[POST]			VARCHAR(254),	-- Должность
						[SUBDIV]		VARCHAR(254),	-- Подразделение
						[DATE_BEGIN]	DATETIME,		-- Дата назначения на должность				
						[OBW_EXPIR]		INT,			-- Общий стаж
						[GS_EXPIR]		INT	,			-- Стаж госслужбы	
						[CHIN_PR]		VARCHAR(254))	-- Предполагаемый классный чин
------------------------------------------------------------------------------------

-- Сведения о классном чине --------------------------------------------------------
DECLARE @EMPL_CHIN TABLE(	LINK INT, 
							EMPL_LINK INT, 
							DATE DATETIME, 
							CHIN_NAME VARCHAR(150), 
							ATT_KOM_LINK INT)
INSERT INTO @EMPL_CHIN(LINK, EMPL_LINK, DATE, CHIN_NAME, ATT_KOM_LINK)
SELECT LINK, EMPL_LINK, DATE, CHIN_NAME, ATT_KOM_LINK
FROM KU_EMPL_CHIN
WHERE LINK = @nSel_Spr1
------------------------------------------------------------------------------------
DECLARE @DATE_CHIN DATETIME, @EMPL_LINK INT
SET @DATE_CHIN = (SELECT DATE FROM @EMPL_CHIN)
SET @EMPL_LINK = (SELECT EMPL_LINK FROM @EMPL_CHIN)

-- Сведения о сотруднике -----------------------------------------------------------
DECLARE @KU_EMPL_PLACING_FN TABLE (	LINK INT, 
									PERS_LINK INT,
									FIO VARCHAR(254),
									POST_NAME VARCHAR(254),
									SUBDIV_NAME VARCHAR(254))
INSERT INTO @KU_EMPL_PLACING_FN(	LINK,	PERS_LINK,	FIO,	POST_NAME,	SUBDIV_NAME)
SELECT	LINK,	PERS_LINK,	NAME_EMPL,	POST_NAME,	SUBDIV_NAME
FROM	DBO.KU_EMPL_PLACING_FN(@DATE_CHIN)
WHERE	LINK = @EMPL_LINK
-------------------------------------------------------------------------------------

-- Сведения об образовании ----------------------------------------------------------
DECLARE @UCH_ZAV VARCHAR(3000)
SET @UCH_ZAV = RTRIM(DBO.KJ_GET_EDUC_EMPL(@EMPL_LINK))
-------------------------------------------------------------------------------------

-- Сведения о проф.переподготовке и пов.квалификации --------------------------------
DECLARE @PROF_KV VARCHAR(2000)
SET @PROF_KV = RTRIM(DBO.GetProfKvalToEmpl_More(@EMPL_LINK))
--------------------------------------------------------------------------------------

-- Дата назначения на должность ------------------------------------------------------
DECLARE @DATE_BEGIN DATETIME
SET @DATE_BEGIN = (	SELECT	TOP 1 IM.DATE_BEGIN
					FROM	ITEM_MOVE IM
					WHERE	IM.EMPL_LINK = @EMPL_LINK AND (IM.NEW_FACE = 0 OR IM.NEW_FACE = 1) AND IM.ACTIVE = 1 AND IM.DATE_BEGIN <= @DATE_CHIN
					ORDER BY IM.DATE_BEGIN DESC)
--------------------------------------------------------------------------------------

-- Сведения об общем стаже, стаже госслужбы ------------------------------------------
DECLARE @OBW_EXPIR INT, @GS_EXPIR INT
SET @OBW_EXPIR = dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GEN',@DATE_CHIN)
SET @GS_EXPIR =  dbo.ku_GetEmplExpir(@EMPL_LINK,'YEAR','GOS_NADB',@DATE_CHIN)

DECLARE @CHIEF_FIO VARCHAR(1000)
DECLARE @LINK_DEP INT

SELECT @LINK_DEP = DEP_LINK FROM dbo.EMPL WHERE LINK = @EMPL_LINK

SELECT TOP 1
	@CHIEF_FIO = LEFT(RTRIM(CHIEF.FM) + ' ' + CHIEF.IM + ' ' + CHIEF.OT
	+ ', ' + ISNULL(CHIEF.POST_NAME,''), 1000)
FROM dbo.DICTIONARY_DEPARTMENT DD1 
	INNER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
WHERE DD1.LINK = @LINK_DEP

--------------------------------------------------------------------------------------
INSERT INTO @RESULT (	[CHIEF], [DATE],[FIO],[UCH_ZAV],[PROF_KV],[POST],
						[SUBDIV],[DATE_BEGIN],[OBW_EXPIR],[GS_EXPIR], [CHIN_PR]	)
SELECT
	[CHIEF_FIO] = LTRIM(RTRIM(@CHIEF_FIO)),
	[DATE]		=	EC.DATE,
	[FIO]		=	KEP.FIO,					-- ФИО	
	[UCH_ZAV]	=	@UCH_ZAV,					-- Сведения об образовании
	[PROF_KV]	=	@PROF_KV,					-- Сведения о проф.переподготовке и пов.квалификации
	[POST]		=	ISNULL(KEP.POST_NAME,''),	-- Должность
	[SUBDIV]	=	ISNULL(KEP.SUBDIV_NAME,''),	-- Подразделение
	[DATE_BEGIN]= 	@DATE_BEGIN,				-- Дата назначения на должность				
	[OBW_EXPIR]	=	@OBW_EXPIR,					-- Общий стаж
	[GS_EXPIR]	=	@GS_EXPIR,					-- Стаж госслужбы	
	[CHIN_PR]	=	EC.CHIN_NAME				-- Присваемый классный чин
FROM	@EMPL_CHIN				EC	LEFT JOIN 
		@KU_EMPL_PLACING_FN		KEP	ON	EC.EMPL_LINK = KEP.LINK		

SELECT * FROM @RESULT







GO


GRANT EXECUTE ON dbo.[KO_REP_MANAGER_COMMENT] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_12_PFR_INV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_12_PFR_INV]

GO

CREATE PROCEDURE dbo.RSA_RSV_1_12_PFR_INV
	@varKSdDate1 DATETIME,
	@varKSdDate2 DATETIME,
	@LINK_DEP int = NULL,
	@WAY_CALC TINYINT = 7,
	@REP TINYINT = 0
AS BEGIN

	DECLARE @varKSDEFAULTDK AS DATETIME
	
	SET	@varKSDEFAULTDK = CONVERT( VARCHAR(8), ( YEAR( GETDATE() ) * 100 + 12 ) * 100 + 31 )

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)

	CREATE TABLE #TMP (
		LINK INT, 
		FIO VARCHAR(254),
		FIO2 VARCHAR(254),
		NUM_SPR VARCHAR(30), 
		DATE_SPR VARCHAR(10), 
		GRP VARCHAR(25), 
		GRP2 VARCHAR(25), 
		PER_BEG VARCHAR(10), 
		PER_END VARCHAR(10), 
		SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

	CREATE TABLE #TMP0 (
		[PERS_LINK] int,
		[FIO] varchar(254),
		[FIO2] varchar(254),
		[DOC_NUM] varchar(30),
		[DOC_DATE] varchar(10),
		[GROUP_NAME] varchar(254),
		[GRP2] varchar(3),
		[PER_BEG] varchar(10),
		[PER_END] varchar(10))	

	INSERT INTO #TMP0(PERS_LINK,FIO,FIO2,DOC_NUM,DOC_DATE,GROUP_NAME,GRP2,PER_BEG,PER_END)
	SELECT
		DIF.PERS_LINK, 
		LEFT((SELECT 
			TOP 1 LTRIM(RTRIM(DF.FM)) + ' ' + LTRIM(RTRIM(DF.IM)) + ' ' + LTRIM(RTRIM(DF.OT)) 

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO,
		LEFT((SELECT 
			TOP 1 UPPER(LTRIM(RTRIM(DF.FM)) + ',' + LTRIM(RTRIM(DF.IM)) + ',' + LTRIM(RTRIM(DF.OT)) )

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO2,
		DOC_NUM = LEFT(MAX(DIF.DOC_NUM),30),
		DOC_DATE = LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DOC_DATE),104),''))), 
		GROUP_NAME = LEFT(MAX(DIF.GROUP_NAME),254),
		CASE 
			WHEN MAX(DIF.GROUP_NAME) = 'I ГРУППА' THEN 'I'
			WHEN MAX(DIF.GROUP_NAME) = 'II ГРУППА' THEN 'II'
			WHEN MAX(DIF.GROUP_NAME) = 'III ГРУППА' THEN 'III'
			ELSE ''
		END AS GRP2, 
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DATE_BEGIN),104),''))) AS PER_BEG,
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),ISNULL(MAX(DIF.DATE_END),dbo.DateEndOfYear(@varKSdDate1)),104),''))) AS PER_END
	FROM dbo.KU_PERS_INVALID  DIF INNER JOIN dbo.EMPL E ON DIF.PERS_LINK = E.PERS_LINK
	WHERE COALESCE(DIF.DATE_BEGIN,@varKSdDate2) <= @varKSdDate2 AND COALESCE(DIF.DATE_END,@varKSdDate1) >= @varKSdDate1
		and E.DEP_LINK = @DEP_LINK
	GROUP BY 
		DIF.PERS_LINK
		
	INSERT INTO #TMP0(PERS_LINK,FIO,FIO2,DOC_NUM,DOC_DATE,GROUP_NAME,GRP2,PER_BEG,PER_END)
	SELECT
		DIF.PERS_LINK, 
		LEFT((SELECT 
			TOP 1 LTRIM(RTRIM(DF.FM)) + ' ' + LTRIM(RTRIM(DF.IM)) + ' ' + LTRIM(RTRIM(DF.OT)) 

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO,
		LEFT((SELECT 
			TOP 1 UPPER(LTRIM(RTRIM(DF.FM)) + ',' + LTRIM(RTRIM(DF.IM)) + ',' + LTRIM(RTRIM(DF.OT)) )

				FROM person DF
				WHERE DF.LINK = DIF.PERS_LINK),254) AS FIO2,
		DOC_NUM = LEFT(MAX(DIF.DOC_NUM),30),
		DOC_DATE = LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DOC_DATE),104),''))), 
		GROUP_NAME = LEFT(MAX(DIF.GROUP_NAME),254),
		CASE 
			WHEN MAX(DIF.GROUP_NAME) = 'I ГРУППА' THEN 'I'
			WHEN MAX(DIF.GROUP_NAME) = 'II ГРУППА' THEN 'II'
			WHEN MAX(DIF.GROUP_NAME) = 'III ГРУППА' THEN 'III'
			ELSE ''
		END AS GRP2, 
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),MAX(DIF.DATE_BEGIN),104),''))) AS PER_BEG,
		LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),ISNULL(MAX(DIF.DATE_END),dbo.DateEndOfYear(@varKSdDate1)),104),''))) AS PER_END
	FROM dbo.KU_PERS_INVALID  DIF
	WHERE 
		COALESCE(DIF.DATE_BEGIN,@varKSdDate2) <= @varKSdDate2 AND COALESCE(DIF.DATE_END,@varKSdDate1) >= @varKSdDate1
		and EXISTS (SELECT * FROM dbo.REESTR_DGH DGH 
						WHERE DGH.DEP_LINK = @DEP_LINK AND DGH.PERS_LINK = DIF.PERS_LINK 
								AND COALESCE(DGH.DATE1,@varKSdDate2) <= @varKSdDate2 AND COALESCE(DGH.DATE2,@varKSdDate1) >= @varKSdDate1)
		AND NOT EXISTS (SELECT * FROM #TMP0 TT WHERE TT.PERS_LINK = DIF.PERS_LINK)						
	GROUP BY 
		DIF.PERS_LINK			

	--
	if  OBJECT_ID('tempdb..#PERS_INV1') IS NOT NULL
		DROP TABLE #PERS_INV1

	--
	DECLARE @varKSSTART_YEAR DATETIME
	SET @varKSSTART_YEAR  = dbo.DateBeginOfYear(@varKSdDate1)

	DECLARE @varKSnYear INT, @varKSnMonth1 INT, @varKSnMONTH2 INT, @varKSnMONTH3 INT
	SELECT 
		@varKSnYear = YEAR(@varKSdDate1),
		@varKSnMonth1 = MONTH(@varKSdDate2)-2,
		@varKSnMONTH2 = MONTH(@varKSdDate2)-1,
		@varKSnMONTH3 = MONTH(@varKSdDate2)

	Declare @StBase2 table (link int)
	Insert into @StBase2 (link)
	select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = @WAY_CALC)

	---------
	CREATE TABLE #TSUM (PERS_LINK INT, MON TINYINT, FACE_GROUP TINYINT, SUMMA NUMERIC(18,2))

	INSERT INTO 
		#TSUM (PERS_LINK, MON, FACE_GROUP, SUMMA)
	select 
		E.PERS_LINK,
		MON = Month(CJ.PERIOD_BEGIN),
		( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
		SUMMA = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
	from 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
		INNER JOIN DBO.PERSON P1 ON P1.LINK = E.PERS_LINK
		LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
		LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK AND COALESCE(I.DATE_BEGIN,dbo.DateBeginOfYear(@varKSdDate1)) <= dbo.DateEndOfYear(@varKSdDate2) AND COALESCE(I.DATE_END,dbo.DateEndOfYear(@varKSdDate2)) >= dbo.DateBeginOfYear(@varKSdDate1)
	where 	
		Year(period_begin) = @varKSnYear and Month(period_begin) <= @varKSnMONTH3 
		and CJ.LINK_DEP = @DEP_LINK
		and P.[OBJECT] = 1
	GROUP BY
		E.PERS_LINK, Month(CJ.PERIOD_BEGIN),( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )
	UNION ALL	
	select
		CJ.PERS_LINK, 
		MON = Month(CJ.PERIOD_BEGIN),
		( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
		SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
	from 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
		LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK AND COALESCE(I.DATE_BEGIN,dbo.DateBeginOfYear(@varKSdDate1)) <= dbo.DateEndOfYear(@varKSdDate2) AND COALESCE(I.DATE_END,dbo.DateEndOfYear(@varKSdDate2)) >= dbo.DateBeginOfYear(@varKSdDate1)
	where 	
		Year(period_begin) = @varKSnYear and Month(period_begin) <= @varKSnMONTH3 
		and CJ.LINK_DEP = @DEP_LINK
		and P.[OBJECT] = 1
	GROUP BY
		CJ.PERS_LINK, Month(CJ.PERIOD_BEGIN), ( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )		


	-------
	CREATE TABLE #TMP_00 (PERS_LINK INT, MON TINYINT, FACE_GROUP TINYINT, SUMMA NUMERIC(18,2))
	
	INSERT INTO #TMP_00 (PERS_LINK, MON, FACE_GROUP, SUMMA)
	SELECT 
		PERS_LINK, MON, FACE_GROUP, SUMMA = SUM(SUMMA)
	FROM 
		#TSUM
	GROUP BY 
		PERS_LINK, MON, FACE_GROUP

	--По людям округленные суммы
	SELECT PERS_LINK, 
		CASE @varKSnMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
		Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMonth1 THEN SUMMA ELSE 0 END)) AS SM1,
		Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH2 THEN SUMMA ELSE 0 END)) AS SM2,
		Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH3 THEN SUMMA ELSE 0 END)) AS SM3,

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
		
	INTO #TMP_000
	FROM #TMP_00
	GROUP BY PERS_LINK

	--Подгонка суммы (Из-за проблем округления)	
	DECLARE @NADO TABLE (SUM_Q numeric(18,2),SUM_M1 numeric(18,2),SUM_M2 numeric(18,2),SUM_M3 numeric(18,2), S1 numeric(18,2), S2 numeric(18,2), S3 numeric(18,2), S4 numeric(18,2), S5 numeric(18,2), S6 numeric(18,2), S7 numeric(18,2), S8 numeric(18,2), S9 numeric(18,2))
	--Итоговые округленные суммы неокругленных сумм по людам
	INSERT INTO @NADO (SUM_Q, SUM_M1, SUM_M2, SUM_M3, S1, S2, S3, S4, S5, S6, S7, S8, S9)
	SELECT 
		CASE @varKSnMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
			 
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMonth1 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH2 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH3 THEN SUMMA ELSE 0 END)),

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))		  
		 
	FROM #TMP_00	
	WHERE FACE_GROUP = 1

	INSERT INTO @NADO (SUM_Q, SUM_M1, SUM_M2, SUM_M3, S1, S2, S3, S4, S5, S6, S7, S8, S9)
	SELECT 
		CASE @varKSnMONTH3
			WHEN 3 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))
			WHEN 6 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))	
			WHEN 9 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
			WHEN 12 THEN
						Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))			
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA ELSE 0 END))
						+ Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA ELSE 0 END))							
		END AS SM_ALL, 
			 
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMonth1 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH2 THEN SUMMA ELSE 0 END)),
		 Convert(numeric(18,2),SUM(CASE WHEN MON = @varKSnMONTH3 THEN SUMMA ELSE 0 END)),

		S1 = Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA ELSE 0 END)),
		S2 = Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA ELSE 0 END)),
		S3 = Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA ELSE 0 END)),
		
		S4 = Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA ELSE 0 END)),
		S5 = Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA ELSE 0 END)),
		S6 = Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA ELSE 0 END)),
		
		S7 = Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA ELSE 0 END)),
		S8 = Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA ELSE 0 END)),
		S9 = Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA ELSE 0 END))
		 
	FROM #TMP_00		 
	WHERE FACE_GROUP = 2
	------------------------------------------------
--Распределение разницы между итоговой округленной суммы неокругленных сумм по людам и суме округленных сум по людам
--Разница округлений исправляется на человеке с максимальным доходом в месяце, когда получилась разница	
--Корректировка сумм за предудущий 1 квартал
	IF @varKSnMONTH3 > 3 AND ISNULL((SELECT SUM(S1) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S1) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S1) FROM @NADO),0) - ISNULL((SELECT SUM(S1) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S1 DESC)
	END
	IF @varKSnMONTH3 > 3 AND ISNULL((SELECT SUM(S2) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S2) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S2) FROM @NADO),0) - ISNULL((SELECT SUM(S2) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S2 DESC)
	END	
	IF @varKSnMONTH3 > 3 AND ISNULL((SELECT SUM(S3) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S3) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S3) FROM @NADO),0) - ISNULL((SELECT SUM(S3) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S3 DESC)
	END
--Корректировка сумм за предудущий 2 квартал
	IF @varKSnMONTH3 > 6 AND ISNULL((SELECT SUM(S4) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S4) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S4) FROM @NADO),0) - ISNULL((SELECT SUM(S4) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S4 DESC)
	END
	IF @varKSnMONTH3 > 6 AND ISNULL((SELECT SUM(S5) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S5) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S5) FROM @NADO),0) - ISNULL((SELECT SUM(S5) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S5 DESC)
	END	
	IF @varKSnMONTH3 > 6 AND ISNULL((SELECT SUM(S6) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S6) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S6) FROM @NADO),0) - ISNULL((SELECT SUM(S6) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S6 DESC)
	END
--Корректировка сумм за предудущий 3 квартал
	IF @varKSnMONTH3 > 9 AND ISNULL((SELECT SUM(S7) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S7) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S7) FROM @NADO),0) - ISNULL((SELECT SUM(S7) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S7 DESC)
	END
	IF @varKSnMONTH3 > 9 AND ISNULL((SELECT SUM(S8) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S8) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S8) FROM @NADO),0) - ISNULL((SELECT SUM(S8) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S8 DESC)
	END	
	IF @varKSnMONTH3 > 9 AND ISNULL((SELECT SUM(S9) FROM #TMP_000),0) <> ISNULL((SELECT SUM(S9) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(S9) FROM @NADO),0) - ISNULL((SELECT SUM(S9) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY S9 DESC)
	END				
	
--Корректировка сумма для отчётного квартала
	IF ISNULL((SELECT SUM(SM1) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM1 = ISNULL(SM1,0) + ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0) - ISNULL((SELECT SUM(SM1) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M1) FROM @NADO),0) - ISNULL((SELECT SUM(SM1) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM1 DESC)
	END		

	IF ISNULL((SELECT SUM(SM2) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM2 = ISNULL(SM2,0) + ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0) - ISNULL((SELECT SUM(SM2) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M2) FROM @NADO),0) - ISNULL((SELECT SUM(SM2) FROM #TMP_000),0)		
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM2 DESC)
	END	

	IF ISNULL((SELECT SUM(SM3) FROM #TMP_000),0) <> ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0)
	BEGIN
		UPDATE #TMP_000 
		SET SM3 = ISNULL(SM3,0) + ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0) - ISNULL((SELECT SUM(SM3) FROM #TMP_000),0),
			SM_ALL = ISNULL(SM_ALL,0) + ISNULL((SELECT SUM(SUM_M3) FROM @NADO),0) - ISNULL((SELECT SUM(SM3) FROM #TMP_000),0)
		WHERE PERS_LINK = (SELECT TOP 1 PERS_LINK FROM #TMP_000 ORDER BY SM3 DESC)
	END	

	INSERT INTO #TMP
	SELECT R1.*, SM_ALL, SM1+SM2+SM3, SM1, SM2, SM3
	FROM #TMP0 R1, #TMP_000 R2 
	WHERE R1.PERS_LINK = R2.PERS_LINK
	
	IF @REP = 0
		SELECT * FROM #TMP ORDER BY FIO
	ELSE
	BEGIN
		--Вывод для РСВ-1, 4-ФСС
		DECLARE @Cur1 CURSOR, @LINK INT, @NUM_PP INT, @MAX_LINK INT, @FIO VARCHAR(254)
		SET @MAX_LINK = ISNULL((SELECT MAX(LINK) FROM #TMP),0)
		SET @NUM_PP = @MAX_LINK
		SET @Cur1 = CURSOR FORWARD_ONLY

		FOR SELECT DISTINCT LINK, FIO from #TMP ORDER BY FIO

		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO @LINK, @FIO
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				SET @NUM_PP = @NUM_PP + 1
				UPDATE #TMP SET LINK = @NUM_PP WHERE LINK = @LINK
			END
			FETCH NEXT FROM @Cur1 INTO @LINK, @FIO
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1
		
		UPDATE #TMP SET LINK = LINK - @MAX_LINK

		SELECT
			CODE = CONVERT(VARCHAR(10),LINK),
			COL1 = CONVERT(VARCHAR(10),LINK),
			COL2 = FIO,
			COL3 = ISNULL(CONVERT(VARCHAR(10),DATE_SPR,104),''),
			COL4 = ISNULL(CONVERT(VARCHAR(10),PER_END,104),''),
			COL5 = SM_ALL, 
			COL6 = SM1, 
			COL7 = SM2, 
			COL8 = SM3
		FROM
			#TMP
		ORDER BY
			LINK
	
	END

DROP TABLE #TMP		

END





GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_12_PFR_INV] TO PUBLIC

GO





GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[XK_SET_ISUSED_BY_BUFFER]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XK_SET_ISUSED_BY_BUFFER]
GO

--- Устанавливает\Снимает признак "Используется в учете" ---
--- Используется для списков справочников ---
CREATE PROCEDURE dbo.XK_SET_ISUSED_BY_BUFFER
	@strOBJ_CODE	VARCHAR (30),
	@strBUFFER_NAME	VARCHAR (254),
	@iSET_VALUE	TINYINT,
	@iNOT_CLEAR_BUFFER	TINYINT = 0
AS
BEGIN
	DECLARE @strTABLE_NAME VARCHAR (254), 
		@iRET	INT,
		@varKStrancount INT

	EXECUTE @iRET = dbo.X_GET_PROP @strOBJ_CODE, 'SERVER_TABLE_NAME', @strTABLE_NAME OUTPUT

	SET @iSET_VALUE = CASE
				WHEN ISNULL (@iSET_VALUE, 0) = 0 THEN 0
				ELSE 1
			END

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	---!!! ОБНОВЛЕНИЕ ЗАПИСЕЙ !!!---
	--- Группы активов ---
	IF @strTABLE_NAME = 'GROUP_INV'		
		UPDATE T1 SET ISUSED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.GROUP_INV T1 ON (T1.LINK = BUF.LINK)

	--- КБК ---
	IF @strTABLE_NAME = 'KL_KBK'		
		UPDATE T1 SET USED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.KL_KBK T1 ON (T1.LINK = BUF.LINK)

	--- НОМЕНКЛАТУРА ---
	IF @strTABLE_NAME = 'NOMENCLATURE'		
		UPDATE T1 SET ISUSED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.NOMENCLATURE T1 ON (T1.LINK = BUF.LINK)

	--- ХОЗ. ОПЕРАЦИИ ---
	IF @strTABLE_NAME = 'XOZ_OPER'		
		UPDATE T1 SET USED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.XOZ_OPER T1 ON (T1.LINK = BUF.LINK)

	--- ВИДЫ ФИНАНСОВОГО ОБЕСПЕЧЕНИЯ ---
	IF @strTABLE_NAME = 'FIN_SOURCE'		
		UPDATE T1 SET ISUSED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.FIN_SOURCE T1 ON (T1.LINK = BUF.LINK)

	--- Организации ---
	IF @strTABLE_NAME = 'DEPARTMENTS'		
		UPDATE T1 SET ISUSED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.DEPARTMENTS T1 ON (T1.LINK = BUF.LINK)

	--- Виды НДС ---
	IF @strTABLE_NAME = 'TYPE_OPER_NDS'		
		UPDATE T1 SET ISUSED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.TYPE_OPER_NDS T1 ON (T1.LINK = BUF.LINK)

	IF ISNULL (@iNOT_CLEAR_BUFFER, 0) = 0
		EXECUTE @iRET = dbo.BUFFERCLEAR @strBUFFER_NAME

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0
END
GO

GRANT EXECUTE ON dbo.[XK_SET_ISUSED_BY_BUFFER] TO PUBLIC
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_PRINT_RRO1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_PRINT_RRO1]
GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RT_PRINT_RRO1
	@LSF int,
	@empty_row tinyint,
	@PeriodCode datetime
AS
	declare @link_f int,
			@link_t int,
			-----------
			@nlen int,
			@tmp_table varchar(100),
			@cstr varchar(8000)

	set @nlen = 43

	create table #table1 (
		col1  varchar(50),
		col2  varchar(8000), 
		col3  varchar(9), 
		col4  varchar(8000), 
		col5  varchar(8000),
		col6  varchar(1000),
		col7  varchar(254),
		col8  varchar(254),
		col9  varchar(254),
		col10 varchar(254),
		col11 varchar(254),
		col12 varchar(254),
		col13 varchar(254),
		col14 varchar(254),
		col15 varchar(254),
		col16 varchar(254),
		col17 varchar(254),
		col18 varchar(8000),
		col19 varchar(1000),
		col20 varchar(254),
		col21 varchar(254),
		col22 varchar(254),
		col23 varchar(254),
		col24 varchar(254),
		col25 varchar(254),
		col26 varchar(254),
		col27 varchar(254),
		col28 varchar(254),
		col29 varchar(254),
		col30 varchar(254),
		col31 numeric(20,4),
		col32 numeric(20,4),
		col33 numeric(20,4),
		col34 numeric(20,4),
		col35 numeric(20,4),
		col36 numeric(20,4),
		col37 varchar(8000),
		col38 varchar(3),
		code varchar(50))
	declare @table2 table (
		col1  varchar(50),
		col2  varchar(8000), 
		col3  varchar(9), 
		col4  varchar(8000), 
		col5  varchar(8000),
		col6  varchar(8000),
		col7  varchar(8000),
		col8  varchar(8000),
		col9  varchar(8000),
		col10 varchar(8000),
		col11 numeric(20,4),
		col12 numeric(20,4),
		col13 numeric(20,4),
		col14 numeric(20,4),
		col15 numeric(20,4),
		col16 numeric(20,4),
		col17 varchar(8000),
		del tinyint,
		orders varchar(50))
	
	select @link_f = link_form from dbo.report_saved_forms where link_saved_form = @LSF
	select @link_t = link_table from dbo.report_tables where link_form = @link_f and orders = 1

	EXEC dbo.X_GET_TABLE_NAME @tmp_table OUTPUT
	set @cstr='exec ri_proc_t'+ltrim(str(@link_t))+' '+ltrim(str(@LSF))+',default,default,default,default,default,0,'+@tmp_table

	print @cstr
	execute(@cstr)



	set @cstr='
		insert into #table1 (col1,col2,col3,col4, col5, col6, col7, col8, col9,col10,col11,col12,col13,col14,col15,col16,col17,col18,col19,col20,col21,col22,col23,col24,col25,col26,col27,col28,col29,col30,col31,col32,col33,col34,col35,col36,col37,col38,code)
		select				 col7,col8,col9,col10,col11,null,col17,col18,col20,col19,col12,col13,col14,col15,col16,col21,col22,col23,null ,col29,col30,col32,col31,col24,col25,col26,col27,col28,col33,col34,col1, col2, col3, col4, col5 ,col6, col35,col36,code from '+@tmp_table+' where rtrim(col9) in (select rtrim(code) from dbo.RT_GET_RECORDS_RRO(1,'''+rtrim(convert(varchar,@PeriodCode,112))+'''))'



	execute(@cstr)
--	set @cstr='select * from '+@tmp_table
--	execute(@cstr)
	set @cstr='drop table '+@tmp_table
	execute(@cstr)


	-- заполнили таблицу #table1
	-- select * from #table1
	update #table1
	set col6 = case
					when len([col11]) !> 0 and len([col12]) !> 0 and len([col13]) !> 0 and len([col14]) !> 0 and len([col15]) !> 0
					then ''
					else 
						case
							when len([col11]) > 0 
							then 'абз. ' + [col11]
							else ''
						end +
						case
							when len([col12]) > 0 
							then (case when len([col11]) > 0 then ', ' else '' end) + 'подп. ' + [col12]
							else ''
						end +
						case
							when len([col13]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 then ', ' else '' end) + 'п. ' + [col13]
							else ''
						end +
						case
							when len([col14]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 or len([col13]) > 0 then ', ' else '' end) + 'ч. ' + [col14]
							else ''
						end +
						case
							when len([col15]) > 0 
							then (case when len([col11]) > 0 or len([col12]) > 0 or len([col13]) > 0 or len([col14]) > 0 then ', ' else '' end) + 'ст. ' + [col15]
							else ''
						end
				end,
		 col19 = case
					when len([col24]) !> 0 and len([col25]) !> 0 and len([col26]) !> 0 and len([col27]) !> 0 and len([col28]) !> 0
					then ''
					else 
						case
							when len([col24]) > 0 
							then 'абз. ' + [col24]
							else ''
						end +
						case
							when len([col25]) > 0 
							then (case when len([col24]) > 0 then ', ' else '' end) + 'подп. ' + [col25]
							else ''
						end +
						case
							when len([col26]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 then ', ' else '' end) + 'п. ' + [col26]
							else ''
						end +
						case
							when len([col27]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 or len([col26]) > 0 then ', ' else '' end) + 'ч. ' + [col27]
							else ''
						end +
						case
							when len([col28]) > 0 
							then (case when len([col24]) > 0 or len([col25]) > 0 or len([col26]) > 0 or len([col27]) > 0 then ', ' else '' end) + 'ст. ' + [col28]
							else ''
						end
				end

	declare @col1 varchar(50),
			@col3 varchar(50),
			@orders varchar(50),
			@cStr1 varchar(8000),
			@cStr2 varchar(8000),
			@cStr3 varchar(8000),
			@i int,
			@nNumRow int


	-- если не задан пункт (col1) то, очищаем все колонки кроме колонок с суммами
	update #table1
	set col4 = '', 
		col5 = '', 
		col6 = '', 
		col7 = '', 
		col8 = '', 
		col9 = '',
		col10 = '',
		col11 = '',
		col12 = '',
		col13 = '',
		col14 = '',
		col15 = '',
		col16 = '',
		col17 = '',
		col18 = '',
		col19 = '',
		col20 = '',
		col21 = '',
		col22 = '',
		col23 = '',
		col24 = '',
		col25 = '',
		col26 = '',
		col27 = '',
		col28 = '',
		col29 = '',
		col30 = '',
		col37 = '',
		col38 = ''
	where len(col1)=0
	-- если @empty_row = 1 то добавляем в таблицу #table1 все узлы дерева
	if @empty_row = 1 begin
		insert into #table1 (col1,col2,col3,col38)
		select distinct pnum, true_name, code, '000' from dbo.RT_GET_RECORDS_RRO(1,@PeriodCode) where rtrim(code) not in (select rtrim(col3) from #table1)
	end

	create table #tmp_table(nnp varchar(50), code varchar(9), orders varchar(20))
	insert into #tmp_table (nnp, code, orders)
	select col1,col3,'' from #table1 group by col1,col3
--	select * from #tmp_table
	exec dbo.RT_RRO_ORDERS_BY_TREE
--	select * from #tmp_table


	declare the_cursor cursor local static for
	--select col1,col3,dbo.RT_RRO_NORMALIZE_NNP(col1) as Orders from #table1 group by col1,col3 order by dbo.RT_RRO_NORMALIZE_NNP(col1)
	select nnp,code,orders from #tmp_table order by orders
	open the_cursor
	fetch next from the_cursor into @col1,@col3,@orders 
	while @@fetch_status = 0 begin
		insert into @table2 (col1,col3,orders,del) values (@col1,@col3,@orders,0)
		-- col2
		-- поле Наименование полномочия РО. 
		-- используем значение в строке с минимальным кодом строки

	
		update @table2
		set col2 = isnull((
			select left(rtrim(col2),1000) from #table1 where col1 = @col1 and col3 = @col3 and code = (select min(code) from #table1 where col1 = @col1 and col3 = @col3)
		), col2)
		where col1 = @col1 and col3 = @col3

		update @table2
		set col2 = isnull((
			select left(rtrim(col2),1000) from #table1 where col1 = @col1 and col3 = @col3 and col38 = (select min(col38) from #table1 where col1 = @col1 and col3 = @col3)
		), col2)
		where col1 = @col1 and col3 = @col3 and isnull(col2,'')= ''

		-- col4
		-- поле Код 
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем)
		select @cStr = col4 from #table1 where col1 = @col1 and col3 = @col3 group by col4
		-- и, собственно, запихиваем это дело в @table2
		update @table2
		set col4 = @cStr
		where col1 = @col1 and col3 = @col3

		
		exec DropTempTable '#tmp1'
		create table #tmp1 (nn int identity(1,1), col5 varchar(8000), col6 varchar(8000), col7 varchar(8000), norm_col5 varchar(8000), norm_col6 varchar(8000), norm_col7 varchar(8000))	
		set @nNumRow = 0
		insert into #tmp1 (col5, col6, col7, norm_col5, norm_col6, norm_col7)
		select  col5,
			    col6,
			    col7,
			    norm_col5 = dbo.RT_RRO_CUTWORD(col5,@nlen),
			    norm_col6 = dbo.RT_RRO_CUTWORD(col6,@nlen),
				norm_col7 = dbo.RT_RRO_CUTWORD(col7,@nlen)
		from #table1 
		where col1 = @col1 and col3 = @col3 and col38/*код строки*/ in (select min(col38/*код строки*/) from #table1 where col1 = @col1 and col3 = @col3 group by col8,col9,col10,col11,col12,col13,col14,col15 having len(col8)>0 or len(col9)>0 or len(col10)>0 or len(col11)>0 or len(col12)>0 or len(col13)>0 or len(col14)>0 or len(col15)>0)
		select @nNumRow = @@ROWCOUNT		

		update #tmp1 set norm_col6 = norm_col6 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col5) !< dbo.RT_RRO_COUNT_CR(norm_col6) then dbo.RT_RRO_COUNT_CR(norm_col5) - dbo.RT_RRO_COUNT_CR(norm_col6) else 0 end)
		update #tmp1 set norm_col7 = norm_col7 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col5) !< dbo.RT_RRO_COUNT_CR(norm_col7) then dbo.RT_RRO_COUNT_CR(norm_col5) - dbo.RT_RRO_COUNT_CR(norm_col7) else 0 end)

		if @nNumRow	> 0 begin
			set @cStr1 = ''
			set @cStr2 = ''
			set @cStr3 = ''
--			select @cStr1 = left(norm_col5,len(norm_col5)-2), @cStr2 = left(norm_col6,len(norm_col6)-2), @cStr3 = left(norm_col7,len(norm_col7)-2) from #tmp1 where nn = 1
			select
					@cStr1 = case when len(norm_col5)>1 then left(norm_col5,len(norm_col5)-2) else '' end, 
					@cStr2 = case when len(norm_col6)>1 then left(norm_col6,len(norm_col6)-2) else '' end, 
					@cStr3 = case when len(norm_col7)>1 then left(norm_col7,len(norm_col7)-2) else '' end
			from #tmp1 where nn = 1
			update @table2
			set col5 = replace(@cStr1,char(13)+char(10),char(10)), col6 = replace(@cStr2,char(13)+char(10),char(10)), col7 = replace(@cStr3,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		
			delete from #tmp1 where nn = 1			

			while exists(select * from #tmp1) begin
				select top 1 @i = nn from #tmp1

				if not exists(select * from @table2 where orders = @orders + right('000'+cast(@i as varchar),3))
					insert into @table2 (orders,del) values (@orders + right('000'+cast(@i as varchar),3),0)

--				select @cStr1 = left(norm_col5,len(norm_col5)-2), @cStr2 = left(norm_col6,len(norm_col6)-2), @cStr3 = left(norm_col7,len(norm_col7)-2) from #tmp1 where nn = @i
				select
						@cStr1 = case when len(norm_col5)>1 then left(norm_col5,len(norm_col5)-2) else '' end, 
						@cStr2 = case when len(norm_col6)>1 then left(norm_col6,len(norm_col6)-2) else '' end, 
						@cStr3 = case when len(norm_col7)>1 then left(norm_col7,len(norm_col7)-2) else '' end
				from #tmp1 where nn = @i

				update @table2
				set col5 = replace(@cStr1,char(13)+char(10),char(10)), col6 = replace(@cStr2,char(13)+char(10),char(10)), col7 = replace(@cStr3,char(13)+char(10),char(10))
				where orders = @orders + right('000'+cast(@i as varchar),3)
				
				delete from #tmp1 where nn = @i
			end
		end

		exec DropTempTable '#tmp1'

		-- col18,col19,col20
		-- поля Наименование и реквизиты нормативного правового акта, абзац, подпункт и т.д., дата вступления в силу и срок действия
		-- собираем все уникальные значения в строчку (дублирующиеся игнорируем) самое забавное то, что дубликаты ищем по след. колонкам: col21 - col28
		exec DropTempTable '#tmp2'
		create table #tmp2 (nn int identity(1,1), col18 varchar(8000), col19 varchar(8000), col20 varchar(8000), norm_col18 varchar(8000), norm_col19 varchar(8000), norm_col20 varchar(8000))	
		set @nNumRow = 0
		insert into #tmp2 (col18, col19, col20, norm_col18, norm_col19, norm_col20)
		select  col18,
			    col19,
			    col20,
			    norm_col18 = dbo.RT_RRO_CUTWORD(col18,@nlen),
			    norm_col19 = dbo.RT_RRO_CUTWORD(col19,@nlen),
				norm_col20 = dbo.RT_RRO_CUTWORD(col20,@nlen)
		from #table1 
		where col1 = @col1 and col3 = @col3 and col38/*код строки*/ in (select min(col38/*код строки*/) from #table1 where col1 = @col1 and col3 = @col3 group by col21,col22,col23,col24,col25,col26,col27,col28 having len(col21)>0 or len(col22)>0 or len(col23)>0 or len(col24)>0 or len(col25)>0 or len(col26)>0 or len(col27)>0 or len(col28)>0)
		select @nNumRow = @@ROWCOUNT		
		
		update #tmp2 set norm_col19 = norm_col19 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col18) !< dbo.RT_RRO_COUNT_CR(norm_col19) then dbo.RT_RRO_COUNT_CR(norm_col18) - dbo.RT_RRO_COUNT_CR(norm_col19) else 0 end)
		update #tmp2 set norm_col20 = norm_col20 + replicate(char(13)+char(10),case when dbo.RT_RRO_COUNT_CR(norm_col18) !< dbo.RT_RRO_COUNT_CR(norm_col20) then dbo.RT_RRO_COUNT_CR(norm_col18) - dbo.RT_RRO_COUNT_CR(norm_col20) else 0 end)

		if @nNumRow	> 0 begin
			set @cStr1 = ''
			set @cStr2 = ''
			set @cStr3 = ''
--			select @cStr1 = left(norm_col18,len(norm_col18)-2), @cStr2 = left(norm_col19,len(norm_col19)-2), @cStr3 = left(norm_col20,len(norm_col20)-2) from #tmp2 where nn = 1
			select
					@cStr1 = case when len(norm_col18)>1 then left(norm_col18,len(norm_col18)-2) else '' end, 
					@cStr2 = case when len(norm_col19)>1 then left(norm_col19,len(norm_col19)-2) else '' end, 
					@cStr3 = case when len(norm_col20)>1 then left(norm_col20,len(norm_col20)-2) else '' end
			from #tmp2 where nn = 1

			update @table2
			set col8 = replace(@cStr1,char(13)+char(10),char(10)), col9 = replace(@cStr2,char(13)+char(10),char(10)), col10 = replace(@cStr3,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		
			delete from #tmp2 where nn = 1			

			while exists(select * from #tmp2) begin
				select top 1 @i = nn from #tmp2

				if not exists(select * from @table2 where orders = @orders + right('000'+cast(@i as varchar),3))
					insert into @table2 (orders,del) values (@orders + right('000'+cast(@i as varchar),3),0)

--				select @cStr1 = left(norm_col18,len(norm_col18)-2), @cStr2 = left(norm_col19,len(norm_col19)-2), @cStr3 = left(norm_col20,len(norm_col20)-2) from #tmp2 where nn = @i
				select 
					@cStr1 = case when len(norm_col18)>1 then left(norm_col18,len(norm_col18)-2) else '' end, 
					@cStr2 = case when len(norm_col19)>1 then left(norm_col19,len(norm_col19)-2) else '' end, 
					@cStr3 = case when len(norm_col20)>1 then left(norm_col20,len(norm_col20)-2) else '' end
				from #tmp2 where nn = @i
				update @table2
				set col8 = replace(@cStr1,char(13)+char(10),char(10)), col9 = replace(@cStr2,char(13)+char(10),char(10)), col10 = replace(@cStr3,char(13)+char(10),char(10))
				where orders = @orders + right('000'+cast(@i as varchar),3)
				
				delete from #tmp2 where nn = @i
			end
		end

		exec DropTempTable '#tmp2'

		-- col31,col32,col33,col34,col35,col36
		-- числовые поля
		update @table2
		set col11 = (select sum(col31) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3
 
		update @table2
		set col12 = (select sum(col32) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3

		update @table2
		set col13 = (select sum(col33) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3

		update @table2
		set col14 = (select sum(col34) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3
		
		update @table2
		set col15 = (select sum(col35) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3

		update @table2
		set col16 = (select sum(col36) from #table1 where col1 = @col1 and col3 = @col3)
		where col1 = @col1 and col3 = @col3

		-- и наконец примечание col37
		select  col37 = max(col37),
			    norm_col37 = dbo.RT_RRO_CUTWORD(max(col37),@nlen/2)
		into #tmp3 
		from #table1 
		where col1 = @col1 and col3 = @col3 
		group by col37
		having len(col37) > 0
		
		set @cStr = ''
		update #tmp3 set @cStr = @cStr + norm_col37
			update @table2
			set col17 = replace(@cStr,char(13)+char(10),char(10))
			where col1 = @col1 and col3 = @col3
		drop table #tmp3

		fetch next from the_cursor into @col1,@col3,@orders 
	end
	close the_cursor
	deallocate the_cursor	

	select col1,col3,col4,col5,col6,replace(col7,'01.01.2999','не установлен') as col7,col8,col9,replace(col10,'01.01.2999','не установлен') as col10,col11,col12,col13,col14,col15,col16,col17,col2,del,
   orders = (SELECT COUNT(*) FROM @table2 T1 WHERE T1.orders < T.orders)   
   from @table2 T order by orders

	drop table #table1
	drop table #tmp_table
GO
GRANT EXECUTE ON dbo.[RT_PRINT_RRO1] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
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_get_all_adm_table]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[rn_get_all_adm_table]
GO

/*

	© Кейсистемс (Keysystems), 2006
	Редактирование/создание отчета/свода/свода сводов в WEB
*/


CREATE       PROCEDURE dbo.rn_get_all_adm_table
	@LSF int,
	@iTable  int, -- порядок таблицы
	@bDeleteEmptyRows int=0,
	@allAtr int=1,
	@AddAtr int = 0 -- всегда добавлять администратор
AS

declare @iLF int,@LT int


create table #org (code varchar(20), name varchar(250))

declare @nameProcTable varchar(50),@cRuStr varchar(8000), @cStrNotItog varchar(1000), @cStrItog varchar(1000), @cStrCols varchar(1000)
set @nameProcTable='dbo.RI_PROC_T'

set @cStrNotItog = case @iTable	when 1 then ' where  CODE not like ''8500000000%'' and not (CODE like ''9600000000%'' or CODE like ''7900000000%'') and orders = 0 '
								when 2 then ' where not (CODE like ''9600000000%'' or CODE like ''7900000000%'') and orders = 0 '
								when 3 then ' where CODE not like ''5009000000000%'' and CODE not like ''5200100000000%'' and CODE not like ''6200200000000%'' and CODE <> ''500000'' and left(code,7) not in (''8000400'', ''8100500'', ''8100500'', ''8110600'', ''8120700'', ''8200800'', ''8210900'', ''8220100'', ''8230200'', ''8240300'')'
								else '' 
					end

set @cStrItog = case @iTable	when 1 then ' where CODE like ''8500000000%'' or  (CODE like ''96000000000%'' or CODE like ''79000000000%'') or (orders <>0 and code like ''%9600%'') '
								when 2 then ' where (CODE like ''96000000000%'' or CODE like ''79000000000%'') or (orders <>0 and code like ''%9000000%'') '
								when 3 then ' where CODE like ''50090000000000%'' or CODE like ''5200100000000%'' or CODE like ''6200200000000%'' or CODE = ''500000'' or left(code,7) in (''8000400'', ''8100500'', ''8100500'', ''8110600'', ''8120700'', ''8200800'', ''8210900'', ''8220100'', ''8230200'', ''8240300'') '
								else ' where 1=0 ' 
					end

declare @iCode_Col int,@atr varchar(100),@tmp_table_main varchar(100),@tmp_table varchar(100),@cnt int,@LF int,@code_form varchar(50),@begin_date datetime,@period_type int,@period_number int,@link_org int,@link_type_svod int
create table #LSF (lsf int, link_Form int, codeForm char(20), startDate datetime)

select @code_form=code,@LF=link_form from report_forms where link_form=(select top 1 link_form from report_saved_forms where link_saved_form=@LSF)

select @LT=LINK_TABLE from report_tables where link_form=@LF and  orders=@iTable

--select @LSF=link_saved_form,@begin_date=begin_date,@period_type=period_type,@period_number=period_number,@link_org=link_organization,@link_type_svod=link_type_svod from report_saved_forms where link_saved_form=@LSF

EXEC dbo.X_GET_TABLE_NAME @tmp_table_main OUTPUT
EXEC dbo.X_GET_TABLE_NAME @tmp_table OUTPUT

			select @LSF=link_saved_form,@begin_date=begin_date,@period_type=period_type,@period_number=period_number,@link_org=link_organization,@link_type_svod=link_type_svod from report_saved_forms where link_saved_form=@LSF
			delete #LSF
		IF @allAtr=1
		begin
			insert #LSF (lsf,link_form,codeform,startDate)
			select max(RSF1.link_saved_form) as link_saved_form, RSF1.link_form, RF.code as code_form, max(RF.Start_Date) as Start_Date
			from report_saved_forms RSF1 (NOLOCK) left join report_forms RF (NOLOCK) on RSF1.link_form = RF.link_form
			  where RSF1.link_organization = @link_Org
            AND RSF1.del = 0
				and isnull(RSF1.Link_Type_Svod, 0) = isnull(@link_type_svod, 0)
				and year(RSF1.begin_Date) = year(@Begin_date)
				and RSF1.period_type = @period_Type
				and RSF1.period_number = @period_number
				and RSF1.IsChangeAnalit = 0
				and RSF1.version = (select max(version) from report_saved_forms RSF2 (NOLOCK)
						where RSF2.link_organization = @link_Org
                     AND RSF2.del = 0
							and isnull(RSF2.Link_Type_Svod, 0) = isnull(@link_type_svod, 0)
							and year(RSF2.begin_Date) = year(@Begin_date) 
							and RSF2.period_type = @period_Type
							and RSF2.period_number = @period_number
							and RSF2.link_form = RSF1.link_form 
							and RSF2.IsChangeAnalit = 0
			 and isnull(RSF2.atr_code,'')=isnull(RSF1.atr_code,'')                       
			)
			group by RSF1.link_form, RF.code,isnull(RSF1.atr_code,'')

			delete #LSF where link_form<>@LF
		end
		else
			insert #LSF (lsf,link_form,codeform,startDate)
			select @LSF,link_form,code,start_date from report_forms where link_form=(select top 1 link_form from report_saved_forms where link_saved_form=@lsf)



		delete #LSF where link_form<>@LF
		select @iCode_Col=orders from report_coloumns where link_col=(select top 1 link_code_col from report_tables where link_table=@LT)
		select top 1 @LSF=lsf from #LSF 
		delete #LSF where lsf=@lsf
		set @atr=rtrim(dbo.RN_GET_ATR_VALUE(@lsf,'REPORTS_ATR_ADM'))
		SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@LT)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table_main
		print @cRuStr			
		execute (@cRuStr)		


		IF @allAtr=1 or @AddAtr = 1
		begin
/*
			SET @cRuStr='UPDATE '+@tmp_table_main+' set COL'+ltrim(str(@iCode_Col))+'=rtrim('''+@atr+''')+RTRIM(COL'+ltrim(str(@iCode_Col))+'),CODE=rtrim('''+@atr+''')+RTRIM(CODE)'  + @cStrNotItog + '
UPDATE '+@tmp_table_main+' set COL'+ltrim(str(@iCode_Col))+'=''000''+RTRIM(COL'+ltrim(str(@iCode_Col))+'),CODE=''000''+RTRIM(CODE)'  + @cStrItog
*/

			SET @cRuStr='ALTER TABLE '+@tmp_table_main+' ALTER COLUMN COL'+ltrim(str(@iCode_Col))+' VARCHAR(50) ALTER TABLE '+@tmp_table_main+' ALTER COLUMN CODE VARCHAR(50) UPDATE '+@tmp_table_main+' set COL'+ltrim(str(@iCode_Col))+'= case when '+rtrim(replace(@cStrItog,'where',''))+' then ''000''+RTRIM(COL'+ltrim(str(@iCode_Col))+') else rtrim('''+@atr+''')+RTRIM(COL'+ltrim(str(@iCode_Col))+') end,
			CODE = case when '+rtrim(replace(@cStrItog,'where',''))+' then ''000''+RTRIM(CODE) else rtrim('''+@atr+''')+RTRIM(CODE) end'
		
			execute (@cRuStr)
		end

		while exists(select * from #LSF) 
			BEGIN

				select top 1 @LSF=lsf from #LSF 
				delete #LSF where lsf=@lsf
				SET @cRuStr = 'EXEC '+@nameProcTable + ltrim(convert(varchar(15),@LT)) + ' @varKSLSF = ' + convert(varchar(15), @LSF)+ ', @bDeleteEmptyRows = ' + ISNULL(CAST(@bDeleteEmptyRows AS VARCHAR),'NULL')+',@del_fcol =1,@tmp_table='+@tmp_table

				execute (@cRuStr)					
				set @atr=dbo.RN_GET_ATR_VALUE(@lsf,'REPORTS_ATR_ADM')

				SET @cRuStr='UPDATE '+@tmp_table+' set COL'+ltrim(str(@iCode_Col))+'=rtrim('''+@atr+''')+COL'+ltrim(str(@iCode_Col))+',CODE=rtrim('''+@atr+''')+CODE' + @cStrNotItog + '
UPDATE '+@tmp_table+' set COL'+ltrim(str(@iCode_Col))+'=''000''+COL'+ltrim(str(@iCode_Col))+',CODE=''000''+CODE' + @cStrItog
				--	print @cRuStr
				execute (@cRuStr)	


				SET @cRuStr='insert '+@tmp_table_main+' select * from '+@tmp_table+' drop table ' +@tmp_table
				--	print @cRuStr
				execute (@cRuStr)					
				

			end
		
		set @cStrCols = 'max(checked) as checked, max(Upd) as Upd, min(del) as del, max(link_saved_form) as link_saved_form, max(link_row) as link_row, max(orders) as orders, max(Calc_orders) as Calc_orders, max(Print_NULL) as Print_Null, Code'

		select @cStrCols = @cStrCols + ', ' + case Col_Type when 0 then 'sum(COL' else 'max(COL' end + LTRIM(STR(orders)) + ') as COL'  + LTRIM(STR(orders))
		from report_coloumns 
		where Link_Table = @LT 
		order by orders

		SET @cRuStr='select ' + @cStrCols + ' from  '+@tmp_table_main+' group by Code order by left(code,3), orders, code  drop table ' +@tmp_table_main
--			print @cRuStr
		execute (@cRuStr)					


GO
GRANT EXECUTE ON dbo.[rn_get_all_adm_table] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
EXECUTE RO_WEB_EDIT_OBJECT_METHOD_SVOD 21230
*/


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_REPORT_JURN_INVOICE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_JURN_INVOICE]

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.BK_REPORT_JURN_INVOICE
	@varKSdDate_1 datetime,
	@varKSdDate_2 DATETIME,
	@varKSnOption1 int,	-- 1 - Полученные счета-фактуры
				-- 2 - Выданные счета-фактуры -- 
				-- 3 - Общий --
	@intSVOD_ZB	int	-- Сводный отчет (ЦБ) 
AS
BEGIN

	DECLARE @intDEP_LINK	INT,
		@strHD_Org_Name VARCHAR (254),
		@strHD_PUR_INN VARCHAR (20),
		@strHD_PUR_KPP VARCHAR (20),

		@DOC_LINK	INT,
		@NDS_TYPE	VARCHAR (4),
		@NDS_TYPE_VAL	VARCHAR (254),

		@CUR_DOC_LINK	INT,

		@strSFIN_CODE CHAR (1),
		@cVal_SFIN char(1), @nOtborLinkSFIN int	-- Отбор источников финансирования --

	DECLARE @TAB1 TABLE (LINK_DOC INT,
			DEP1	INT,

			DOC_DATE1 DATETIME,
			DOC_NUM1 VARCHAR (50),

			DOC_DATE2 DATETIME,
			DOC_NUM2 VARCHAR (50),

			COR_DATE1 DATETIME,
			COR_NUM1 VARCHAR (50),

			DATE_OPL DATETIME,

			SORT_NUM VARCHAR (50),
			SORT_DATE	DATETIME,

			IS_COR	TINYINT,
			ORDERS	TINYINT)

	--- Сводный отчет (ЦБ) --- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @intDEP_LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())

	IF @intSVOD_ZB = 1
		SET @intDEP_LINK = dbo.GetOwnDepLink ()

	SELECT	@strHD_Org_Name = dbo.BK_GET_PRINT_DEP_NAME (LINK),
		@strHD_PUR_INN = INN,
		@strHD_PUR_KPP = KPP
	FROM dbo.DEPARTMENTS
	WHERE LINK = @intDEP_LINK

	SELECT @strHD_Org_Name = ISNULL (@strHD_Org_Name, ''),
		@strHD_PUR_INN = ISNULL (@strHD_PUR_INN, ''),
		@strHD_PUR_KPP = ISNULL (@strHD_PUR_KPP, '')

	IF @intSVOD_ZB = 1
		SET @strHD_Org_Name = RTRIM (@strHD_Org_Name) + '(ЦБ)'

	IF @varKSnOption1 = 1		-- Полученные счета-фактуры --
			OR @varKSnOption1 = 3
	BEGIN
		INSERT INTO @TAB1	-- Отбор всех полученных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.SEL_LINK,	-- ПРОДАВЕЦ --

			DOC.[DATE],
			DOC.NUMBER,

			DOC.COR_DATE, 
			DOC.COR_NUM,

			NULL,
			'',

			DOC.DATE_BASE,

			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			DOC.[DATE],

			0,
			1
		FROM dbo.DOCUMENTS_INVOICE_RECEIVED DOC
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)

		INSERT INTO @TAB1	-- Отбор всех кор. полученных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.SEL_LINK,	-- ПРОДАВЕЦ --

			DOC.OSN_DATE,
			DOC.OSN_NUM,

			DOC.COR_DATE, 
			DOC.COR_NUM,

			DOC.[DATE],
			DOC.NUMBER,

			DOC.DATE_BASE,

			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			DOC.[DATE],

			1,
			1
		FROM dbo.DOCUMENTS_INVOICE_COR_IN DOC
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)
	END

	IF @varKSnOption1 = 2		-- Книга продаж (Выданные счета-фактуры) --
			OR @varKSnOption1 = 3
	BEGIN
		INSERT INTO @TAB1	 -- Отбор всех выданных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.BUY_LINK,	-- ПОКУПАЕТЛЬ --

			DOC.[DATE],
			DOC.NUMBER,

			DOC.COR_DATE, 
			DOC.COR_NUM,

			NULL,
			'',

			DOC.DATE_BASE,

			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			DOC.[DATE],

			0,
			0
		FROM dbo.DOCUMENTS_INVOICE_ISSUED DOC
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)

		INSERT INTO @TAB1	-- Отбор всех кор. выданных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.BUY_LINK,	-- ПОКУПАЕТЛЬ --

			DOC.OSN_DATE,
			DOC.OSN_NUM,

			DOC.COR_DATE, 
			DOC.COR_NUM,

			DOC.[DATE],
			DOC.NUMBER,

			DOC.DATE_BASE,

			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			DOC.[DATE],

			1,
			0
		FROM dbo.DOCUMENTS_INVOICE_COR_OUT DOC
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)
	END
/*
	IF @varKSnOption1 = 2		-- Книга продаж (Выданные счета-фактуры) --
			OR @varKSnOption1 = 3
		INSERT INTO @TAB1	 -- Отбор всех выданных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.BUY_LINK,	-- ПОКУПАЕТЛЬ --
			DOC.SUMMA,
			DOC.[DATE],
			DOC.NUMBER,
			DOC.DATE_BASE,
			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			2
		FROM dbo.DOCUMENTS_INVOICE_ISSUED DOC
		INNER JOIN dbo.DEPARTMENTS DEP ON ((DEP.ZB = 1 OR DEP.[TYPE] = 4)
						AND DEP.LINK = DOC.DEP_LINK)
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND (@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK
				OR @intSVOD_ZB = 1)

*/


	-- Табличные части --
	DECLARE @TAB2 TABLE
		(DOC_LINK INT,
		NDS_TYPE VARCHAR (4),

		SUMMA NUMERIC (28,4),
		SUM_NDS NUMERIC (28,4),
		SUMMA_ALL NUMERIC (28,4),

		SUMMA_OLD NUMERIC (28,4),
		S_NDS_OLD NUMERIC (28,4),
		S_ALL_OLD NUMERIC (28,4),

		SUMMA_NEW NUMERIC (28,4),
		S_NDS_NEW NUMERIC (28,4),
		S_ALL_NEW NUMERIC (28,4),
		
			S_INC NUMERIC (28,4),
			S_DEC NUMERIC (28,4),
	
			S_NDS_INC NUMERIC (28,4),
			S_NDS_DEC NUMERIC (28,4),
	
			S_ALL_INC NUMERIC (28,4),
			S_ALL_DEC NUMERIC (28,4),

		IS_COR	TINYINT)

	-- Табличная часть с\ф --
	INSERT INTO @TAB2
	SELECT T1.LINK_DOC,
		ISNULL (T2.TNDS_CODE, ''),

		T2.SUMMA,
		T2.SUMMA_NDS,
		T2.SUMMA_ALL,
	
		T2.SUMMA,
		T2.SUMMA_NDS,
		T2.SUMMA_ALL,

		0, 0, 0,

		0, 0,
		0, 0,
		0, 0,
		0
	FROM @TAB1 T1
	INNER JOIN dbo.BK_DOC_TABLE_MZ_NDS_FN (DEFAULT) T2 ON (T2.LINK_UP = T1.LINK_DOC)
	WHERE T1.IS_COR = 0

	-- Табличная часть кор. с\ф --
	INSERT INTO @TAB2
	SELECT T1.LINK_DOC,
		ISNULL (T2.TNDS_CODE2, ''),

		0, 0, 0,		
		
		T2.SUMMA,
		T2.SUMMA_NDS,
		T2.SUMMA_ALL,

		T2.SUM_NEW,
		T2.S_NDS_NEW,
		T2.S_ALL_NEW,
		
		CASE
			WHEN T2.SUM_NEW > T2.SUMMA THEN T2.SUM_NEW - T2.SUMMA
			ELSE 0
		END,
		CASE
			WHEN T2.SUMMA > T2.SUM_NEW THEN T2.SUMMA - T2.SUM_NEW
			ELSE 0
		END,
		CASE
			WHEN T2.S_NDS_NEW > T2.SUMMA_NDS THEN T2.S_NDS_NEW - T2.SUMMA_NDS
			ELSE 0
		END,
		CASE
			WHEN T2.SUMMA_NDS > T2.S_NDS_NEW THEN T2.SUMMA_NDS - T2.S_NDS_NEW
			ELSE 0
		END,
		CASE
			WHEN T2.S_ALL_NEW > T2.SUMMA_ALL THEN T2.S_ALL_NEW - T2.SUMMA_ALL
			ELSE 0
		END,
		CASE
			WHEN T2.SUMMA_ALL > T2.S_ALL_NEW THEN T2.SUMMA_ALL - T2.S_ALL_NEW
			ELSE 0
		END,

		1
	FROM @TAB1 T1
	INNER JOIN dbo.BK_DOC_TAB_INVOICE_COR_FN (DEFAULT) T2 ON (T2.LINK_UP = T1.LINK_DOC)
	WHERE T1.IS_COR = 1

-- SELECT * FROM @TAB2
	
	-- Вычисляем суммы по документам и операции по НДС --
	DECLARE @TAB_SUM TABLE
		(DOC_LINK INT, 
		NDS_TYPE VARCHAR (100),
		SUMMA NUMERIC (28,4),
		SUM_NDS NUMERIC (28,4),
		SUMMA_ALL NUMERIC (28,4),

		S_INC NUMERIC (28,4),
		S_DEC NUMERIC (28,4),

		S_NDS_INC NUMERIC (28,4),
		S_NDS_DEC NUMERIC (28,4),

		S_ALL_INC NUMERIC (28,4),
		S_ALL_DEC NUMERIC (28,4)
		)

	-- Собираем виды операций по НДС --
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
	FOR
	SELECT DOC_LINK,
		NDS_TYPE
	FROM @TAB2
	GROUP BY DOC_LINK,
		NDS_TYPE
	ORDER BY DOC_LINK,
		NDS_TYPE

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @DOC_LINK, 
			@NDS_TYPE

	SET @CUR_DOC_LINK = 0

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @DOC_LINK <> @CUR_DOC_LINK
		BEGIN
			INSERT INTO @TAB_SUM
			SELECT DOC_LINK,
				@NDS_TYPE_VAL,
				SUM (SUMMA),
				SUM (SUM_NDS),
				SUM (SUMMA_ALL),

				SUM (S_INC),
				SUM (S_DEC),
		
				SUM (S_NDS_INC),
				SUM (S_NDS_DEC),
		
				SUM (S_ALL_INC),
				SUM (S_ALL_DEC)

			FROM @TAB2 
			WHERE DOC_LINK = @CUR_DOC_LINK
			GROUP BY DOC_LINK

			SET @CUR_DOC_LINK = @DOC_LINK 
			SET @NDS_TYPE_VAL = ''
		END

		SET @NDS_TYPE_VAL = @NDS_TYPE_VAL
			+ CASE 
				WHEN @NDS_TYPE_VAL <> '' AND @NDS_TYPE <> '' THEN ', '
				ELSE ''
			END
			+ @NDS_TYPE

		FETCH FROM #DATA_CURSOR
			INTO @DOC_LINK, 
				@NDS_TYPE
	END

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	-- Запись последней итерации --
	INSERT INTO @TAB_SUM
	SELECT DOC_LINK,
		@NDS_TYPE_VAL,
		SUM (SUMMA),
		SUM (SUM_NDS),
		SUM (SUMMA_ALL),

		SUM (S_INC),
		SUM (S_DEC),

		SUM (S_NDS_INC),
		SUM (S_NDS_DEC),

		SUM (S_ALL_INC),
		SUM (S_ALL_DEC)
	FROM @TAB2 
	WHERE DOC_LINK = @CUR_DOC_LINK
	GROUP BY DOC_LINK

-- SELECT * FROM @TAB_SUM

	DECLARE @RESULT TABLE
		(DOC_LINK INT,
		DEP_NAME VARCHAR (254), DEP_INN VARCHAR (20), DEP_KPP VARCHAR (20),
		DEP_NAME1 VARCHAR (254), DEP_INN1 VARCHAR (20), DEP_KPP1 VARCHAR (20),
		
		BIL_DATE VARCHAR (10), 
		BIL_TYPE VARCHAR (20),
		
		NDS_TYPE VARCHAR (100),

		SORT_DATE DATETIME,

		DOC_DATE1 VARCHAR (10), DOC_NUM1 VARCHAR (50),

		COR_DATE1 VARCHAR (10), COR_NUM1 VARCHAR (50),

		DOC_DATE2 VARCHAR (10), DOC_NUM2 VARCHAR (50),

		DATE_OPL VARCHAR (10), SUM_TOTAL NUMERIC (28,4),
		SUMMA NUMERIC (28,4), SUM_NDS NUMERIC (28,4),

		S_INC NUMERIC (28,4),
		S_DEC NUMERIC (28,4),

		S_NDS_INC NUMERIC (28,4),
		S_NDS_DEC NUMERIC (28,4),

		S_ALL_INC NUMERIC (28,4),
		S_ALL_DEC NUMERIC (28,4),

		REP1 TINYINT, SORT_NUM VARCHAR (50),
		ORDERS TINYINT)

	INSERT INTO @RESULT
	SELECT T1.LINK_DOC,
		@strHD_Org_Name,
		@strHD_PUR_INN,
		@strHD_PUR_KPP,

		ISNULL (D1.NAME, ''),
		ISNULL (D1.INN, ''),
		ISNULL (D1.KPP, ''),

		CONVERT (VARCHAR (10), T1.DOC_DATE1, 104),
		'1',
		
		ISNULL (TS.NDS_TYPE, ''),

		T1.SORT_DATE,

		CONVERT (VARCHAR (10), T1.DOC_DATE1, 104),
		T1.DOC_NUM1,

		CONVERT (VARCHAR (10), T1.COR_DATE1, 104),
		T1.COR_NUM1,

		CONVERT (VARCHAR (10), T1.DOC_DATE2, 104),
		T1.DOC_NUM2,

		ISNULL (CONVERT (VARCHAR (10), T1.DATE_OPL, 104), ''),

		ISNULL (TS.SUMMA_ALL, 0),
		ISNULL (TS.SUMMA, 0),
		ISNULL (TS.SUM_NDS, 0),

		ISNULL (TS.S_INC, 0),
		ISNULL (TS.S_DEC, 0),

		ISNULL (TS.S_NDS_INC, 0),
		ISNULL (TS.S_NDS_DEC, 0),

		ISNULL (TS.S_ALL_INC, 0),
		ISNULL (TS.S_ALL_DEC, 0),

		1,
		T1.SORT_NUM,
		T1.ORDERS
	FROM @TAB1 T1
	LEFT OUTER JOIN dbo.DEPARTMENTS D1 ON (D1.LINK = T1.DEP1)
	LEFT OUTER JOIN @TAB_SUM TS ON (TS.DOC_LINK = T1.LINK_DOC)

	SELECT * 
	FROM @RESULT
	ORDER BY ORDERS,
		SORT_DATE,
		SORT_NUM
END

GO


GRANT EXECUTE ON dbo.[BK_REPORT_JURN_INVOICE] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_REPORT_BOOK_SALES_PURCHASE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_BOOK_SALES_PURCHASE]

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.BK_REPORT_BOOK_SALES_PURCHASE
	@varKSdDate_1 datetime,
	@varKSdDate_2 DATETIME,
	@varKSnOption1 int,	-- 1 - Книга покупок (Полученные счета-фактуры)
				-- 2 - Книга продаж (Выданные счета-фактуры) -- 
	@intSVOD_ZB	int,	-- Сводный отчет (ЦБ) 
	@cVal_SFIN char(1), @nOtborLinkSFIN int	-- Отбор источников финансирования --
AS
BEGIN
	DECLARE @intDEP_LINK	INT,
		@strHD_Org_Name VARCHAR (254),
		@strHD_PUR_INN VARCHAR (20),
		@strHD_PUR_KPP VARCHAR (20)

	-- Источник в выборе начинается с пустого значения --
	-- Отбор источников финансирования --
	DECLARE @TAB_SFIN TABLE
		(LINK	INT,
		CODE CHAR (2))

	IF LEN (@cVal_SFIN) > 0 
	BEGIN
		INSERT INTO @TAB_SFIN
		SELECT D.LINK,
			D.CODE
		FROM dbo.OBJECT_VAR_FIN_SOURCE OVR
		INNER JOIN dbo.FIN_SOURCE D ON (D.LINK = OVR.RECORD)
		WHERE OVR.LINK_UP = @nOtborLinkSFIN
	END
	ELSE
	BEGIN
		INSERT INTO @TAB_SFIN
		SELECT D.LINK,
			D.CODE
		FROM dbo.FIN_SOURCE D 

		INSERT INTO @TAB_SFIN (LINK, CODE) 
		SELECT 0, ''
	END

	-- Шапка документа --
	DECLARE @TAB1 TABLE
		(LINK_DOC INT,
		DEP1 INT,
		TOTAL_SUM NUMERIC (28,4),
		
		-- Реквизиты с\ф --
		DOC_DATE1 DATETIME,
		DOC_NUM1 VARCHAR (50),

		-- Исправление с\ф --
		DOC_DATE2 DATETIME,
		DOC_NUM2 VARCHAR (50),

		-- Реквизиты коррект. с\ф --
		COR_DATE1	DATETIME,
		COR_NUM1	VARCHAR (50),

		-- Исправление коррект. с\ф --
		COR_DATE2	DATETIME,
		COR_NUM2	VARCHAR (50),

		DATE_OPL DATETIME,
		SORT_NUM VARCHAR (50),

		IS_COR	TINYINT		-- Корректир. с\ф	0 - с\ф, 1 - получ. с\ф, 2 - выст. с\ф
		)

	-- НДС 18% --
	DECLARE @TAB2_18 TABLE
		(LINK_DOC INT,
		NALOG NUMERIC (28,4),
		SUMMA NUMERIC (28,4),
		SFIN_LINK INT)

	-- НДС 10% --
	DECLARE @TAB2_10 TABLE
		(LINK_DOC INT,
		NALOG NUMERIC (28,4),
		SUMMA NUMERIC (28,4),
		SFIN_LINK INT)

	-- НДС 0% --
	DECLARE @TAB2_0 TABLE
		(LINK_DOC INT,
		SUMMA NUMERIC (28,4),
		SFIN_LINK INT)

	-- НДС 20% --
	DECLARE @TAB2_20 TABLE
		(LINK_DOC INT,
		NALOG NUMERIC (28,4),
		SUMMA NUMERIC (28,4),
		SFIN_LINK INT)

	-- БЕЗ НДС % --
	DECLARE @TAB2_NO_NDS TABLE
		(LINK_DOC INT,
		SUMMA NUMERIC (28,4),
		SFIN_LINK INT)

	-- Итоговая сумма по документу --
	DECLARE @TAB_DOC_SUM TABLE
		(LINK_DOC INT,
		SUMMA_ALL NUMERIC (28,4))
	
	--- Сводный отчет (ЦБ) --- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @intDEP_LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())

	IF @intSVOD_ZB = 1
		SET @intDEP_LINK = dbo.GetOwnDepLink ()

	SELECT	@strHD_Org_Name = [NAME],
		@strHD_PUR_INN = INN,
		@strHD_PUR_KPP = KPP
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @intDEP_LINK

	SELECT @strHD_Org_Name = ISNULL (@strHD_Org_Name, ''),
		@strHD_PUR_INN = ISNULL (@strHD_PUR_INN, ''),
		@strHD_PUR_KPP = ISNULL (@strHD_PUR_KPP, '')

	IF @intSVOD_ZB = 1
		SET @strHD_Org_Name = RTRIM (@strHD_Org_Name) + '(ЦБ)'

	IF @varKSnOption1 = 1		-- Книга покупок (Полученные счета-фактуры) --
		INSERT INTO @TAB1	-- Отбор всех полученных с/ф за период --
		SELECT DOC.LINK,
			DOC.SEL_LINK,	-- ПРОДАВЕЦ --
			DOC.SUMMA,
			DOC.[DATE],
			DOC.NUMBER,

			DOC.COR_DATE,
			DOC.COR_NUM,

			NULL,
			'',
			NULL,
			'',

			DOC.DATE_BASE,
			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			0
		FROM dbo.DOCUMENTS_INVOICE_RECEIVED DOC
		INNER JOIN dbo.DEPARTMENTS DEP ON ((DEP.ZB = 1 OR DEP.[TYPE] = 4)
						AND DEP.LINK = DOC.DEP_LINK)
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND DOC.BOOK_PUR = CONVERT (BIT, 1)
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)
	

	IF @varKSnOption1 = 2		-- Книга продаж (Выданные счета-фактуры) --
		INSERT INTO @TAB1	-- Отбор всех выданных с/ф за период -- 
		SELECT DOC.LINK,
			DOC.BUY_LINK,	-- ПОКУПАТЕЛЬ --
			DOC.SUMMA,
			DOC.[DATE],
			DOC.NUMBER,

			DOC.COR_DATE,
			DOC.COR_NUM,

			NULL,
			'',
			NULL,
			'',

			DOC.DATE_BASE,
			RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
			0
		FROM dbo.DOCUMENTS_INVOICE_ISSUED DOC
		INNER JOIN dbo.DEPARTMENTS DEP ON ((DEP.ZB = 1 OR DEP.[TYPE] = 4)
						AND DEP.LINK = DOC.DEP_LINK)
		WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
			AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
				OR @intSVOD_ZB = 1)
			AND DOC.BOOK_SALES = CONVERT (BIT, 1)

	-- НАЛОГОВЫЕ СТАВКИ --
	DECLARE @TABLE_NDS TABLE
		(LINK_UP	INT,
		SUMMA_ALL	NUMERIC (28,4),
		SUMMA_NDS	NUMERIC (28,4),
		SUMMA		NUMERIC (28,4),
		FS_LINK		INT,
		FS_CODE		VARCHAR (2),
		NO_NDS		TINYINT,
		STAVKA_NDS	NUMERIC (5,2))

	INSERT INTO @TABLE_NDS
	SELECT T1.LINK_UP,
		T1.SUMMA_ALL,
		T1.SUMMA_NDS,
		T1.SUMMA,
		ISNULL (T1.FS_LINK, 0),
		ISNULL (T1.FS_CODE, ''),
		T1.NO_NDS, 
		T1.STAVKA_NDS 
	FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (DEFAULT) T1
	INNER JOIN @TAB1 T0 ON (T0.LINK_DOC = T1.LINK_UP)
	INNER JOIN @TAB_SFIN T3 ON (T3.LINK = T1.FS_LINK)

	-- 18% --
	INSERT INTO @TAB2_18	 
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA_NDS),
		SUM (T1.SUMMA),
		0
	FROM @TABLE_NDS T1
--	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
--	INNER JOIN @TAB_SFIN T3 ON (T3.LINK = T1.FS_LINK)
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 18
	GROUP BY T1.LINK_UP

	-- 10% --
	INSERT INTO @TAB2_10	 
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA_NDS),
		SUM (T1.SUMMA),
		0
	FROM @TABLE_NDS T1
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 10
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_0	-- 0% 
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA),
		0
	FROM @TABLE_NDS T1
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 0
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_NO_NDS	-- --
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA),
		0
	FROM @TABLE_NDS T1
	WHERE T1.NO_NDS = 1
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_20	-- 20% 
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA_NDS),
		SUM (T1.SUMMA),
		0
	FROM @TABLE_NDS T1
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 20
	GROUP BY T1.LINK_UP

	-- Итоговая сумма по документу --
	INSERT INTO @TAB_DOC_SUM
	SELECT T1.LINK_UP,
		SUM (T1.SUMMA_ALL)
	FROM @TABLE_NDS T1
	GROUP BY T1.LINK_UP

	-- Выбираем корректировочные с\ф (полученные) --
	INSERT INTO @TAB1	
	SELECT DOC.LINK,
		DOC.SEL_LINK,	-- ПРОДАВЕЦ --
		DOC.SUMMA,
		DOC.OSN_DATE,
		DOC.OSN_NUM,

		DOC.OSN_DATE_C,
		DOC.OSN_NUM_C,

		DOC.[DATE],
		DOC.NUMBER,
		DOC.COR_DATE,
		DOC.COR_NUM,

		DOC.DATE_BASE,
		RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
		1
	FROM dbo.DOCUMENTS_INVOICE_COR_IN DOC
	INNER JOIN dbo.DEPARTMENTS DEP ON ((DEP.ZB = 1 OR DEP.[TYPE] = 4)
					AND DEP.LINK = DOC.DEP_LINK)
	WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
		AND DOC.INBOOK = 1
		AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
			OR @intSVOD_ZB = 1)

	-- Выбираем корректировочные с\ф (выданные) --
	INSERT INTO @TAB1	
	SELECT DOC.LINK,
		DOC.SEL_LINK,	-- ПРОДАВЕЦ --
		DOC.SUMMA,
		DOC.OSN_DATE,
		DOC.OSN_NUM,

		DOC.OSN_DATE_C,
		DOC.OSN_NUM_C,

		DOC.[DATE],
		DOC.NUMBER,
		DOC.COR_DATE,
		DOC.COR_NUM,

		DOC.DATE_BASE,
		RIGHT (REPLACE (SPACE (50), SPACE (1), '0') + LTRIM (RTRIM (DOC.NUMBER)), 50),
		2
	FROM dbo.DOCUMENTS_INVOICE_COR_OUT DOC
	INNER JOIN dbo.DEPARTMENTS DEP ON ((DEP.ZB = 1 OR DEP.[TYPE] = 4)
					AND DEP.LINK = DOC.DEP_LINK)
	WHERE DOC.[DATE] BETWEEN @varKSdDate_1 AND @varKSdDate_2
		AND DOC.INBOOK = 1
		AND ((@intSVOD_ZB = 0 AND DOC.DEP_LINK = @intDEP_LINK)
			OR @intSVOD_ZB = 1)

-- SELECT * FROM @TAB1

	-- Табличная часть кор. с\ф --
	DECLARE @TABLE_COR TABLE
		(LINK_UP	INT,

/*		SUMMA_ALL1	NUMERIC (28,4),
		SUMMA_NDS1	NUMERIC (28,4),
		SUMMA1		NUMERIC (28,4),

		SUMMA_ALL2	NUMERIC (28,4),
		SUMMA_NDS2	NUMERIC (28,4),
		SUMMA2		NUMERIC (28,4),
*/
		SUMMA_ALL	NUMERIC (28,4),
		SUMMA_NDS	NUMERIC (28,4),
		SUMMA		NUMERIC (28,4),

		NO_NDS		TINYINT,
		STAVKA_NDS	NUMERIC (5,2),

		FS_LINK		INT,
		FS_CODE		VARCHAR (2))

	INSERT INTO @TABLE_COR
	SELECT T1.LINK_UP,

		T1.S_ALL_NEW - T1.SUMMA_ALL,
		T1.S_NDS_NEW - T1.SUMMA_NDS,
		T1.SUM_NEW - T1.SUMMA,

		T1.NO_NDS_NEW,
		T1.ST_NDS_NEW,

		T2.LINK,
		T2.CODE		

	FROM dbo.BK_DOC_TAB_INVOICE_COR_FN (DEFAULT) T1
	INNER JOIN @TAB_SFIN T2 ON (T2.LINK = T1.FS_LINK)

-- SELECT * FROM @TABLE_COR

	-- Обработка кор. с\ф --
	INSERT INTO @TAB2_18	 
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA_NDS)),
		ABS (SUM (T1.SUMMA)),
		0
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 18
		-- Книга покупок 
		AND (@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0))
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0))
			)
	GROUP BY T1.LINK_UP

	-- 10% --
	INSERT INTO @TAB2_10	 
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA_NDS)),
		ABS (SUM (T1.SUMMA)),
		0
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 10
		-- Книга покупок 
		AND (@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0))
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0))
			)
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_0	-- 0% 
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA)),
		0
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 0
		-- Книга покупок 
		AND (@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0))
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0))
			)
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_NO_NDS	-- --
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA)),
		0
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE T1.NO_NDS = 1
		-- Книга покупок 
		AND (@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0))
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0))
			)
	GROUP BY T1.LINK_UP

	INSERT INTO @TAB2_20	-- 20% 
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA_NDS)),
		ABS (SUM (T1.SUMMA)),
		0
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE T1.NO_NDS = 0
		AND T1.STAVKA_NDS = 20
		-- Книга покупок 
		AND (@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0))
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND (T1.SUMMA_NDS < 0 OR T1.SUMMA < 0)
				OR T2.IS_COR = 2 AND (T1.SUMMA_NDS > 0 OR T1.SUMMA > 0))
			)
	GROUP BY T1.LINK_UP

	-- Итоговая сумма по документу --
	INSERT INTO @TAB_DOC_SUM
	SELECT T1.LINK_UP,
		ABS (SUM (T1.SUMMA_ALL))
	FROM @TABLE_COR T1
	INNER JOIN @TAB1 T2 ON (T2.LINK_DOC = T1.LINK_UP)
	WHERE 
		-- Книга покупок 
		(@varKSnOption1 = 1
			AND (T2.IS_COR = 1 AND T1.SUMMA_ALL > 0 
				OR T2.IS_COR = 2 AND T1.SUMMA_ALL < 0)
		-- Книга продаж
		OR @varKSnOption1 = 2
			AND (T2.IS_COR = 1 AND T1.SUMMA_ALL < 0 
				OR T2.IS_COR = 2 AND T1.SUMMA_ALL > 0)
			)
	GROUP BY T1.LINK_UP

	DECLARE @RESULT TABLE (DEP_NAME VARCHAR (254), DEP_INN VARCHAR (20), DEP_KPP VARCHAR (20),
		DEP_NAME1 VARCHAR (254), DEP_INN1 VARCHAR (20), DEP_KPP1 VARCHAR (20),
		dDOC_DATE DATETIME,
		DOC_DATE1 VARCHAR (10), DOC_NUM1 VARCHAR (50),
		DOC_DATE2 VARCHAR (10), DOC_NUM2 VARCHAR (50),
		COR_DATE1 VARCHAR (10), COR_NUM1 VARCHAR (50),
		COR_DATE2 VARCHAR (10), COR_NUM2 VARCHAR (50),
		DATE_OPL VARCHAR (10), SUM_TOTAL NUMERIC (28,4),
		SUMMA18 NUMERIC (28,4), NALOG18 NUMERIC (28,4),
		SUMMA10 NUMERIC (28,4), NALOG10 NUMERIC (28,4),
		SUMMA0 NUMERIC (28,4),
		SUMMA20 NUMERIC (28,4), NALOG20 NUMERIC (28,4),
		SUM_NONDS NUMERIC (28,4),
		REP1 TINYINT, SORT_NUM VARCHAR (50),
		IS_COR	TINYINT)

	INSERT INTO @RESULT
	SELECT @strHD_Org_Name,
		@strHD_PUR_INN,
		@strHD_PUR_KPP,

		ISNULL (D1.NAME, ''),
		ISNULL (D1.INN, ''),
		ISNULL (D1.KPP, ''),

		CASE
			WHEN IS_COR = 0 THEN T1.DOC_DATE1
			ELSE T1.COR_DATE1
		END,

		CONVERT (VARCHAR (10), T1.DOC_DATE1, 104),
		T1.DOC_NUM1,

		CONVERT (VARCHAR (10), T1.DOC_DATE2, 104),
		T1.DOC_NUM2,

		CONVERT (VARCHAR (10), T1.COR_DATE1, 104),
		T1.COR_NUM1,

		CONVERT (VARCHAR (10), T1.COR_DATE2, 104),
		T1.COR_NUM2,

		ISNULL (CONVERT (VARCHAR (10), T1.DATE_OPL, 104), ''),
		ISNULL (DOC_SUM.SUMMA_ALL, 0),
		ISNULL (T18.SUMMA, 0),
		ISNULL (T18.NALOG, 0),
		ISNULL (T10.SUMMA, 0),
		ISNULL (T10.NALOG, 0),
		ISNULL (T0.SUMMA, 0),
		ISNULL (T20.SUMMA, 0),
		ISNULL (T20.NALOG, 0),
		ISNULL (TNO.SUMMA, 0),
		1,
		T1.SORT_NUM,
		CASE 
			WHEN T1.IS_COR = 0 THEN 0
			ELSE 1
		END
	FROM @TAB1 T1
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT D1 ON (D1.LINK = T1.DEP1)
	LEFT OUTER JOIN @TAB2_18 T18 ON (T1.LINK_DOC = T18.LINK_DOC) 
	LEFT OUTER JOIN @TAB2_10 T10 ON (T1.LINK_DOC = T10.LINK_DOC) 
	LEFT OUTER JOIN @TAB2_0 T0 ON (T1.LINK_DOC = T0.LINK_DOC) 
	LEFT OUTER JOIN @TAB2_20 T20 ON (T1.LINK_DOC = T20.LINK_DOC)
	LEFT OUTER JOIN @TAB2_NO_NDS TNO ON (T1.LINK_DOC = TNO.LINK_DOC)
	LEFT OUTER JOIN @TAB_DOC_SUM DOC_SUM ON (T1.LINK_DOC = DOC_SUM.LINK_DOC)

	SELECT * 
	FROM @RESULT
	WHERE IS_COR = 0
		OR IS_COR = 1 AND SUM_TOTAL > 0
	ORDER BY dDOC_DATE,
		SORT_NUM,
		IS_COR
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_BOOK_SALES_PURCHASE] 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_MAKE_FULL_SVOD_AGAIN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[I_REPORT_MAKE_FULL_SVOD_AGAIN]
GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE          PROCEDURE dbo.I_REPORT_MAKE_FULL_SVOD_AGAIN
	@varKSLinkSF	int,
    @iLinkTable     int = 0,
    @varKStDo     TINYINT = 0 -- 1 - все равно делать пересчет свода, даже если нет отчетов
AS

if (select count(*) from report_saved_forms where link_saved_form = @varKSLinkSF) <> 1
	return -1  
-- увеличивается счетчик сохранения.
update dbo.report_saved_forms
set CountSave = isnull(CountSave, 0) + 1
where Link_Saved_Form = @varKSLinkSF

IF @iLinkTable>0 
BEGIN
        update dbo.report_saved_tables
        set CountSave = isnull(CountSave, 0) + 1
        where Link_Saved_Form = @varKSLinkSF AND Link_Table=@iLinkTable
END

DECLARE	@varKSBYear		int,
	@varKSLinkF		int,
	@varKSpTYPE		tinyint,
	@varKSPNomber		tinyint,
	@varKSCode		char(20),
	@varKSLink_last_event	int,
	@LinkOrg		int,
	@LinkBudg		int,
	@varKSLinkTreeSvod	int,
	@varKSiSvod		tinyint,
	@varKSBDAte		datetime,
	@iRetValue		INT,
   @atr VARCHAR(1000),
   @iLinkSF_Del INT 

set @varKSiSvod = 0 -- свод отчетов

select	@varKSLinkF = link_form,
	@varKSCode = (select code from report_forms RF where RF.link_form = RSF.link_form),
	@varKSBYear = year(Begin_Date), 
	@varKSBDAte = Begin_Date,
	@varKSpTYPE = Period_Type, 
	@varKSPNomber = Period_Number,
	@LinkBudg = Link_Type_Svod,
	@LinkOrg = Link_Organization,
   @atr = RSF.[atr_code]
from report_saved_forms RSF where link_saved_form = @varKSLinkSF

select @varKSLinkTreeSvod = min(Link) from dbo.RO_SVOD_TREE where Link_report_budg = @LinkBudg and Link_report_org = @LinkOrg AND [Link_History] = dbo.[RO_SVOD_TREE_Link_History](@varKSBDAte)

IF NOT EXISTS(SELECT * FROM dbo.report_saved_forms RSF JOIN dbo.RO_Svod_TREE RST ON RSF.[Link_Organization] = RST.[LINK_REPORT_ORG] AND ISNULL(RSF.[Link_Type_Svod], 0) = ISNULL(RST.[LINK_REPORT_BUDG], 0) AND RST.[LINK_SELF] = @varKSLinkTreeSvod 
              WHERE link_form = @varKSLinkF AND [Begin_Date] = @varKSBDAte AND [Period_Type] = @varKSpTYPE
                  AND RSF.atr_code = @atr) AND @varKStDo = 0
   RETURN 2


declare @atribut varchar(1000),@LINK_REPORT_ORG int,@LINK_REPORT_BUDG INT, @atribut1 VARCHAR(1000)

set @LINK_REPORT_ORG=dbo.RO_SVOD_ORG(@varKSLinkTreeSvod)
set @LINK_REPORT_BUDG=dbo.RO_SVOD_BUDG(@varKSLinkTreeSvod)


set @atribut=''

SET @atribut1 = dbo.rn_get_atr_val(@varKSLinkSF,0,1)  

if @atribut1 like  '%REPORTS_ATR_VID=%' or  @atribut like  '%REPORTS_ATR_RRO_TYPE=%' or @atribut like '%REPORTS_ATR_TYPE_ORG=%'
   SET  @atribut = @atribut1   

IF @varKSCode in ('(72н)0503125','(72н)0503125M','(72н)425','(72н)425M', 'OPKB', '0503125M', '425M', '0503125G', '0503125M') 
    begin
        set @atribut=dbo.rn_get_atr_val(@varKSLinkSF,0,1)        
    END

-------------- перед затиранием удаляем в корзину
EXEC dbo.RO_RECYCLE_SAVE @varKSLinkSF


IF   @iLinkTable=0
BEGIN
	DELETE FROM report_summa where link_saved_form = @varKSLinkSF
	DELETE FROM report_dinamics where link_sf = @varKSLinkSF
	DELETE FROM report_string where link_saved_form = @varKSLinkSF
	DELETE FROM report_summa_arh where link_saved_form = @varKSLinkSF
	DELETE FROM report_dinamics_arh where link_sf = @varKSLinkSF
	DELETE FROM report_string_arh where link_saved_form = @varKSLinkSF
END
ELSE
BEGIN
	DELETE FROM report_summa where link_saved_form = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_summa.Link_Col)
	DELETE FROM report_dinamics where link_sf = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_dinamics.Link_Col)
	DELETE FROM report_string where link_saved_form = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_string.Link_Col)
	
	DELETE FROM report_summa_arh where link_saved_form = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_summa_arh.Link_Col)
	DELETE FROM report_dinamics_arh where link_sf = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_dinamics_arh.Link_Col)
	DELETE FROM report_string_arh where link_saved_form = @varKSLinkSF AND EXISTS(select * from Report_coloumns RC Where Rc.link_table=@iLinkTable AND RC.Link_Col=report_string_arh.Link_Col)
END


--проверим, не архивный ли отчет сохраняем.
IF exists(select * from report_saved_forms where link_saved_form=@varKSLinkSF  and is_arhiv=1)
	begin
	   --архивный, надо перенести данные в оперативную таблицу
		exec rn_move_form_from_arh @varKSLinkSF
	end


exec @iRetValue = dbo.I_REPORT_MAKE_FULL_SVOD_NEW @varKSLinkF, @varKSBDAte, @varKSpTYPE, @varKSPNomber, @varKSLinkTreeSvod, @varKSLinkSF, @varKSiSvod, @atribut, @iLinkTable 
RETURN @iRetValue



GO
GRANT ALL ON dbo.[I_REPORT_MAKE_FULL_SVOD_AGAIN] TO PUBLIC



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_151_SVOD]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_151_SVOD]
END
GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 2008

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_151_SVOD]
   @lvcKODF         VARCHAR(10),
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,     -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liReturn INT,
        @liLSF    INT,
        @lvcTXT   VARCHAR(8000),
        @lvcWord1 VARCHAR(8000),
        @lvcWord2 VARCHAR(8000),
        @lvcKBP   VARCHAR(50),
        @lvcVB    VARCHAR(50),
        @liORDER  INT,
        @i        INT,
		@vcUK		varchar(100)

IF ISNULL(@liRepeatRequest,0) > 0 
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] = 'ВФ=0')
BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode   
   RETURN @liReturn
END



SELECT @lvcKBP = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('KБП=','ИСТ=') OR 
      LEFT([TXT],3) IN ('KБ=')

SELECT @lvcVB = [TXT]
FROM #IMPORT_TABLE
WHERE LEFT([TXT],4) IN ('ВИД=','ВБ=')

 SELECT top 1 @vcUK = dbo.[RA_GETWORDNUM]([TXT], 3, '|')
 FROM #IMPORT_TABLE
 WHERE LEFT([TXT],3) IN ('TO|')

 IF @lvcKBP IS NULL
 BEGIN
    SELECT @lvcKBP = 'КБП=' + ISNULL([KBP],'')      
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
 END

 IF @lvcVB IS NULL 
 BEGIN
    SELECT @lvcVB = 'ВИД=' + ISNULL([VB],'')
    FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] 
    WHERE [UK] = @vcUK and form_code = '0503151'
 END

IF @lvcKBP IS NULL
BEGIN
   SELECT @lvcKBP = 'КБП=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_KBP_151'
END

IF @lvcVB IS NULL 
BEGIN
   SELECT @lvcVB = 'ВИД=' + ISNULL([VAL_STR],'')
   FROM dbo.[REPORT_OPTIONS] 
   WHERE [RAZDEL] = 'FORM_151' AND
         [CODE] = 'IMPORT_VB_151'
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE LEFT([TXT],3) = 'FK|')
BEGIN
   DELETE #IMPORT_TABLE 
   WHERE [ORDER] IN (1,2)


   SET IDENTITY_INSERT #IMPORT_TABLE ON  
   
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('КОДФ='+@lvcKODF,-1)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcKBP,'КБП='),0)
   INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES (ISNULL(@lvcVB,'ВИД='),1)
   
   IF @lvcKODF = '0503151G'
   BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=5',2)
   END
   ELSE BEGIN
      INSERT #IMPORT_TABLE([TXT],[ORDER]) VALUES ('ПРД=3',2)
   END
   
   SET IDENTITY_INSERT #IMPORT_TABLE OFF

   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode
   RETURN @liReturn
END

UPDATE #IMPORT_TABLE
SET [TXT]=LEFT([TXT],dbo.[RA_GETWORDPOS]([TXT],4,'|')-1)+SUBSTRING([TXT],dbo.[RA_GETWORDPOS]([TXT],5,'|'),8000)
WHERE dbo.[RA_GETWORDCOUNT]([TXT],'|')=9 AND LEFT([TXT],2)='RD'

DECLARE @tabIMPORT TABLE ([TXT] VARCHAR(8000),
                          [ORDER] INT IDENTITY(1,1))
   

INSERT @tabIMPORT([TXT]) VALUES ('КОДФ='+@lvcKODF)

IF EXISTS (SELECT * 
           FROM #IMPORT_TABLE
           WHERE LEFT([TXT],3)='PW|')
BEGIN       
   INSERT @tabIMPORT([TXT]) 
   SELECT 'ДТ=' + RTRIM(dbo.[RA_GETWORDNUM]([TXT],7,'|'))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3)='PW|'
END


/*
IF EXISTS (SELECT * 
           FROM #IMPORT_TABLE
           WHERE LEFT([TXT],3)='BF|')
BEGIN       
   INSERT @tabIMPORT([TXT]) 
   SELECT 'ДТ=' + RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|'))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3)='BF|'
END
ELSE BEGIN
   INSERT @tabIMPORT([TXT]) 
   SELECT 'ДТ=' + RTRIM(dbo.[RA_GETWORDNUM]([TXT],5,'|'))
   FROM #IMPORT_TABLE
   WHERE LEFT([TXT],3)='OT|'
END
*/

INSERT @tabIMPORT([TXT]) VALUES (ISNULL(@lvcKBP,'КБП='))
INSERT @tabIMPORT([TXT]) VALUES (ISNULL(@lvcVB,'ВИД='))

IF @lvcKODF = '0503151G'
BEGIN
   INSERT @tabIMPORT([TXT]) VALUES ('ПРД=5')
END
ELSE BEGIN
   INSERT @tabIMPORT([TXT]) VALUES ('ПРД=3')
END 

INSERT @tabIMPORT([TXT]) VALUES ('РД=1')

INSERT @tabIMPORT([TXT])
SELECT [TXT] = [B].[CODE_STR] + '|' +
               CASE 
                  WHEN [CODE] = REPLICATE('*',17) THEN '***'
                  ELSE '000'
               END + '|' +
               [B].[CODE] + '|' +
               LTRIM(STR([COL4],20,2)) + '|' +
               LTRIM(STR([COL5],20,2)) + '|' +
               LTRIM(STR([COL6],20,2)) + '|' +
               LTRIM(STR([COL7],20,2))             
FROM (
   SELECT [A].[CODE_STR],
          [A].[CODE],
          [COL4] = SUM([COL4]),
          [COL5] = SUM([COL5]),
          [COL6] = SUM([COL6]),
          [COL7] = SUM([COL7])      
   FROM 
   (
      SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],2,'|'),
             [CODE] = CASE 
                         WHEN SUBSTRING([TXT],9,1)='|' THEN REPLICATE('*',17)
                         ELSE SUBSTRING(dbo.[RA_GETWORDNUM]([TXT],3,'|'),4,17)
                      END,
             [COL4] = CAST(dbo.[RA_GETWORDNUM]([TXT],4,'|') AS NUMERIC(20,4)),
             [COL5] = CAST(dbo.[RA_GETWORDNUM]([TXT],5,'|') AS NUMERIC(20,4)),
             [COL6] = CAST(dbo.[RA_GETWORDNUM]([TXT],6,'|') AS NUMERIC(20,4)),
             [COL7] = CAST(dbo.[RA_GETWORDNUM]([TXT],7,'|') AS NUMERIC(20,4))
      FROM #IMPORT_TABLE
      WHERE LEFT([TXT],3)='RD1' AND  
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],4,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],5,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],6,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 
   ) [A]
   GROUP BY [A].[CODE_STR],[A].[CODE]
) [B]

INSERT @tabIMPORT([TXT]) VALUES ('РД=2')

INSERT @tabIMPORT([TXT])
SELECT [TXT] = [B].[CODE_STR] + '|' +
               CASE 
                  WHEN [CODE] = REPLICATE('*',17) OR [CODE_STR] = '450' THEN '***'
                  ELSE '000'
               END + '|' +
               LEFT([B].[CODE],4) + '|' +
               SUBSTRING([B].[CODE],5,7) + '|' +
               SUBSTRING([B].[CODE],12,3) + '|' +
               SUBSTRING([B].[CODE],15,3) + '|' +
               LTRIM(STR([COL4],20,2)) + '|' +
               LTRIM(STR([COL5],20,2)) + '|' +
               LTRIM(STR([COL6],20,2)) + '|' +
               LTRIM(STR([COL7],20,2))             
FROM (
   SELECT [A].[CODE_STR],
          [A].[CODE],
          [COL4] = SUM([COL4]),
          [COL5] = SUM([COL5]),
          [COL6] = SUM([COL6]),
          [COL7] = SUM([COL7])      
   FROM 
   (
      SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],2,'|'),
             [CODE] = CASE 
                         WHEN SUBSTRING([TXT],9,1)='|' THEN REPLICATE('*',17)
                         ELSE SUBSTRING(dbo.[RA_GETWORDNUM]([TXT],3,'|'),4,17)
                      END,
             [COL4] = CAST(dbo.[RA_GETWORDNUM]([TXT],4,'|') AS NUMERIC(20,4)),
             [COL5] = CAST(dbo.[RA_GETWORDNUM]([TXT],5,'|') AS NUMERIC(20,4)),
             [COL6] = CAST(dbo.[RA_GETWORDNUM]([TXT],6,'|') AS NUMERIC(20,4)),
             [COL7] = CAST(dbo.[RA_GETWORDNUM]([TXT],7,'|') AS NUMERIC(20,4))
      FROM #IMPORT_TABLE
      WHERE LEFT([TXT],3)='RD2' AND  
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],4,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],5,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],6,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 
   ) [A]
   GROUP BY [A].[CODE_STR],[A].[CODE]
) [B]

INSERT @tabIMPORT([TXT]) VALUES ('РД=3')

INSERT @tabIMPORT([TXT])
SELECT [TXT] = [B].[CODE_STR] + '|' +
               CASE [B].[CODE]
                  WHEN  REPLICATE('*',17) THEN '***' 
                  ELSE '000'
               END + '|' +
               [B].[CODE] + '|' +
               LTRIM(STR([COL4],20,2)) + '|' +
               LTRIM(STR([COL5],20,2)) + '|' +
               LTRIM(STR([COL6],20,2)) + '|' +
               LTRIM(STR([COL7],20,2))             
FROM (
   SELECT [A].[CODE_STR],
          [A].[CODE],
          [COL4] = SUM([COL4]),
          [COL5] = SUM([COL5]),
          [COL6] = SUM([COL6]),
          [COL7] = SUM([COL7])      
   FROM 
   (
      SELECT [CODE_STR] = dbo.[RA_GETWORDNUM]([TXT],2,'|'),
             [CODE] = CASE 
                         WHEN SUBSTRING([TXT],9,1)='|' THEN REPLICATE('*',17)
                         ELSE SUBSTRING(dbo.[RA_GETWORDNUM]([TXT],3,'|'),4,17)
                      END,
             [COL4] = CAST(dbo.[RA_GETWORDNUM]([TXT],4,'|') AS NUMERIC(20,4)),
             [COL5] = CAST(dbo.[RA_GETWORDNUM]([TXT],5,'|') AS NUMERIC(20,4)),
             [COL6] = CAST(dbo.[RA_GETWORDNUM]([TXT],6,'|') AS NUMERIC(20,4)),
             [COL7] = CAST(dbo.[RA_GETWORDNUM]([TXT],7,'|') AS NUMERIC(20,4))
      FROM #IMPORT_TABLE
      WHERE LEFT([TXT],3)='RD3' AND  
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],4,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],5,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],6,'|'))=1 AND
            dbo.[RA_ISNUMERIC](dbo.[RA_GETWORDNUM]([TXT],7,'|'))=1 
   ) [A]
   GROUP BY [A].[CODE_STR],[A].[CODE]
) [B]


DELETE #IMPORT_TABLE

INSERT #IMPORT_TABLE([TXT])
SELECT [TXT]
FROM @tabIMPORT
ORDER BY [ORDER]


--select * from #IMPORT_TABLE ORDER BY [ORDER]

EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                               @liRepeatRequest,
                                               @tIsAppend,
                                               @bDinamicRows,
                                               @iLINK_SELF,
                                               @tMode
                                

RETURN @liReturn

GO
GRANT ALL ON dbo.[RA_IMPORT_FORM_151_SVOD] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/

GO




GO

--AFTER CODE 20.06.2012
exec RN_SAVE_REPORT_KBK 0,'R_SPR_KSBU_125',0,'Справочник счетов бюджетного учета для формы 0503125 (атрибут)','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_KSBU_125',@link_self,'Справочник счетов бюджетного учета для формы 0503125 (атрибут)','HEADER'
GO
delete report_control_protokol
delete report_kbk where code_form= 'R_SPR_KSBU_125'
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 '120551000',0,'R_SPR_KSBU_125',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651000',0,'R_SPR_KSBU_125',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по выданным авансам по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по представленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках  целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках  целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным гарантиям)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251000',0,'R_SPR_KSBU_125',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251830',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404000',0,'R_SPR_KSBU_125',1,'Внутриведомственные расчеты',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130406000',0,'R_SPR_KSBU_125',1,'Расчеты с прочими кредиторами',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям.',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110151',0,'R_SPR_KSBU_125',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110180',0,'R_SPR_KSBU_125',1,'Прочие доходы',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120241',0,'R_SPR_KSBU_125',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120251',0,'R_SPR_KSBU_125',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404000',0,'R_SPR_KSBU_125',1,'Внутриведомственные расчеты',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230406000',0,'R_SPR_KSBU_125',1,'Расчеты с прочими кредиторами',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям.',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110180',0,'R_SPR_KSBU_125',1,'Прочие доходы',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120241',0,'R_SPR_KSBU_125',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', NULL,NULL,0


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_SAVE_REPORT_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_SAVE_REPORT_KBK]
GO

/*
c Кейсистемс (Keysystems), 2006
*/
--сохранение REPORT_KBK
CREATE        PROCEDURE dbo.RN_SAVE_REPORT_KBK
  @iLINK     int  OUTPUT,
  @cCode         varchar (200)='', --код кбк
  @iLink_self   int = NULL,
  @cName         varchar(250)='', --наименование
  @cCode_Form    varchar(250)='',
  @iChildrens  bit=0,
  @cCode_str  varchar(50)='', --код строки
  @property  int =0, --свойства строки
  @add_info varchar(4000)='',  -- Доп информация
  @long_name varchar(4000)='',  -- длинное наименование
	@dBegin_date datetime = NULL,
	@dEnd_date	datetime = NULL,
   @bCheck     BIT = 0       -- проверка для новых кодов, на то что уже есть в спраовчнике или в федеральном спрвочнике	
AS

IF @bCheck = 1 
BEGIN
   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = @cCode_Form AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1100 
   END    

   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = REPLACE(@cCode_Form, '_USER', '') AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1101 
   END    
END    

DECLARE @Date DATETIME , @dOldBeginDate DATETIME , @dOldEndDate DATETIME , @vcOldName VARCHAR(254), @vcOldLongName VARCHAR(8000), @bJastWas bit
-- очищение кэша проверки внутридокументных КС
delete report_control_protokol

set @cCode=RTRIM(@cCode)
set @iLink_self=isnull(@iLink_self,0) 

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT -1 -- Время ожидания разблокировки ресурсов 3 сек.

BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.
  -- Чтобы не было двойных кодов
 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')
   END

 IF (SELECT COUNT(*) 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form ) = 1 and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form
   END

 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') 
   END

SET @bJastWas = 0
   
IF isnull(@iLink, 0) <> 0
BEGIN
   SELECT @dOldBeginDate = begin_date, @dOldEndDate = end_date, @vcOldName = NAME, @vcOldLongName = Long_Name
   FROM dbo.report_kbk
   WHERE link = @iLink 
   
   set @bJastWas = 1

   IF (SELECT NAME FROM dbo.report_kbk WHERE link = @iLink) <> @cName OR  (SELECT LONG_NAME FROM dbo.report_kbk WHERE link = @iLink) <> @long_name
   BEGIN
      SET @Date = CONVERT(DATETIME,CONVERT(VARCHAR(10), GETDATE(), 112), 112)
      IF NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @iLink)
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         SELECT @iLink, '20000101', NAME, rk.[Long_name]
         FROM  dbo.[REPORT_KBK] rk
         WHERE link = @iLink
      END
      UPDATE dbo.[REPORT_KBK_HIST]
      SET NAME = @cName, [LONG_NAME] = @long_name
      WHERE LINK_UP =  @iLink AND [DATE] = @Date 
      IF @@ROWCOUNT = 0
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         VALUES( @iLink, @Date, @cName, @long_name)
      END 
   END
END    
   

   -- Обновление записи (если она существует).
  UPDATE [REPORT_KBK]
  SET   [CODE] =    @cCODE,
        [NAME] =    @cNAME,
        [CODE_FORM]=@cCODE_FORM,
        [CHILDRENS]=@iChildrens,
        [LINK_SELF]=@iLink_Self,
        [CODE_STR]=@cCode_str,
        [property]=@property,
        [add_info]=@add_info,
        [LONG_NAME] =    @LONG_NAME,
		[BEGIN_DATE] = @dBegin_date,
		[END_DATE] = @dEnd_date
  WHERE [LINK] = @iLINK

DECLARE @liRowCount   INT, -- Число обработанных строк.
        @liError      INT  -- Код ошибки.
   -- Сохранение количества обработанных строк и кода ошибки. 
   SELECT @liRowCount = @@ROWCOUNT, 
          @liError    = @@ERROR

   -- Восстановление точки сохранения при ошибке.
  IF @liError <> 0 BEGIN
    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
    RETURN 7 -- Возврат кода ошибки.
  END
 
  IF @liRowCount = 0  
   BEGIN
    INSERT 
      INTO dbo.[REPORT_KBK] ([CODE],[NAME],[LINK_SELF],[CHILDRENS],[CODE_FORM],[CODE_STR],[property],[add_info],long_name, begin_date, end_date)
    VALUES (@cCODE, @cNAME,@iLink_Self,@iChildrens,@cCode_Form,@cCode_Str,@property,@add_info,@long_name, @dBegin_date, @dEnd_date)

      -- Сохранение первичного ключа и кода ошибки. 
    SELECT @iLINK   = @@IDENTITY 
    SELECT @liError = @@ERROR
      -- Восстановление точки сохранения при ошибке.
    IF @liError <> 0
    BEGIN
      ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
      RETURN 7 -- Возврат кода ошибки.
    END
  END

IF @cCode_Form='HEADER'
begin  
  UPDATE REPORT_KBK 
  SET childrens=case when exists(select * from REPORT_KBK A where A.link_self=REPORT_KBK.link) then 0 else 1 end
  WHERE link=@iLink OR link=@iLink_self
  update report_kbk 
  set imageindex=4  
  where code_form='header'
end

--EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK
--
--DECLARE @LF INT, @LSF INT 
--
--EXEC dbo.DropTempTable '#t_CodeRow' 
--CREATE TABLE #t_CodeRow (Code VARCHAR(50))
--
--if @bJastWas = 1 AND ((isnull(@dBegin_date, '19000101') <> isnull(@dOldBeginDate, '19000101')
--    OR ISNULL(case when @dEnd_date > '20200101' THEN '30000101'  ELSE @dEnd_date END , '30000101') <> ISNULL(case when @dOldEnddate > '20200101' THEN '30000101'  ELSE @dOldEnddate END, '30000101')
--      OR @vcOldName <> @cName OR @vcOldLongName <> @long_name)
--   AND (@cCode_Form LIKE '%_2011_USER%' OR (RTRIM(@cCode_Form) LIKE '%_2011' AND NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = RTRIM(@cCode_Form) + '_USER' AND @cCode = Code))))
--BEGIN
--   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
--   FROM dbo.report_saved_forms rsf
--      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
--   WHERE rf.[Code] IN ( '0503117M','0503117G','0503127G','0503127M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
--   
--   IF @LSF IS NOT NULL 
--   BEGIN 
--      IF @cCode_Form LIKE '%ЭКР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_117_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--      END 
--      IF @cCode_Form LIKE '%ВР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_117_2011')
--               and SUBSTRING(CODE, 12,3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
--               and SUBSTRING(CODE, 12,3) = @cCode
--      END
--      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
--   END  
--   SET @LSF = NULL
--   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
--   FROM dbo.report_saved_forms rsf
--      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
--   WHERE rf.[Code] IN ( '0503114M','0503114G','0503137G','0503137M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
--   
--   IF @LSF IS NOT NULL 
--   BEGIN 
--      TRUNCATE TABLE #t_CodeRow
--      IF @cCode_Form LIKE '%ЭКР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_114_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--      END 
--      IF @cCode_Form LIKE '%ВР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 12,3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 12,3) = @cCode
--      END
--      IF @cCode_Form LIKE '%ЦСР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 5,7) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 5,7) = @cCode
--      END
--      IF @cCode_Form LIKE '%РЗПР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 1,4) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
--               and SUBSTRING(CODE, 1,4) = @cCode
--      END
--      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
--   END  
--   SET @LSF = NULL
--   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
--   FROM dbo.report_saved_forms rsf
--      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
--   WHERE rf.[Code] IN ( '0503317M_ФК','0503317G_ФК') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
--   
--   IF @LSF IS NOT NULL 
--   BEGIN 
--      TRUNCATE TABLE #t_CodeRow
--      IF @cCode_Form LIKE '%ЭКР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
--               AND RIGHT(RTRIM(Code), 3) = @cCode
--      END 
--      IF @cCode_Form LIKE '%ВР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 15,3) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 15,3) = @cCode
--      END
--      IF @cCode_Form LIKE '%ЦСР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 8,7) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 8,7) = @cCode
--      END
--      IF @cCode_Form LIKE '%РЗПР%'
--      BEGIN
--          INSERT #t_CodeRow
--          SELECT Code
--          FROM  dbo.report_kbk 
--          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 4,4) = @cCode
--               
--         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
--               and SUBSTRING(CODE, 4,4) = @cCode
--      END
--      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
--   END  
--   
--END     

COMMIT TRANSACTION -- Фиксация транзакции.

RETURN 0 -- Ошибок нет.




GO
GRANT ALL ON dbo.[RN_SAVE_REPORT_KBK] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503769_Дебет С КОДОМ R_SPR_ACC_769_D------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_769_D'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_769_D', 'План счетов для 0503769_Дебет', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_769_D]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_769_D]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503769_Дебет (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_769_D]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_769_D' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_769_D] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_D')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_D'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_D', 'План счетов для 0503769_Дебет', 152, (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_ACC_769_D', NAME = 'План счетов для 0503769_Дебет', ORDERS = '152', 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_ACC_769_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_D_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_D_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_D_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_D_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_D_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_D_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_D_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_D_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_D'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_D_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D', 'TITLE', 'План счетов для 0503769_Дебет'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_769_D'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_769_D'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D', 'SERVER_TABLE_NAME', 'R_SPR_ACC_769_D'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_769_D'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_D_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_D', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_D', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_D', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_769_D',0,'План счетов для 0503769_Дебет','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_ACC_769_D',@link_self,'План счетов для 0503769_Дебет','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_D')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_D')
delete report_kbk where code_form= 'R_SPR_ACC_769_D'
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 '20500000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20511000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20521000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20531000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20541000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20551000',0,'R_SPR_ACC_769_D',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20552000',0,'R_SPR_ACC_769_D',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20553000',0,'R_SPR_ACC_769_D',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20561000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20571000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20572000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20573000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20574000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20575000',0,'R_SPR_ACC_769_D',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20581000',0,'R_SPR_ACC_769_D',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20600000',0,'R_SPR_ACC_769_D',1,'Расчеты по выданным авансам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20612000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20613000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20621000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по услугам связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20622000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20623000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20624000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20625000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20626000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20631000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20632000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20633000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20634000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20641000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20642000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20651000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20652000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20653000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20661000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20662000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20663000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20691000',0,'R_SPR_ACC_769_D',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20700000',0,'R_SPR_ACC_769_D',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20711000',0,'R_SPR_ACC_769_D',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20713000',0,'R_SPR_ACC_769_D',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20714000',0,'R_SPR_ACC_769_D',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20721000',0,'R_SPR_ACC_769_D',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20723000',0,'R_SPR_ACC_769_D',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20724000',0,'R_SPR_ACC_769_D',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20731000',0,'R_SPR_ACC_769_D',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20733000',0,'R_SPR_ACC_769_D',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20800000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20811000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20812000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20813000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20821000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20822000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20823000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20824000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20825000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20826000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20831000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20832000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20834000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20861000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20862000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20863000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20891000',0,'R_SPR_ACC_769_D',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20900000',0,'R_SPR_ACC_769_D',1,'Расчеты по ущербу имуществу',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20971000',0,'R_SPR_ACC_769_D',1,'Расчеты по ущербу основным средствам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20972000',0,'R_SPR_ACC_769_D',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20973000',0,'R_SPR_ACC_769_D',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20974000',0,'R_SPR_ACC_769_D',1,'Расчеты по ущербу материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20981000',0,'R_SPR_ACC_769_D',1,'Расчеты по недостачам денежных средств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20982000',0,'R_SPR_ACC_769_D',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21000000',0,'R_SPR_ACC_769_D',1,'Прочие расчеты с дебиторами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21001000',0,'R_SPR_ACC_769_D',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21002000',0,'R_SPR_ACC_769_D',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21003000',0,'R_SPR_ACC_769_D',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21004000',0,'R_SPR_ACC_769_D',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21005000',0,'R_SPR_ACC_769_D',1,'Расчеты с прочими дебиторами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21006000',0,'R_SPR_ACC_769_D',1,'Расчеты с учредителем',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '88888888',0,'R_SPR_ACC_769_D',1,'',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_ACC_769_D'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503769_Кредит С КОДОМ R_SPR_ACC_769_DK------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_769_DK'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_769_DK', 'План счетов для 0503769_Кредит', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_769_DK]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_769_DK]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503769_Кредит (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_769_DK]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_769_DK' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_769_DK] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_DK')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_DK'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_DK', 'План счетов для 0503769_Кредит', 196, (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_ACC_769_DK', NAME = 'План счетов для 0503769_Кредит', ORDERS = '196', 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_ACC_769_DK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_DK_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_DK_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_DK_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_DK_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_DK_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_DK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_DK_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_DK_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_DK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_DK_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK', 'TITLE', 'План счетов для 0503769_Кредит'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_769_DK'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_769_DK'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK', 'SERVER_TABLE_NAME', 'R_SPR_ACC_769_DK'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_769_DK'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_DK_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_DK', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_DK', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_DK', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_769_DK',0,'План счетов для 0503769_Кредит','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_ACC_769_DK',@link_self,'План счетов для 0503769_Кредит','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_DK')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_DK')
delete report_kbk where code_form= 'R_SPR_ACC_769_DK'
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 '30200000',0,'R_SPR_ACC_769_DK',1,'Расчеты по принятым обязательствам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30211000',0,'R_SPR_ACC_769_DK',1,'Расчеты по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30212000',0,'R_SPR_ACC_769_DK',1,'Расчеты по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30213000',0,'R_SPR_ACC_769_DK',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30221000',0,'R_SPR_ACC_769_DK',1,'Расчеты по услугам связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30222000',0,'R_SPR_ACC_769_DK',1,'Расчеты по транспортным услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30223000',0,'R_SPR_ACC_769_DK',1,'Расчеты по коммунальным услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30224000',0,'R_SPR_ACC_769_DK',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30225000',0,'R_SPR_ACC_769_DK',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30226000',0,'R_SPR_ACC_769_DK',1,'Расчеты по прочим работам, услугам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30231000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению основных средств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30232000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30233000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30234000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30241000',0,'R_SPR_ACC_769_DK',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30242000',0,'R_SPR_ACC_769_DK',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30251000',0,'R_SPR_ACC_769_DK',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30252000',0,'R_SPR_ACC_769_DK',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30253000',0,'R_SPR_ACC_769_DK',1,'Расчеты по перечислениям международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30261000',0,'R_SPR_ACC_769_DK',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30262000',0,'R_SPR_ACC_769_DK',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30263000',0,'R_SPR_ACC_769_DK',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30272000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30273000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30275000',0,'R_SPR_ACC_769_DK',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30291000',0,'R_SPR_ACC_769_DK',1,'Расчеты по прочим расходам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30300000',0,'R_SPR_ACC_769_DK',1,'Расчеты по платежам в бюджеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30301000',0,'R_SPR_ACC_769_DK',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30302000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30303000',0,'R_SPR_ACC_769_DK',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30304000',0,'R_SPR_ACC_769_DK',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30305000',0,'R_SPR_ACC_769_DK',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30306000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30307000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30308000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30309000',0,'R_SPR_ACC_769_DK',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30310000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30311000',0,'R_SPR_ACC_769_DK',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30312000',0,'R_SPR_ACC_769_DK',1,'Расчеты по налогу на имущество организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30313000',0,'R_SPR_ACC_769_DK',1,'Расчеты по земельному налогу',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30400000',0,'R_SPR_ACC_769_DK',1,'Прочие расчеты с кредиторами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30402000',0,'R_SPR_ACC_769_DK',1,'Расчеты с депонентами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30403000',0,'R_SPR_ACC_769_DK',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30404000',0,'R_SPR_ACC_769_DK',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '88888888',0,'R_SPR_ACC_769_DK',1,'',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_ACC_769_DK'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503769 Итого по счету дебет С КОДОМ R_SPR_ACC_769_K------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_769_K'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_769_K', 'План счетов для 0503769 Итого по счету дебет', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_769_K]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_769_K]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503769 Итого по счету дебет (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_769_K]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_769_K' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_769_K] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_K')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_K'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_K', 'План счетов для 0503769 Итого по счету дебет', 195, (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_ACC_769_K', NAME = 'План счетов для 0503769 Итого по счету дебет', ORDERS = '195', 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_ACC_769_K'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_K_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_K_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_K_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_K_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_K_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_K_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_K_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_K_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_K'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_K_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K', 'TITLE', 'План счетов для 0503769 Итого по счету дебет'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_769_K'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_769_K'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K', 'SERVER_TABLE_NAME', 'R_SPR_ACC_769_K'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_769_K'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_K_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_K', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_K', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_K', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_769_K',0,'План счетов для 0503769 Итого по счету дебет','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_ACC_769_K',@link_self,'План счетов для 0503769 Итого по счету дебет','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_K')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_K')
delete report_kbk where code_form= 'R_SPR_ACC_769_K'
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 '20500000',0,'R_SPR_ACC_769_K',1,'Расчеты по доходам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20600000',0,'R_SPR_ACC_769_K',1,'Расчеты по выданным авансам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20700000',0,'R_SPR_ACC_769_K',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20800000',0,'R_SPR_ACC_769_K',1,'Расчеты с подотчетными лицами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '20900000',0,'R_SPR_ACC_769_K',1,'Расчеты по ущербу имуществу',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '21000000',0,'R_SPR_ACC_769_K',1,'Прочие расчеты с дебиторами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '88888888',0,'R_SPR_ACC_769_K',1,'',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_ACC_769_K'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503769 Итого по счету кредит С КОДОМ R_SPR_ACC_769_KK------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_769_KK'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_769_KK', 'План счетов для 0503769 Итого по счету кредит', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_769_KK]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_769_KK]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503769 Итого по счету кредит (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_769_KK]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_769_KK' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_769_KK] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_KK')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_769_KK'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_KK', 'План счетов для 0503769 Итого по счету кредит', 197, (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_ACC_769_KK', NAME = 'План счетов для 0503769 Итого по счету кредит', ORDERS = '197', 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_ACC_769_KK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_KK_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_KK_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_KK_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_KK_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_KK_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_KK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_769_KK_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_769_KK_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_769_KK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_769_KK_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK', 'TITLE', 'План счетов для 0503769 Итого по счету кредит'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_769_KK'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_769_KK'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK', 'SERVER_TABLE_NAME', 'R_SPR_ACC_769_KK'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_769_KK'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_769_KK_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_KK', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_KK', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_769_KK', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_769_KK',0,'План счетов для 0503769 Итого по счету кредит','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_ACC_769_KK',@link_self,'План счетов для 0503769 Итого по счету кредит','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_KK')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_ACC_769_KK')
delete report_kbk where code_form= 'R_SPR_ACC_769_KK'
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 '30200000',0,'R_SPR_ACC_769_KK',1,'Расчеты по принятым обязательствам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30300000',0,'R_SPR_ACC_769_KK',1,'Расчеты по платежам в бюджеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30400000',0,'R_SPR_ACC_769_KK',1,'Прочие расчеты с кредиторами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '88888888',0,'R_SPR_ACC_769_KK',1,'',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_ACC_769_KK'

GO


GO
exec RN_SAVE_REPORT_KBK 0,'0503314G_02_2010',0,'Форма 0503314G Расходы','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2010' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'0503314G_02_2010',@link_self,'Форма 0503314G Расходы','HEADER'
GO
delete report_control_protokol
delete report_kbk where code_form= '0503314G_02_2010'
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 '00000000000000000200',0,'0503314G_02_2010',1,'Расходы',0,'200',1,'00010','Расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000210',0,'0503314G_02_2010',1,'Оплата труда и начисления на оплату труда',0,'200',1,'00020','Оплата труда и начисления на оплату труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000211',0,'0503314G_02_2010',1,'Заработная плата',0,'200',0,'00030','Заработная плата', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000212',0,'0503314G_02_2010',1,'Прочие выплаты',0,'200',0,'00040','Прочие выплаты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000213',0,'0503314G_02_2010',1,'Начисления на оплату труда',0,'200',0,'00050','Начисления на оплату труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000220',0,'0503314G_02_2010',1,'Приобретение услуг',0,'200',1,'00060','Приобретение услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000221',0,'0503314G_02_2010',1,'Услуги связи',0,'200',0,'00070','Услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000222',0,'0503314G_02_2010',1,'Транспортные услуги',0,'200',0,'00080','Транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000223',0,'0503314G_02_2010',1,'Коммунальные услуги',0,'200',0,'00090','Коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000224',0,'0503314G_02_2010',1,'Арендная плата за пользование имуществом',0,'200',0,'00100','Арендная плата за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000225',0,'0503314G_02_2010',1,'Услуги по содержанию имущества',0,'200',0,'00110','Услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000226',0,'0503314G_02_2010',1,'Прочие услуги',0,'200',0,'00120','Прочие услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000230',0,'0503314G_02_2010',1,'Обслуживание долговых обязательств',0,'200',1,'00130','Обслуживание долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000231',0,'0503314G_02_2010',1,'Обслуживание внутренних долговых обязательств',0,'200',0,'00140','Обслуживание внутренних долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000232',0,'0503314G_02_2010',1,'Обслуживание внешних долговых обязательств',0,'200',0,'00150','Обслуживание внешних долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000240',0,'0503314G_02_2010',1,'Безвозмездные и безвозвратные перечисления организациям',0,'200',1,'00160','Безвозмездные и безвозвратные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000241',0,'0503314G_02_2010',1,'Безвозмездные и безвозвратные перечисления государственным и муниципальным организациям',0,'200',0,'00170','Безвозмездные и безвозвратные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000242',0,'0503314G_02_2010',1,'Безвозмездные и безвозвратные перечисления  организациям, за исключением государственных и муниципальных организаций',0,'200',0,'00180','Безвозмездные и безвозвратные перечисления  организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000250',0,'0503314G_02_2010',1,'Безвозмездные и безвозвратные перечисления бюджетам',0,'200',1,'00190','Безвозмездные и безвозвратные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000251',0,'0503314G_02_2010',1,'Перечисления другим бюджетам бюджетной системы Российской Федерации',0,'200',0,'00200','Перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000252',0,'0503314G_02_2010',1,'Перечисления наднациональным организациям и правительствам иностранных государств',0,'200',0,'00210','Перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000253',0,'0503314G_02_2010',1,'Перечисления международным организациям',0,'200',0,'00220','Перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000260',0,'0503314G_02_2010',1,'Социальное обеспечение',0,'200',1,'00230','Социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000261',0,'0503314G_02_2010',1,'Пособия по социальному страхованию населения',0,'200',0,'00240','Пособия по социальному страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000262',0,'0503314G_02_2010',1,'Пособия по социальной помощи населению',0,'200',0,'00250','Пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000263',0,'0503314G_02_2010',1,'Социальные пособия, выплачиваемые организациями сектора государственного управления',0,'200',0,'00260','Социальные пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000290',0,'0503314G_02_2010',1,'Прочие расходы',0,'200',0,'00270','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000300',0,'0503314G_02_2010',1,'Поступление нефинансовых активов',0,'200',1,'00280','Поступление нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000310',0,'0503314G_02_2010',1,'Увеличение стоимости основных средств',0,'200',0,'00290','Увеличение стоимости основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000320',0,'0503314G_02_2010',1,'Увеличение стоимости нематериальных активов',0,'200',0,'00300','Увеличение стоимости нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000330',0,'0503314G_02_2010',1,'Увеличение стоимости непроизведенных активов',0,'200',0,'00305','Увеличение стоимости непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000340',0,'0503314G_02_2010',1,'Увеличение стоимости материальных запасов',0,'200',0,'00310','Увеличение стоимости материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000500',0,'0503314G_02_2010',1,'Поступление финансовых активов',0,'200',1,'00320','Поступление финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000530',0,'0503314G_02_2010',1,'Увеличение стоимости акций и иных форм участия в капитале',0,'200',0,'00330','Увеличение стоимости акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000540',0,'0503314G_02_2010',1,'Увеличение задолженности по бюджетным ссудам и кредитам',0,'200',0,'00340','Увеличение задолженности по бюджетным ссудам и кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000600',0,'0503314G_02_2010',1,'Выбытие финансовых активов',0,'200',1,'00350','Выбытие финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000620',0,'0503314G_02_2010',1,'Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'200',0,'00360','Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00000000000000000640',0,'0503314G_02_2010',1,'Уменьшение задолженности по бюджетным ссудам и кредитам',0,'200',0,'00370','Уменьшение задолженности по бюджетным ссудам и кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00079000000000000000',0,'0503314G_02_2010',1,'Результат исполнения бюджета (дефицит "--", профицит "+")',0,'450',2,'00390','Результат исполнения бюджета (дефицит "--", профицит "+")', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '00096000000000000000',0,'0503314G_02_2010',1,'Расходы бюджета - ИТОГО',0,'200',0,'00380','Расходы бюджета - ИТОГО', NULL,NULL,0


GO


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 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010120000',@link_self,'Основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010121000',@link_self,'Жилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010121310',@link_self,'Увеличение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010121410',@link_self,'Уменьшение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010122000',@link_self,'Нежилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010122310',@link_self,'Увеличение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010122410',@link_self,'Уменьшение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010123000',@link_self,'Сооружения - особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010123310',@link_self,'Увеличение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010123410',@link_self,'Уменьшение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010124000',@link_self,'Машины и оборудование – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010124310',@link_self,'Увеличение стоимости машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010124410',@link_self,'Уменьшение стоимости машин и оборудования– особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010125000',@link_self,'Транспортные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010125310',@link_self,'Увеличение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010125410',@link_self,'Уменьшение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010126000',@link_self,'Производственный и хозяйственный инвентарь – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010126310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010126410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010127310',@link_self,'Увеличение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010127410',@link_self,'Уменьшение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010128000',@link_self,'Прочие основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010128310',@link_self,'Увеличение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010128410',@link_self,'Уменьшение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'010991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'020982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'021553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'030900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'040230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'050600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'10712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'10714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'110991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'120982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'150600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210120000',@link_self,'Основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210121000',@link_self,'Жилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210121310',@link_self,'Увеличение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210121410',@link_self,'Уменьшение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210122000',@link_self,'Нежилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210122310',@link_self,'Увеличение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210122410',@link_self,'Уменьшение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210123000',@link_self,'Сооружения - особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210123310',@link_self,'Увеличение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210123410',@link_self,'Уменьшение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210124000',@link_self,'Машины и оборудование – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210124310',@link_self,'Увеличение стоимости машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210124410',@link_self,'Уменьшение стоимости машин и оборудования– особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210125000',@link_self,'Транспортные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210125310',@link_self,'Увеличение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210125410',@link_self,'Уменьшение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210126000',@link_self,'Производственный и хозяйственный инвентарь – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210126310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210126410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210127310',@link_self,'Увеличение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210127410',@link_self,'Уменьшение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210128000',@link_self,'Прочие основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210128310',@link_self,'Увеличение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210128410',@link_self,'Уменьшение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210421000',@link_self,'Амортизация жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210421410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210422000',@link_self,'Амортизация нежилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210422410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210423000',@link_self,'Амортизация сооружений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210423410',@link_self,'Уменьшение за счет амортизации стоимости сооружений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210424000',@link_self,'Амортизация машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210424410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210425000',@link_self,'Амортизация транспортных средств – особо ценного  движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств – особо ценного  движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210425410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210426000',@link_self,'Амортизация производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210426410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210427000',@link_self,'Амортизация библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210427410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210428000',@link_self,'Амортизация прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210428410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210429000',@link_self,'Амортизация нематериальных активов – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210429420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'210991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'250600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'310991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'320982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'321553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'330900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'340230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'350600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'40429000',@link_self,'Амортизация нематериальных активов – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410120000',@link_self,'Основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410121000',@link_self,'Жилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410121310',@link_self,'Увеличение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410121410',@link_self,'Уменьшение стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410122000',@link_self,'Нежилые помещения – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410122310',@link_self,'Увеличение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410122410',@link_self,'Уменьшение стоимости нежилых помещений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410123000',@link_self,'Сооружения - особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410123310',@link_self,'Увеличение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410123410',@link_self,'Уменьшение стоимости сооружений - особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410124000',@link_self,'Машины и оборудование – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410124310',@link_self,'Увеличение стоимости машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410124410',@link_self,'Уменьшение стоимости машин и оборудования– особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410125000',@link_self,'Транспортные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410125310',@link_self,'Увеличение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410125410',@link_self,'Уменьшение стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410126000',@link_self,'Производственный и хозяйственный инвентарь – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410126310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410126410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410127310',@link_self,'Увеличение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410127410',@link_self,'Уменьшение стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410128000',@link_self,'Прочие основные средства – особо ценное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410128310',@link_self,'Увеличение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410128410',@link_self,'Уменьшение стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410420000',@link_self,'Амортизация  особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410421000',@link_self,'Амортизация жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410421410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410422000',@link_self,'Амортизация нежилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410422410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410423000',@link_self,'Амортизация сооружений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410423410',@link_self,'Уменьшение за счет амортизации стоимости сооружений – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410424000',@link_self,'Амортизация машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410424410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410425000',@link_self,'Амортизация транспортных средств – особо ценного  движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств – особо ценного  движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410425410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410426000',@link_self,'Амортизация производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410426410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410427000',@link_self,'Амортизация библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410427410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410428000',@link_self,'Амортизация прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410428410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410429420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов – особо ценного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов – особо ценного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'410991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'420982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'421553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Основные средства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'450600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'510991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'520982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'521553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Акции',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Облигации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Векселя',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Касса',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Денежные документы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Амортизация',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'550600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'610991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'620982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'621553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'650600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710000000',@link_self,'НЕФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710100000',@link_self,'Основные средства','ПлСчет_Каз_2011',0,'',0,'','Основные средства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710110000',@link_self,'Основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710111000',@link_self,'Жилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710111310',@link_self,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710111410',@link_self,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710112000',@link_self,'Нежилые помещения – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710112310',@link_self,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710112410',@link_self,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710113000',@link_self,'Сооружения - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710113310',@link_self,'Увеличение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710113410',@link_self,'Уменьшение стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710115000',@link_self,'Транспортные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710115310',@link_self,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710115410',@link_self,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710118000',@link_self,'Прочие основные средства – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710118310',@link_self,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710118410',@link_self,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710130000',@link_self,'Основные средства –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Основные средства –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710131000',@link_self,'Жилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710131310',@link_self,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710131410',@link_self,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710132000',@link_self,'Нежилые помещения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710132310',@link_self,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710132410',@link_self,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710133000',@link_self,'Сооружения – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Сооружения – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710133310',@link_self,'Увеличение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710133410',@link_self,'Уменьшение стоимости сооружений – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710134000',@link_self,'Машины и оборудование – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710134310',@link_self,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710134410',@link_self,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710135000',@link_self,'Транспортные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710135310',@link_self,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710135410',@link_self,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710136000',@link_self,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710136310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710136410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710137000',@link_self,'Библиотечный фонд – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710137310',@link_self,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710137410',@link_self,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710138000',@link_self,'Прочие основные средства – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710138310',@link_self,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710138410',@link_self,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710140000',@link_self,'Основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710141000',@link_self,'Жилые помещения - предметы  лизинга','ПлСчет_Каз_2011',0,'',0,'','Жилые помещения - предметы  лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710141310',@link_self,'Увеличение стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710141410',@link_self,'Уменьшение стоимости жилых помещений -предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710142000',@link_self,'Нежилые помещения – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нежилые помещения – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710142310',@link_self,'Увеличение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710142410',@link_self,'Уменьшение стоимости нежилых помещений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710143000',@link_self,'Сооружения - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Сооружения - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710143310',@link_self,'Увеличение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710143410',@link_self,'Уменьшение стоимости сооружений – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710144000',@link_self,'Машины и оборудование – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Машины и оборудование – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710144310',@link_self,'Увеличение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710144410',@link_self,'Уменьшение стоимости машин и оборудования – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710145000',@link_self,'Транспортные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Транспортные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710145310',@link_self,'Увеличение стоимости транспортных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710145410',@link_self,'Уменьшение стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710146000',@link_self,'Производственный и хозяйственный инвентарь – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710146310',@link_self,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710146410',@link_self,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710147000',@link_self,'Библиотечный фонд – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Библиотечный фонд – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710147310',@link_self,'Увеличение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710147410',@link_self,'Уменьшение стоимости библиотечного фонда – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710148000',@link_self,'Прочие основные средства – предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие основные средства – предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710148310',@link_self,'Увеличение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710148410',@link_self,'Уменьшение стоимости прочих основных средств – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710200000',@link_self,'Нематериальные активы','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710230000',@link_self,'Нематериальные активы –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710230320',@link_self,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710230420',@link_self,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710240000',@link_self,'Нематериальные активы –  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы –  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710240320',@link_self,'Увеличение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710240420',@link_self,'Уменьшение стоимости нематериальных активов – предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710300000',@link_self,'Непроизведенные активы','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710310000',@link_self,'Непроизведенные активы – недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710311000',@link_self,'Земля - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Земля - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710311330',@link_self,'Увеличение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710311430',@link_self,'Уменьшение стоимости земли - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710312000',@link_self,'Ресурсы недр - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710312330',@link_self,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710312430',@link_self,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710313000',@link_self,'Прочие непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710313330',@link_self,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710313430',@link_self,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710400000',@link_self,'Амортизация','ПлСчет_Каз_2011',0,'',0,'','Амортизация','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710410000',@link_self,'Амортизация недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710411000',@link_self,'Амортизация жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710411410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710412000',@link_self,'Амортизация нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710412410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710413000',@link_self,'Амортизация сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710413410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710415000',@link_self,'Амортизация транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710415410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710418000',@link_self,'Амортизация прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710418410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710430000',@link_self,'Амортизация  иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация  иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710431000',@link_self,'Амортизация жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710431410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710432000',@link_self,'Амортизация нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710432410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710433000',@link_self,'Амортизация сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710433410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710434000',@link_self,'Амортизация машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710434410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710435000',@link_self,'Амортизация транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710435410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710436000',@link_self,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710436410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710437000',@link_self,'Амортизация библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710437410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710438000',@link_self,'Амортизация прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710438410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710439000',@link_self,'Амортизация нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710439420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710440000',@link_self,'Амортизация предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710441000',@link_self,'Амортизация жилых помещений - предметов  лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация жилых помещений - предметов  лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710441410',@link_self,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710442000',@link_self,'Амортизация нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нежилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710442410',@link_self,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710443000',@link_self,'Амортизация сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация сооружений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710443410',@link_self,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710444000',@link_self,'Амортизация машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация машин и оборудования - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710444410',@link_self,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710445000',@link_self,'Амортизация транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710445410',@link_self,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710446000',@link_self,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710446410',@link_self,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710447000',@link_self,'Амортизация библиотечного фонда -  предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710447410',@link_self,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710448000',@link_self,'Амортизация прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация прочих основных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710448410',@link_self,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710449000',@link_self,'Амортизация нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710449420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710450000',@link_self,'Амортизация имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Амортизация имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710451000',@link_self,'Амортизация недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710451410',@link_self,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710458000',@link_self,'Амортизация движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация движимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710458410',@link_self,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710459000',@link_self,'Амортизация нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Амортизация нематериальных активов в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710459420',@link_self,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','ПлСчет_Каз_2011',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710500000',@link_self,'Материальные запасы','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710530000',@link_self,'Материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710531000',@link_self,'Медикаменты и перевязочные средств - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710531340',@link_self,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710531440',@link_self,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710532000',@link_self,'Продукты питания - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Продукты питания - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710532340',@link_self,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710532440',@link_self,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710533000',@link_self,'Горюче-смазочные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710533340',@link_self,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710533440',@link_self,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710534000',@link_self,'Строительные материалы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710534340',@link_self,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710534440',@link_self,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710535000',@link_self,'Мягкий инвентарь - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710535340',@link_self,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710535440',@link_self,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710536000',@link_self,'Прочие материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710536340',@link_self,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710536440',@link_self,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710537000',@link_self,'Готовая продукция - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Готовая продукция - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710537340',@link_self,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710537440',@link_self,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710538000',@link_self,'Товары –  иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Товары –  иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710538340',@link_self,'Увеличение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710538440',@link_self,'Уменьшение стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710539000',@link_self,'Наценка на товары – иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Наценка на товары – иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710539340',@link_self,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710540000',@link_self,'Материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710544000',@link_self,'Строительные материалы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Строительные материалы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710544340',@link_self,'Увеличение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710544440',@link_self,'Уменьшение стоимости строительных материалов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710546000',@link_self,'Прочие материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Прочие материальные запасы -  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710546340',@link_self,'Увеличение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710546440',@link_self,'Уменьшение стоимости прочих материальных запасов - предметов лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710600000',@link_self,'Вложения в нефинансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в нефинансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710610000',@link_self,'Вложения в недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710611000',@link_self,'Вложения в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710611310',@link_self,'Увеличение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710611410',@link_self,'Уменьшение вложений в основные средства - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710613000',@link_self,'Вложения в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710613330',@link_self,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710613430',@link_self,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710630000',@link_self,'Вложения в иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710631000',@link_self,'Вложения в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710631310',@link_self,'Увеличение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710631410',@link_self,'Уменьшение вложений в основные средства - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710632000',@link_self,'Вложения в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710632320',@link_self,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710632420',@link_self,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710634000',@link_self,'Вложения в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710634340',@link_self,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710634440',@link_self,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710640000',@link_self,'Вложения в предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710641000',@link_self,'Вложения в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710641310',@link_self,'Увеличение вложений в основные средства - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710641410',@link_self,'Уменьшение вложений в основные средства - предмета лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710642000',@link_self,'Вложения в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в нематериальные активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710642320',@link_self,'Увеличение вложений в нематериальные активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710642420',@link_self,'Уменьшение вложений в нематериальные  активы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710644000',@link_self,'Вложения в материальные запасы -  предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Вложения в материальные запасы -  предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710644340',@link_self,'Увеличение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710644440',@link_self,'Уменьшение вложений в материальные запасы - предметы лизинга','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710700000',@link_self,'Нефинансовые активы в пути','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710710000',@link_self,'Недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710711000',@link_self,'Основные средства – недвижимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710711310',@link_self,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710711410',@link_self,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710730000',@link_self,'Иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710731000',@link_self,'Основные средства - иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710731310',@link_self,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710731410',@link_self,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710733000',@link_self,'Материальные запасы – иное движимое имущество учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710733340',@link_self,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710733440',@link_self,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710740000',@link_self,'Предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710741000',@link_self,'Основные средства - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Основные средства - предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710741310',@link_self,'Увеличение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710741410',@link_self,'Уменьшение стоимости основных средств - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710743000',@link_self,'Материальные запасы - предметы лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы - предметы лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710743340',@link_self,'Увеличение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710743440',@link_self,'Уменьшение стоимости материальных запасов - предметов лизинга в пути','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710800000',@link_self,'Нефинансовые активы имущества казны','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы имущества казны','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710850000',@link_self,'Нефинансовые активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нефинансовые активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710851000',@link_self,'Недвижимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Недвижимое имущество, составляющее казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710851310',@link_self,'Увеличение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710851410',@link_self,'Уменьшение стоимости недвижимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710852000',@link_self,'Движимое имущество, составляющее казну','ПлСчет_Каз_2011',0,'',0,'','Движимое имущество, составляющее казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710852310',@link_self,'Увеличение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710852410',@link_self,'Уменьшение стоимости движимого имущества, составляющего казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710853000',@link_self,'Драгоценности и ювелирные изделия','ПлСчет_Каз_2011',0,'',0,'','Драгоценности и ювелирные изделия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710853310',@link_self,'Увеличение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710853410',@link_self,'Уменьшение стоимости драгоценных и ювелирных изделий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710854000',@link_self,'Нематериальные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Нематериальные активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710854320',@link_self,'Увеличение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710854420',@link_self,'Уменьшение стоимости нематериальных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710855000',@link_self,'Непроизведенные активы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Непроизведенные активы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710855330',@link_self,'Увеличение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710855430',@link_self,'Уменьшение стоимости непроизведенных активов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710856000',@link_self,'Материальные запасы, составляющие казну','ПлСчет_Каз_2011',0,'',0,'','Материальные запасы, составляющие казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710856340',@link_self,'Увеличение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710856440',@link_self,'Уменьшение стоимости материальных запасов, составляющих казну','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710900000',@link_self,'Затраты на изготовление готовой продукции, выполнение работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710960000',@link_self,'Себестоимость готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Себестоимость готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961211',@link_self,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961212',@link_self,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961213',@link_self,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961221',@link_self,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961222',@link_self,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961223',@link_self,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961224',@link_self,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961225',@link_self,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961226',@link_self,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961271',@link_self,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961272',@link_self,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710961290',@link_self,'Прочие затраты в себестоимости готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710970000',@link_self,'Накладные расходы производства готовой продукции, работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971211',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971212',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971213',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971221',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971222',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971223',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971224',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971225',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971226',@link_self,'Накладные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971271',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971272',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710971290',@link_self,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710980000',@link_self,'Общехозяйственные расходы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981211',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981212',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981213',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981221',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981222',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981223',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981224',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981225',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981226',@link_self,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981271',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981272',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710981290',@link_self,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710990000',@link_self,'Издержки обращения','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991211',@link_self,'Издержки обращения в части заработной платы','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части заработной платы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991212',@link_self,'Издержки обращения в части прочих выплат','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих выплат','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991213',@link_self,'Издержки обращения в части начислений на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991221',@link_self,'Издержки обращения в части услуг связи','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991222',@link_self,'Издержки обращения в части транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991223',@link_self,'Издержки обращения в части коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991224',@link_self,'Издержки обращения в части арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991225',@link_self,'Издержки обращения в части содержания имущества','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части содержания имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991226',@link_self,'Издержки обращения в части прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991271',@link_self,'Издержки обращения в части амортизации основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991272',@link_self,'Издержки обращения в части расходования материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части расходования материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'710991290',@link_self,'Издержки обращения в части прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Издержки обращения в части прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720000000',@link_self,'ФИНАНСОВЫЕ АКТИВЫ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720100000',@link_self,'Денежные средства учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720111510',@link_self,'Поступления денежных средств учреждения на лицевые счета в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720111610',@link_self,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720113510',@link_self,'Поступления денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720113610',@link_self,'Выбытия денежных средств учреждения в пути в органе казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720121510',@link_self,'Поступления денежных средств учреждения на счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720121610',@link_self,'Выбытия денежных средств учреждения со счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720122510',@link_self,'Поступления денежных средств учреждения на депозитные счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720122610',@link_self,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720123510',@link_self,'Поступление денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720123610',@link_self,'Выбытия денежных средств учреждения в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720126510',@link_self,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720126610',@link_self,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720127510',@link_self,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720127610',@link_self,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720130000',@link_self,'Денежные средства  в кассе учреждения','ПлСчет_Каз_2011',0,'',0,'','Денежные средства  в кассе учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720134000',@link_self,'Касса','ПлСчет_Каз_2011',0,'',0,'','Касса','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720134510',@link_self,'Поступления средств в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления средств в кассу учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720134610',@link_self,'Выбытия средств из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств из кассы учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720135000',@link_self,'Денежные документы','ПлСчет_Каз_2011',0,'',0,'','Денежные документы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720135510',@link_self,'Поступления денежных документов в кассу учреждения','ПлСчет_Каз_2011',0,'',0,'','Поступления денежных документов в кассу учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720135610',@link_self,'Выбытия денежных документов из кассы учреждения','ПлСчет_Каз_2011',0,'',0,'','Выбытия денежных документов из кассы учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720200000',@link_self,'Средства на счетах бюджета','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720210000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720211000',@link_self,'Средства на счетах бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720211510',@link_self,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720211610',@link_self,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720212000',@link_self,'Средства на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720212510',@link_self,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720212610',@link_self,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720213000',@link_self,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720213510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720213610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720220000',@link_self,'Средства на счетах бюджета в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720221000',@link_self,'Средства на счетах бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720221510',@link_self,'Поступления средств на счета бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720221610',@link_self,'Выбытия средств со счетов бюджета в рублях в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720222000',@link_self,'Средства на счетах бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720222510',@link_self,'Поступления средств на счета бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720222610',@link_self,'Выбытия средств со счетов бюджета в кредитной организации в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720223000',@link_self,'Средства на счетах бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720223510',@link_self,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720223610',@link_self,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720230000',@link_self,'Средства бюджета на депозитных счетах','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720231000',@link_self,'Средства бюджета на депозитных счетах в рублях','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720231510',@link_self,'Поступления средств бюджета на депозитные счета в рублях','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720231610',@link_self,'Выбытия средств бюджета с депозитных счетов в рублях','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720232000',@link_self,'Средства бюджета на депозитных счетах в пути','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720232510',@link_self,'Поступления средств бюджета на депозитные счета в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720232610',@link_self,'Выбытия средств бюджета с депозитных счетов в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720233000',@link_self,'Средства бюджета на депозитных счетах в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720233510',@link_self,'Поступления средств бюджета на депозитные счета в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720233610',@link_self,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720300000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720301000',@link_self,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720301510',@link_self,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720301610',@link_self,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720310000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720312000',@link_self,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720312510',@link_self,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720312610',@link_self,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720313000',@link_self,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720313510',@link_self,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720313610',@link_self,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720314000',@link_self,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720314510',@link_self,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720314610',@link_self,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720315000',@link_self,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720315510',@link_self,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720315610',@link_self,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720320000',@link_self,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720320510',@link_self,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720320610',@link_self,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720330000',@link_self,'Средства на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720332000',@link_self,'Средства бюджета на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720332510',@link_self,'Поступления средств бюджета на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720332610',@link_self,'Выбытия средств бюджета со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720333000',@link_self,'Средства бюджетных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720333510',@link_self,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720333610',@link_self,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720334000',@link_self,'Средства автономных учреждений на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720334510',@link_self,'Поступления средств автономных учреждений на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720334610',@link_self,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720335000',@link_self,'Средства иных организаций на счетах для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720335510',@link_self,'Поступления средств иных организаций на счета для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720335610',@link_self,'Выбытия средств иных организаций со счетов для выплаты наличных денег','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720400000',@link_self,'Финансовые вложения','ПлСчет_Каз_2011',0,'',0,'','Финансовые вложения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720420000',@link_self,'Ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720421000',@link_self,'Облигации','ПлСчет_Каз_2011',0,'',0,'','Облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720421520',@link_self,'Увеличение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости облигаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720421620',@link_self,'Уменьшение стоимости облигаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости облигаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720422000',@link_self,'Векселя','ПлСчет_Каз_2011',0,'',0,'','Векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720422520',@link_self,'Увеличение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости векселей','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720422620',@link_self,'Уменьшение стоимости векселей','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости векселей','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720423000',@link_self,'Иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720423520',@link_self,'Увеличение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720423620',@link_self,'Уменьшение стоимости иных ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720430000',@link_self,'Акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Акции и иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720431000',@link_self,'Акции','ПлСчет_Каз_2011',0,'',0,'','Акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720431530',@link_self,'Увеличение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720431630',@link_self,'Уменьшение стоимости акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720432000',@link_self,'Уставной фонд государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720432530',@link_self,'Увеличение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720432630',@link_self,'Уменьшение уставного фонда государственных (муниципальных) предприятий','ПлСчет_Каз_2011',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720433000',@link_self,'Участие в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Участие в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720433530',@link_self,'Увеличение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720433630',@link_self,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720434000',@link_self,'Иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720434530',@link_self,'Увеличение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720434630',@link_self,'Уменьшение стоимости иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720450000',@link_self,'Иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Иные финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720451000',@link_self,'Активы в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Активы в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720451550',@link_self,'Увеличение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости активов в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720451650',@link_self,'Уменьшение стоимости активов в управляющих компаниях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720452000',@link_self,'Доли в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Доли в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720452550',@link_self,'Увеличение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости долей в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720452650',@link_self,'Уменьшение стоимости долей в международных организациях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости долей в международных организациях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720453000',@link_self,'Прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720453550',@link_self,'Увеличение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение стоимости прочих финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720453650',@link_self,'Уменьшение стоимости прочих финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение стоимости прочих финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720500000',@link_self,'Расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720510000',@link_self,'Расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720511000',@link_self,'Расчеты с плательщиками налоговых доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками налоговых доходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720511560',@link_self,'Увеличение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720511660',@link_self,'Уменьшение дебиторской задолженности по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720520000',@link_self,'Расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720521000',@link_self,'Расчеты с плательщиками доходов от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720521560',@link_self,'Увеличение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720521660',@link_self,'Уменьшение дебиторской задолженности по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720530000',@link_self,'Расчеты по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720531000',@link_self,'Расчеты с плательщиками доходов от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720531560',@link_self,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720531660',@link_self,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720540000',@link_self,'Расчеты по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720541000',@link_self,'Расчеты с плательщиками сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720541560',@link_self,'Увеличение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720541660',@link_self,'Уменьшение дебиторской задолженности по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720550000',@link_self,'Расчеты по поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720551000',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720551560',@link_self,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720551660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720552000',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720552560',@link_self,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720552660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720553000',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720553560',@link_self,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720553660',@link_self,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720560000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720561000',@link_self,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720561560',@link_self,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720561660',@link_self,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720570000',@link_self,'Расчеты по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720571000',@link_self,'Расчеты по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720571560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720571660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720572000',@link_self,'Расчеты по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720572560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720572660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720573000',@link_self,'Расчеты по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720573560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720573660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720574000',@link_self,'Расчеты по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720574560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720574660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720575000',@link_self,'Расчеты по доходам от операций с финансовыми  активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720575560',@link_self,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720575660',@link_self,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720580000',@link_self,'Расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720581000',@link_self,'Расчеты с плательщиками прочих доходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с плательщиками прочих доходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720581560',@link_self,'Увеличение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720581660',@link_self,'Уменьшение дебиторской задолженности по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720600000',@link_self,'Расчеты по выданным авансам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выданным авансам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720610000',@link_self,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720612000',@link_self,'Расчеты по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720612560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720612660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720613000',@link_self,'Расчеты по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720613560',@link_self,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720613660',@link_self,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720620000',@link_self,'Расчеты по авансам по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720621000',@link_self,'Расчеты по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720621560',@link_self,'Увеличение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720621660',@link_self,'Уменьшение дебиторской задолженности по авансам по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720622000',@link_self,'Расчеты по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720622560',@link_self,'Увеличение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720622660',@link_self,'Уменьшение дебиторской задолженности по авансам по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720623000',@link_self,'Расчеты по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720623560',@link_self,'Увеличение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720623660',@link_self,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720624000',@link_self,'Расчеты по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720624560',@link_self,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720624660',@link_self,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720625000',@link_self,'Расчеты по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720625560',@link_self,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720625660',@link_self,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720626000',@link_self,'Расчеты по авансам по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720626560',@link_self,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720626660',@link_self,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720630000',@link_self,'Расчеты по авансам по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720631000',@link_self,'Расчеты по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720631560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720631660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720632000',@link_self,'Расчеты по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720632560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720632660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720633000',@link_self,'Расчеты по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720633560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720633660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720634000',@link_self,'Расчеты по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720634560',@link_self,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720634660',@link_self,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720640000',@link_self,'Расчеты по авансовым безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720641000',@link_self,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720641560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720641660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720642000',@link_self,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720642560',@link_self,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720642660',@link_self,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720650000',@link_self,'Расчеты по авансовым безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720651000',@link_self,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720651560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720651660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720652000',@link_self,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720652560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720652660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720653000',@link_self,'Расчеты по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720653560',@link_self,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720653660',@link_self,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720660000',@link_self,'Расчеты по авансам по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720661000',@link_self,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720661560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720661660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720662000',@link_self,'Расчеты по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720662560',@link_self,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720662660',@link_self,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720663000',@link_self,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720663560',@link_self,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720663660',@link_self,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720690000',@link_self,'Расчеты по авансам по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720691000',@link_self,'Расчеты по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720691560',@link_self,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720691660',@link_self,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720700000',@link_self,'Расчеты по кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по кредитам, займам (ссудам)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720710000',@link_self,'Расчеты по предоставленным кредитам, займам (ссудам)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720711000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720711540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720711640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720713000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720713540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720713640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720714000',@link_self,'Расчеты по предоставленным займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720714540',@link_self,'Увеличение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720714640',@link_self,'Уменьшение задолженности дебиторов по займам, ссудам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720720000',@link_self,'Расчеты в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720721000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720721540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720721640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720723000',@link_self,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720723540',@link_self,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720723640',@link_self,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720724000',@link_self,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720724540',@link_self,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720724640',@link_self,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720730000',@link_self,'Расчеты с дебиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720731000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720731540',@link_self,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720731640',@link_self,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720733000',@link_self,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720733540',@link_self,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720733640',@link_self,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720800000',@link_self,'Расчеты с подотчетными лицами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720810000',@link_self,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720811000',@link_self,'Расчеты с подотчетными лицами по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720811560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720811660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720812000',@link_self,'Расчеты с подотчетными лицами по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720812560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720812660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720813000',@link_self,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720813560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720813660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720820000',@link_self,'Расчеты с подотчетными лицами по работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720821000',@link_self,'Расчеты с подотчетными лицами по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720821560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720821660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720822000',@link_self,'Расчеты с подотчетными лицами по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720822560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720822660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720823000',@link_self,'Расчеты с подотчетными лицами по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720823560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720823660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720824000',@link_self,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720824560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720824660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720825000',@link_self,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720825560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720825660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720826000',@link_self,'Расчеты с подотчетными лицами по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720826560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720826660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720830000',@link_self,'Расчеты с подотчетными лицами по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720831000',@link_self,'Расчеты с подотчетными лицами по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720831560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720831660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720832000',@link_self,'Расчеты с подотчетными лицами по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720832560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720832660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720834000',@link_self,'Расчеты с подотчетными лицами по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720834560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720834660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720860000',@link_self,'Расчеты с подотчетными лицами по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720861000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720861560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720861660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720862000',@link_self,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720862560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720862660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720863000',@link_self,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720863560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720863660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720890000',@link_self,'Расчеты с подотчетными лицами по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720891000',@link_self,'Расчеты с подотчетными лицами по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720891560',@link_self,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720891660',@link_self,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720900000',@link_self,'Расчеты по ущербу имуществу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу имуществу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720970000',@link_self,'Расчеты по ущербу нефинансовым активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу нефинансовым активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720971000',@link_self,'Расчеты по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720971560',@link_self,'Увеличение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720971660',@link_self,'Уменьшение дебиторской задолженности по ущербу основным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720972000',@link_self,'Расчеты по ущербу  нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу  нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720972560',@link_self,'Увеличение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720972660',@link_self,'Уменьшение дебиторской задолженности по ущербу нематериальным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720973000',@link_self,'Расчеты по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720973560',@link_self,'Увеличение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720973660',@link_self,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720974000',@link_self,'Расчеты по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720974560',@link_self,'Увеличение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720974660',@link_self,'Уменьшение дебиторской задолженности по ущербу материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720980000',@link_self,'Расчеты по прочему ущербу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочему ущербу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720981000',@link_self,'Расчеты по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720981560',@link_self,'Увеличение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720981660',@link_self,'Уменьшение дебиторской задолженности по недостачам денежных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720982000',@link_self,'Расчеты по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720982560',@link_self,'Увеличение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720982660',@link_self,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721000000',@link_self,'Прочие расчеты с дебиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с дебиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721001000',@link_self,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721001560',@link_self,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721001660',@link_self,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002000',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002100',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002110',@link_self,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002120',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002130',@link_self,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002140',@link_self,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002150',@link_self,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002151',@link_self,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002152',@link_self,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002153',@link_self,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002160',@link_self,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002170',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002171',@link_self,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002173',@link_self,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002180',@link_self,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002400',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002410',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002420',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002430',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002440',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002600',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002620',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002630',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002640',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002650',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002700',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002710',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721002720',@link_self,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721003000',@link_self,'Расчеты с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721003560',@link_self,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721003660',@link_self,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004000',@link_self,'Расчеты по распределенным поступлениям к зачислению в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004100',@link_self,'Расчеты по поступившим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004110',@link_self,'Расчеты по поступившим налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004120',@link_self,'Расчеты по поступившим доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004130',@link_self,'Расчеты по поступившим доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004140',@link_self,'Расчеты по поступившим суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004150',@link_self,'Расчеты по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004151',@link_self,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004152',@link_self,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004153',@link_self,'Расчеты по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004160',@link_self,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004170',@link_self,'Расчеты по поступившим доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004171',@link_self,'Расчеты по поступившим доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004180',@link_self,'Расчеты по поступившим прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступившим прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004400',@link_self,'Расчеты по поступлениям от выбытия нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004410',@link_self,'Расчет по поступлениям от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчет по поступлениям от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004420',@link_self,'Расчеты по поступлениям от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004430',@link_self,'Расчеты по поступлениям от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004440',@link_self,'Расчеты по поступлениям от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004600',@link_self,'Расчеты по поступлениям от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004610',@link_self,'Расчеты по поступлениям от возврата депозитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата депозитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004620',@link_self,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004630',@link_self,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004640',@link_self,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004650',@link_self,'Расчеты по поступлениям от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004700',@link_self,'Расчеты по поступлениям от заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004710',@link_self,'Расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721004720',@link_self,'Расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлениям внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721005000',@link_self,'Расчеты с прочими дебиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими дебиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721005560',@link_self,'Увеличение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721005660',@link_self,'Уменьшение дебиторской задолженности прочих дебиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721006000',@link_self,'Расчеты с учредителем','ПлСчет_Каз_2011',0,'',0,'','Расчеты с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721006560',@link_self,'Увеличение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Увеличение расчетов с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721006660',@link_self,'Уменьшение расчетов с учредителем','ПлСчет_Каз_2011',0,'',0,'','Уменьшение расчетов с учредителем','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721100000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721100560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721100660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721200000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721200560',@link_self,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721200660',@link_self,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721500000',@link_self,'Вложения в финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721520000',@link_self,'Вложения в ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721521000',@link_self,'Вложения в облигации','ПлСчет_Каз_2011',0,'',0,'','Вложения в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721521520',@link_self,'Увеличение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721521620',@link_self,'Уменьшение вложений в облигации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в облигации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721522000',@link_self,'Вложения в векселя','ПлСчет_Каз_2011',0,'',0,'','Вложения в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721522520',@link_self,'Увеличение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721522620',@link_self,'Уменьшение вложений в векселя','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в векселя','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721523000',@link_self,'Вложения в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721523520',@link_self,'Увеличение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721523620',@link_self,'Уменьшение вложений в иные ценные бумаги, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721530000',@link_self,'Вложения в акции и иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции и иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721531000',@link_self,'Вложения в акции','ПлСчет_Каз_2011',0,'',0,'','Вложения в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721531530',@link_self,'Увеличение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721531630',@link_self,'Уменьшение вложений в акции','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в акции','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721532000',@link_self,'Вложения  в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Вложения  в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721532530',@link_self,'Увеличение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721532630',@link_self,'Уменьшение вложений в государственные (муниципальные) предприятия','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721533000',@link_self,'Вложения в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Вложения в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721533530',@link_self,'Увеличение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721533630',@link_self,'Уменьшение вложений в государственные (муниципальные) учреждения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721534000',@link_self,'Вложения в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721534530',@link_self,'Увеличение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721534630',@link_self,'Уменьшение вложений в иные формы участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в иные формы участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721550000',@link_self,'Вложения в иные финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в иные финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721551000',@link_self,'Вложения в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Вложения в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721551550',@link_self,'Увеличение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721551650',@link_self,'Уменьшение вложений в управляющие компании','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в управляющие компании','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721552000',@link_self,'Вложения в международные организации','ПлСчет_Каз_2011',0,'',0,'','Вложения в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721552550',@link_self,'Увеличение вложений в международные организации','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721552650',@link_self,'Уменьшение вложений в доли в международные организации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в доли в международные организации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721553000',@link_self,'Вложения в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Вложения в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721553550',@link_self,'Увеличение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Увеличение вложений в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'721553650',@link_self,'Уменьшение вложений в прочие финансовые активы','ПлСчет_Каз_2011',0,'',0,'','Уменьшение вложений в прочие финансовые активы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730000000',@link_self,'ОБЯЗАТЕЛЬСТВА','ПлСчет_Каз_2011',0,'',0,'','ОБЯЗАТЕЛЬСТВА','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730100000',@link_self,'Расчеты с кредиторами по долговым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по долговым обязательствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730110000',@link_self,'Расчеты по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730111000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730111710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730111810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730112000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730112710',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730112810',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730113000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730113710',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730113810',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730114000',@link_self,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730114710',@link_self,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730114810',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730120000',@link_self,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730121000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730121710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730121810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730123000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730123720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730123820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730124000',@link_self,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730124720',@link_self,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730124820',@link_self,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730130000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730131000',@link_self,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730131710',@link_self,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730131810',@link_self,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730133000',@link_self,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730133720',@link_self,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730133820',@link_self,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730140000',@link_self,'Расчеты по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730142000',@link_self,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730142720',@link_self,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730142820',@link_self,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730143000',@link_self,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730143720',@link_self,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730143820',@link_self,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730144000',@link_self,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730144720',@link_self,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730144820',@link_self,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730200000',@link_self,'Расчеты по принятым обязательствам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по принятым обязательствам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730210000',@link_self,'Расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730211000',@link_self,'Расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730211730',@link_self,'Увеличение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730211830',@link_self,'Уменьшение кредиторской задолженности по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730212000',@link_self,'Расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730212730',@link_self,'Увеличение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730212830',@link_self,'Уменьшение кредиторской задолженности по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730213730',@link_self,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730213830',@link_self,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730220000',@link_self,'Расчеты по  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730221000',@link_self,'Расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730221730',@link_self,'Увеличение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730221830',@link_self,'Уменьшение кредиторской задолженности по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730222000',@link_self,'Расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730222730',@link_self,'Увеличение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730222830',@link_self,'Уменьшение кредиторской задолженности по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730223000',@link_self,'Расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730223730',@link_self,'Увеличение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730223830',@link_self,'Уменьшение кредиторской задолженности по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730224000',@link_self,'Расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730224730',@link_self,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730224830',@link_self,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730225730',@link_self,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730225830',@link_self,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730226000',@link_self,'Расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730226730',@link_self,'Увеличение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730226830',@link_self,'Уменьшение кредиторской задолженности по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730230000',@link_self,'Расчеты по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730231000',@link_self,'Расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730231730',@link_self,'Увеличение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730231830',@link_self,'Уменьшение кредиторской задолженности по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730232000',@link_self,'Расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730232730',@link_self,'Увеличение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730232830',@link_self,'Уменьшение кредиторской задолженности по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730233000',@link_self,'Расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730233730',@link_self,'Увеличение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730233830',@link_self,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730234000',@link_self,'Расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730234730',@link_self,'Увеличение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730234830',@link_self,'Уменьшение кредиторской задолженности по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730240000',@link_self,'Расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730241730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730241830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730242730',@link_self,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730242830',@link_self,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730250000',@link_self,'Расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730251730',@link_self,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730251830',@link_self,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730252730',@link_self,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730252830',@link_self,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730253000',@link_self,'Расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730253730',@link_self,'Увеличение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730253830',@link_self,'Уменьшение кредиторской задолженности по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730260000',@link_self,'Расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730261730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730261830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730262000',@link_self,'Расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730262730',@link_self,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730262830',@link_self,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730263730',@link_self,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730263830',@link_self,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730270000',@link_self,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730272730',@link_self,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730272830',@link_self,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730273730',@link_self,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730273830',@link_self,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730275000',@link_self,'Расчеты по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730275730',@link_self,'Увеличение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730275830',@link_self,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730290000',@link_self,'Расчеты по  прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по  прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730291000',@link_self,'Расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730291730',@link_self,'Увеличение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730291830',@link_self,'Уменьшение кредиторской задолженности по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730300000',@link_self,'Расчеты по платежам в бюджеты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам в бюджеты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730301000',@link_self,'Расчеты по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730301730',@link_self,'Увеличение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730301830',@link_self,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730302730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730302830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730303000',@link_self,'Расчеты по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730303730',@link_self,'Увеличение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730303830',@link_self,'Уменьшение кредиторской задолженности по налогу на прибыль организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730304000',@link_self,'Расчеты по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730304730',@link_self,'Увеличение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730304830',@link_self,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730305000',@link_self,'Расчеты по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Расчеты по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730305730',@link_self,'Увеличение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730305830',@link_self,'Уменьшение кредиторской задолженности по прочим платежам в бюджет','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730306730',@link_self,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730306830',@link_self,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730307730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730307830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730308730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730308830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730309730',@link_self,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730309830',@link_self,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730310730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730310830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730311730',@link_self,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730311830',@link_self,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730312000',@link_self,'Расчеты по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730312730',@link_self,'Увеличение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730312830',@link_self,'Уменьшение кредиторской задолженности по налогу на имущество организаций','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730313000',@link_self,'Расчеты по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730313730',@link_self,'Увеличение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730313830',@link_self,'Уменьшение кредиторской задолженности по земельному налогу','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730400000',@link_self,'Прочие расчеты с кредиторами','ПлСчет_Каз_2011',0,'',0,'','Прочие расчеты с кредиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730401000',@link_self,'Расчеты по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730401730',@link_self,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730401830',@link_self,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730402000',@link_self,'Расчеты с депонентами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730402730',@link_self,'Увеличение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730402830',@link_self,'Уменьшение кредиторской задолженности по расчетам с депонентами','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730403730',@link_self,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730403830',@link_self,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404000',@link_self,'Внутриведомственные расчеты','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404100',@link_self,'Внутриведомственные расчеты по доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404110',@link_self,'Внутриведомственные расчеты по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404120',@link_self,'Внутриведомственные расчеты по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404130',@link_self,'Внутриведомственные расчеты по доходам от оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404140',@link_self,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404160',@link_self,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404173',@link_self,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404180',@link_self,'Внутриведомственные расчеты по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404200',@link_self,'Внутриведомственные расчеты по расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404210',@link_self,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404211',@link_self,'Внутриведомственные расчеты по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404212',@link_self,'Внутриведомственные расчеты по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404213',@link_self,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404220',@link_self,'Внутриведомственные расчеты по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404221',@link_self,'Внутриведомственные расчеты по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404222',@link_self,'Внутриведомственные расчеты по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404223',@link_self,'Внутриведомственные расчеты по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404224',@link_self,'Внутриведомственные расчеты по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404225',@link_self,'Внутриведомственные расчеты по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404226',@link_self,'Внутриведомственные расчеты по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404230',@link_self,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404231',@link_self,'Внутриведомственные расчеты по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404232',@link_self,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404240',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404241',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404242',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404250',@link_self,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404251',@link_self,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404252',@link_self,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404253',@link_self,'Внутриведомственные расчеты по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404260',@link_self,'Внутриведомственные расчеты по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404261',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404262',@link_self,'Внутриведомственные расчеты по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404263',@link_self,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404273',@link_self,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404290',@link_self,'Внутриведомственные расчеты по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404300',@link_self,'Внутриведомственные расчеты по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404310',@link_self,'Внутриведомственные расчеты по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404320',@link_self,'Внутриведомственные расчеты по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404330',@link_self,'Внутриведомственные расчеты по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404340',@link_self,'Внутриведомственные расчеты по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404400',@link_self,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404410',@link_self,'Внутриведомственные расчеты по доходам от выбытия основных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404420',@link_self,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404430',@link_self,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404440',@link_self,'Внутриведомственные расчеты по доходам от выбытия материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404500',@link_self,'Внутриведомственные расчеты по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404510',@link_self,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404520',@link_self,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404530',@link_self,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404540',@link_self,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404550',@link_self,'Внутриведомственные расчеты по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404560',@link_self,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404600',@link_self,'Внутриведомственные расчеты по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404610',@link_self,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404620',@link_self,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404630',@link_self,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404640',@link_self,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404650',@link_self,'Внутриведомственные расчеты по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404660',@link_self,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404700',@link_self,'Внутриведомственные расчеты по увеличению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404710',@link_self,'Внутриведомственные расчеты по поступлениям внутренних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404720',@link_self,'Внутриведомственные расчеты по поступлениям внешних заимствований','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404730',@link_self,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404800',@link_self,'Внутриведомственные расчеты по уменьшению обязательств','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404810',@link_self,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404820',@link_self,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404830',@link_self,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','ПлСчет_Каз_2011',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405210',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405211',@link_self,'Расчеты по платежам из бюджета с финансовым органом по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405212',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405213',@link_self,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405220',@link_self,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405221',@link_self,'Расчеты по платежам из бюджета с финансовым органом по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405222',@link_self,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405223',@link_self,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405224',@link_self,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405225',@link_self,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405226',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405230',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405231',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405232',@link_self,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405240',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405241',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405242',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405250',@link_self,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405251',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405252',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405253',@link_self,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405260',@link_self,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405261',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405262',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405263',@link_self,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405270',@link_self,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405273',@link_self,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405290',@link_self,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405300',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405310',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405320',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405330',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405340',@link_self,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405500',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405510',@link_self,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405520',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405530',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405540',@link_self,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405550',@link_self,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405800',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405810',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405820',@link_self,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730406000',@link_self,'Расчеты с прочими кредиторами','ПлСчет_Каз_2011',0,'',0,'','Расчеты с прочими кредиторами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730406730',@link_self,'Увеличение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730406830',@link_self,'Уменьшение дебиторской задолженности прочих кредиторов','ПлСчет_Каз_2011',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730600000',@link_self,'Расчеты по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Расчеты по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730600730',@link_self,'Увеличение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730600830',@link_self,'Уменьшение кредиторской задолженности по выплате наличных денег','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730700000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730710000',@link_self,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712000',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712100',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712110',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712120',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712130',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712140',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712150',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712151',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712152',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712153',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712160',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712170',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712171',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712180',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712200',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712210',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712211',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712212',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712213',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712220',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712221',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712222',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712223',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712224',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712225',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712226',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712230',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712231',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712232',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712240',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712241',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712242',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712250',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712251',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712252',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712253',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712260',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712261',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712262',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712263',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712290',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712300',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712310',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712320',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712330',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712340',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712400',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712410',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712420',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712430',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712440',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712500',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712510',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712520',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712530',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712540',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712550',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712600',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712610',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712620',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712630',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712640',@link_self,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712650',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712700',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712710',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712720',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712800',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712810',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730712820',@link_self,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713000',@link_self,'Расчеты по операциям бюджетных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713100',@link_self,'Расчеты по операциям бюджетных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713120',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713130',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713140',@link_self,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713150',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713152',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713153',@link_self,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713170',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713171',@link_self,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713180',@link_self,'Расчеты по операциям бюджетных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713200',@link_self,'Расчеты по операциям бюджетных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713210',@link_self,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713211',@link_self,'Расчеты по операциям бюджетных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713212',@link_self,'Расчеты по операциям бюджетных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713213',@link_self,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713220',@link_self,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713221',@link_self,'Расчеты по операциям бюджетных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713222',@link_self,'Расчеты по операциям бюджетных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713223',@link_self,'Расчеты по операциям бюджетных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713224',@link_self,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713225',@link_self,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713226',@link_self,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713230',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713231',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713232',@link_self,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713240',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713241',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713242',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713250',@link_self,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713252',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713253',@link_self,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713260',@link_self,'Расчеты по операциям бюджетных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713262',@link_self,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713263',@link_self,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713290',@link_self,'Расчеты по операциям бюджетных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713300',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713310',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713320',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713330',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713340',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713400',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713410',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713420',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713430',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713440',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713500',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713510',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713520',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713530',@link_self,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713540',@link_self,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713550',@link_self,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713600',@link_self,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713610',@link_self,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713620',@link_self,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713630',@link_self,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713640',@link_self,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713650',@link_self,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713700',@link_self,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713710',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713720',@link_self,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713800',@link_self,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713810',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730713820',@link_self,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714000',@link_self,'Расчеты по операциям автономных учреждений','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714100',@link_self,'Расчеты по операциям автономных учреждений по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714120',@link_self,'Расчеты по операциям автономных учреждений по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714130',@link_self,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714140',@link_self,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714150',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714152',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714153',@link_self,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714170',@link_self,'Расчеты по операциям автономных учреждений по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714171',@link_self,'Расчеты по операциям автономных учреждений по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714180',@link_self,'Расчеты по операциям автономных учреждений по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714200',@link_self,'Расчеты по операциям автономных учреждений по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714210',@link_self,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714211',@link_self,'Расчеты по операциям автономных учреждений по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714212',@link_self,'Расчеты по операциям автономных учреждений по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714213',@link_self,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714220',@link_self,'Расчеты по операциям автономных учреждений по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714221',@link_self,'Расчеты по операциям автономных учреждений по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714222',@link_self,'Расчеты по операциям автономных учреждений по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714223',@link_self,'Расчеты по операциям автономных учреждений по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714224',@link_self,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714225',@link_self,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714226',@link_self,'Расчеты по операциям автономных учреждений по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714230',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714231',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714232',@link_self,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714240',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714241',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714242',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714250',@link_self,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714252',@link_self,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714253',@link_self,'Расчеты по операциям автономных учреждений по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714260',@link_self,'Расчеты по операциям автономных учреждений по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714262',@link_self,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714263',@link_self,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714290',@link_self,'Расчеты по операциям автономных учреждений по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714300',@link_self,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714310',@link_self,'Расчеты по операциям автономных учреждений по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714320',@link_self,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714330',@link_self,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714340',@link_self,'Расчеты по операциям автономных учреждений по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714400',@link_self,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714410',@link_self,'Расчеты по операциям автономных учреждений по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714420',@link_self,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714430',@link_self,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714440',@link_self,'Расчеты по операциям автономных учреждений по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714500',@link_self,'Расчеты по операциям автономных учреждений по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714510',@link_self,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714520',@link_self,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714530',@link_self,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714540',@link_self,'Расчеты по операциям автономных учреждений по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714550',@link_self,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714600',@link_self,'Расчеты по операциям автономных учреждений по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714610',@link_self,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714620',@link_self,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714630',@link_self,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714640',@link_self,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714650',@link_self,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714700',@link_self,'Расчеты по операциям автономных учреждений по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714710',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714720',@link_self,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714800',@link_self,'Расчеты по операциям автономных учреждений по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714810',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730714820',@link_self,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715000',@link_self,'Расчеты по операциям иных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715100',@link_self,'Расчеты по операциям иных организаций по доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715120',@link_self,'Расчеты по операциям иных организаций по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715130',@link_self,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715140',@link_self,'Расчеты по операциям иных организаций по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715150',@link_self,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715152',@link_self,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715153',@link_self,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715170',@link_self,'Расчеты по операциям иных организаций по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715171',@link_self,'Расчеты по операциям иных организаций по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715180',@link_self,'Расчеты по операциям иных организаций по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715200',@link_self,'Расчеты по операциям иных организаций по расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715210',@link_self,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715211',@link_self,'Расчеты по операциям иных организаций по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715212',@link_self,'Расчеты по операциям иных организаций по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715213',@link_self,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715220',@link_self,'Расчеты по операциям иных организаций по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715221',@link_self,'Расчеты по операциям иных организаций по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715222',@link_self,'Расчеты по операциям иных организаций по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715223',@link_self,'Расчеты по операциям иных организаций по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715224',@link_self,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715225',@link_self,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715226',@link_self,'Расчеты по операциям иных организаций по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715230',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715231',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715232',@link_self,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715240',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715241',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715242',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715250',@link_self,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715252',@link_self,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715253',@link_self,'Расчеты по операциям иных организаций по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715260',@link_self,'Расчеты по операциям иных организаций по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715262',@link_self,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715263',@link_self,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715290',@link_self,'Расчеты по операциям иных организаций по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715300',@link_self,'Расчеты по операциям иных организаций по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715310',@link_self,'Расчеты по операциям иных организаций по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715320',@link_self,'Расчеты по операциям иных организаций по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715330',@link_self,'Расчеты по операциям иных организаций по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715340',@link_self,'Расчеты по операциям иных организаций по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715400',@link_self,'Расчеты по операциям иных организаций по выбытию нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715410',@link_self,'Расчеты по операциям иных организаций по выбытию основных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715420',@link_self,'Расчеты по операциям иных организаций по выбытию нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715430',@link_self,'Расчеты по операциям иных организаций по выбытию непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715440',@link_self,'Расчеты по операциям иных организаций по выбытию материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715500',@link_self,'Расчеты по операциям иных организаций по поступлению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715510',@link_self,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715520',@link_self,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715530',@link_self,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715540',@link_self,'Расчеты по операциям иных организаций по предоставлению заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715550',@link_self,'Расчеты по операциям иных организаций по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715600',@link_self,'Расчеты по операциям иных организаций по выбытию финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715610',@link_self,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715620',@link_self,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715630',@link_self,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715640',@link_self,'Расчеты по операциям иных организаций по возврату заимствований','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715650',@link_self,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715700',@link_self,'Расчеты по операциям иных организаций по долговым заимствованиям','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715710',@link_self,'Расчеты по операциям иных организаций по заимствованиям в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715720',@link_self,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715800',@link_self,'Расчеты по операциям иных организаций по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715810',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730715820',@link_self,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','ПлСчет_Каз_2011',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730800000',@link_self,'Внутренние расчеты по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730800730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730800830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730900000',@link_self,'Внутренние расчеты по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Внутренние расчеты по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730900730',@link_self,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730900830',@link_self,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','ПлСчет_Каз_2011',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740000000',@link_self,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ','ПлСчет_Каз_2011',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740100000',@link_self,'Финансовый результат хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110000',@link_self,'Доходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Доходы текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110100',@link_self,'Доходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Доходы хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110110',@link_self,'Налоговые доходы','ПлСчет_Каз_2011',0,'',0,'','Налоговые доходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110120',@link_self,'Доходы от собственности','ПлСчет_Каз_2011',0,'',0,'','Доходы от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110130',@link_self,'Доходы от  оказания платных услуг','ПлСчет_Каз_2011',0,'',0,'','Доходы от  оказания платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110140',@link_self,'Доходы от сумм принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Доходы от сумм принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110150',@link_self,'Доходы от безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110153',@link_self,'Доходы от поступления от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Доходы от поступления от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110170',@link_self,'Доходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110171',@link_self,'Доходы от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Доходы от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110172',@link_self,'Доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Доходы от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110173',@link_self,'Чрезвычайные доходы от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные доходы от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110180',@link_self,'Прочие доходы','ПлСчет_Каз_2011',0,'',0,'','Прочие доходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120000',@link_self,'Расходы текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Расходы текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120200',@link_self,'Расходы хозяйствующего субъекта','ПлСчет_Каз_2011',0,'',0,'','Расходы хозяйствующего субъекта','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120210',@link_self,'Расходы по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120211',@link_self,'Расходы по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Расходы по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120212',@link_self,'Расходы по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Расходы по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120213',@link_self,'Расходы на начисления на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Расходы на начисления на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120220',@link_self,'Расходы на оплату работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Расходы на оплату работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120221',@link_self,'Расходы на услуги связи','ПлСчет_Каз_2011',0,'',0,'','Расходы на услуги связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120222',@link_self,'Расходы на транспортные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на транспортные услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120223',@link_self,'Расходы на коммунальные услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на коммунальные услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120224',@link_self,'Расходы на арендную плату за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Расходы на арендную плату за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120225',@link_self,'Расходы на работы, услуги по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Расходы на работы, услуги по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120226',@link_self,'Расходы на прочие работы, услуги','ПлСчет_Каз_2011',0,'',0,'','Расходы на прочие работы, услуги','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120230',@link_self,'Расходы на обслуживание государственного (муниципального)  долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120231',@link_self,'Расходы на обслуживание внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120232',@link_self,'Расходы на обслуживание внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Расходы на обслуживание внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120240',@link_self,'Расходы на безвозмездные перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120250',@link_self,'Расходы на безвозмездные перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Расходы на безвозмездные перечисления бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120253',@link_self,'Расходы на перечисления международным организациям','ПлСчет_Каз_2011',0,'',0,'','Расходы на перечисления международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120260',@link_self,'Расходы на социальное обеспечение','ПлСчет_Каз_2011',0,'',0,'','Расходы на социальное обеспечение','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120262',@link_self,'Расходы на пособия по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Расходы на пособия по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120270',@link_self,'Расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Расходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120272',@link_self,'Расходование материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Расходование материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120273',@link_self,'Чрезвычайные расходы по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Чрезвычайные расходы по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120290',@link_self,'Прочие расходы','ПлСчет_Каз_2011',0,'',0,'','Прочие расходы','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740130000',@link_self,'Финансовый результат прошлых отчетных периодов','ПлСчет_Каз_2011',0,'',0,'','Финансовый результат прошлых отчетных периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740140000',@link_self,'Доходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Доходы будущих периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740150000',@link_self,'Расходы будущих периодов','ПлСчет_Каз_2011',0,'',0,'','Расходы будущих периодов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740200000',@link_self,'Результат по кассовым операциям бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовым операциям бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210000',@link_self,'Результат по кассовому исполнению бюджета по поступлениям в бюджет','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210100',@link_self,'Поступления в бюджет по доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210110',@link_self,'Поступления в бюджет по налоговым доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по налоговым доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210120',@link_self,'Поступления в бюджет по доходам от собственности','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от собственности','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210150',@link_self,'Поступления в бюджет безвозмездных поступлений от бюджетов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210153',@link_self,'Поступления в бюджет от международных финансовых организаций','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от международных финансовых организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210170',@link_self,'Поступления в бюджет по доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по доходам от переоценки активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','ПлСчет_Каз_2011',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210180',@link_self,'Поступления в бюджет по прочим доходам','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет по прочим доходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210400',@link_self,'Поступления в бюджет от реализации нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210410',@link_self,'Поступления в бюджет от реализации основных средств','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210440',@link_self,'Поступления в бюджет от реализации материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210600',@link_self,'Поступления в бюджет от выбытия финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210700',@link_self,'Поступления в бюджет от заимствований','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220000',@link_self,'Результат по кассовому исполнению бюджета по выбытиям из бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220200',@link_self,'Выбытия средств бюджета по расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220210',@link_self,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220211',@link_self,'Выбытия средств бюджета по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220212',@link_self,'Выбытия средств бюджета по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220220',@link_self,'Выбытия средств бюджета по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220221',@link_self,'Выбытия средств бюджета по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220222',@link_self,'Выбытия средств бюджета по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220230',@link_self,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220240',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220250',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220260',@link_self,'Выбытия средств бюджета по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220270',@link_self,'Выбытия средств бюджета по расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220290',@link_self,'Выбытия средств бюджета по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220300',@link_self,'Выбытия средств бюджета по поступлению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220500',@link_self,'Выбытия средств бюджета по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220800',@link_self,'Выбытия средств бюджета по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740230000',@link_self,'Результат прошлых отчетных периодов по кассовому исполнению бюджета','ПлСчет_Каз_2011',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750000000',@link_self,'САНКЦИОНИРОВАНИЕ РАСХОДОВ','ПлСчет_Каз_2011',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750100000',@link_self,'Лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101000',@link_self,'Доведенные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101200',@link_self,'Доведенные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101210',@link_self,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101211',@link_self,'Доведенные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101212',@link_self,'Доведенные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101213',@link_self,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101220',@link_self,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101221',@link_self,'Доведенные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101222',@link_self,'Доведенные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101223',@link_self,'Доведенные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101224',@link_self,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101225',@link_self,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101226',@link_self,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101230',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101231',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101232',@link_self,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101240',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101241',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101242',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101250',@link_self,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101251',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101252',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101253',@link_self,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101260',@link_self,'Доведенные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101261',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101262',@link_self,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101263',@link_self,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101290',@link_self,'Доведенные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101300',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101310',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101320',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101330',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101340',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101500',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101530',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750101550',@link_self,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102000',@link_self,'Лимиты бюджетных обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102200',@link_self,'Лимиты бюджетных обязательств по расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102210',@link_self,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102211',@link_self,'Лимиты бюджетных обязательств по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102212',@link_self,'Лимиты бюджетных обязательств по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102213',@link_self,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102220',@link_self,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102221',@link_self,'Лимиты бюджетных обязательств по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102222',@link_self,'Лимиты бюджетных обязательств по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102223',@link_self,'Лимиты бюджетных обязательств по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102224',@link_self,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102225',@link_self,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102226',@link_self,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102230',@link_self,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102231',@link_self,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102232',@link_self,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102240',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102241',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102242',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102250',@link_self,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102251',@link_self,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102252',@link_self,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102253',@link_self,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102260',@link_self,'Лимиты бюджетных обязательств по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102261',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102262',@link_self,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102263',@link_self,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102290',@link_self,'Лимиты бюджетных обязательств по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102300',@link_self,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102310',@link_self,'Лимиты бюджетных обязательств по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102320',@link_self,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102330',@link_self,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102340',@link_self,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102500',@link_self,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750102530',@link_self,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103000',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103200',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103210',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103211',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103212',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103213',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103220',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103221',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103222',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103223',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103224',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103225',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103226',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103230',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103231',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103232',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103240',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103241',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103242',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103250',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103251',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103252',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103253',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103260',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103261',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103262',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103263',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103290',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103300',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103310',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103320',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103330',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103340',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103500',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750103530',@link_self,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104000',@link_self,'Переданные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104200',@link_self,'Переданные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104210',@link_self,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104211',@link_self,'Переданные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104212',@link_self,'Переданные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104213',@link_self,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104220',@link_self,'Переданные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104221',@link_self,'Переданные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104222',@link_self,'Переданные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104223',@link_self,'Переданные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104224',@link_self,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104225',@link_self,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104226',@link_self,'Переданные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104230',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104231',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104232',@link_self,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104240',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104241',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104242',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104250',@link_self,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104251',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104252',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104253',@link_self,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104260',@link_self,'Переданные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104261',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104262',@link_self,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104263',@link_self,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104290',@link_self,'Переданные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104300',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104310',@link_self,'Переданные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104320',@link_self,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104330',@link_self,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104340',@link_self,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104500',@link_self,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750104530',@link_self,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105000',@link_self,'Полученные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105200',@link_self,'Полученные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105210',@link_self,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105211',@link_self,'Полученные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105212',@link_self,'Полученные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105213',@link_self,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105220',@link_self,'Полученные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105221',@link_self,'Полученные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105222',@link_self,'Полученные лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105223',@link_self,'Полученные лимиты бюджетных обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105224',@link_self,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105225',@link_self,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105226',@link_self,'Полученные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105230',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105231',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105232',@link_self,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105240',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105241',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105242',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105250',@link_self,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105251',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105252',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105253',@link_self,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105260',@link_self,'Полученные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105261',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105262',@link_self,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105263',@link_self,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105290',@link_self,'Полученные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105300',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105310',@link_self,'Полученные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105320',@link_self,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105330',@link_self,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105340',@link_self,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105500',@link_self,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750105530',@link_self,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106000',@link_self,'Лимиты бюджетных обязательств в пути','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106200',@link_self,'Лимиты бюджетных обязательств в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106210',@link_self,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106211',@link_self,'Лимиты бюджетных обязательств в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106212',@link_self,'Лимиты бюджетных обязательств в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106213',@link_self,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106220',@link_self,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106221',@link_self,'Лимиты бюджетных обязательств в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106222',@link_self,'Лимиты бюджетных обязательств в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106223',@link_self,'Лимиты бюджетных обязательств в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106224',@link_self,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106225',@link_self,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106226',@link_self,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106230',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106231',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106232',@link_self,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106240',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106241',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106242',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106250',@link_self,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106251',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106252',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106253',@link_self,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106260',@link_self,'Лимиты бюджетных обязательств в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106261',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106262',@link_self,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106263',@link_self,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106290',@link_self,'Лимиты бюджетных обязательств в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106300',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106310',@link_self,'Лимиты бюджетных обязательств в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106320',@link_self,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106330',@link_self,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106340',@link_self,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106500',@link_self,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750106530',@link_self,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109000',@link_self,'Утвержденные лимиты бюджетных обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109200',@link_self,'Утвержденные лимиты бюджетных обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109210',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109211',@link_self,'Утвержденные лимиты бюджетных обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109212',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109213',@link_self,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109220',@link_self,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109221',@link_self,'Утвержденные лимиты бюджетных обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109222',@link_self,'Утверждены лимиты бюджетных обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109223',@link_self,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109224',@link_self,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109225',@link_self,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109226',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109230',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109231',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109232',@link_self,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109240',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109241',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109242',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109250',@link_self,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109251',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109252',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109253',@link_self,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109260',@link_self,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109261',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109262',@link_self,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109263',@link_self,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109290',@link_self,'Утвержденные лимиты бюджетных обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109300',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109310',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109320',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109330',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109340',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109500',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750109530',@link_self,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750110000',@link_self,'Лимиты бюджетных обязательств текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750120000',@link_self,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750130000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750140000',@link_self,'Лимиты бюджетных обязательств  второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750200000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201000',@link_self,'Принятые обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201200',@link_self,'Принятые обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201210',@link_self,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201211',@link_self,'Принятые обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201212',@link_self,'Принятые обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201213',@link_self,'Принятые обязательства по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201220',@link_self,'Принятые обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201221',@link_self,'Принятые обязательства  по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201222',@link_self,'Принятые обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201223',@link_self,'Принятые обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201224',@link_self,'Принятые обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201225',@link_self,'Принятые обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201226',@link_self,'Принятые обязательства по прочим  работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим  работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201230',@link_self,'Принятые обязательства по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201231',@link_self,'Принятые обязательства по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201232',@link_self,'Принятые обязательства по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201240',@link_self,'Принятые обязательства по безвозмездным перечисления организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201241',@link_self,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201242',@link_self,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201250',@link_self,'Принятые обязательства по безвозмездным перечисления бюджетам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201251',@link_self,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201252',@link_self,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201253',@link_self,'Принятые обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201260',@link_self,'Принятые бюджетные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201261',@link_self,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201262',@link_self,'Принятые обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201263',@link_self,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201290',@link_self,'Принятые обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201300',@link_self,'Принятые обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201310',@link_self,'Принятые обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201320',@link_self,'Принятые обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201330',@link_self,'Принятые обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201340',@link_self,'Принятые обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201500',@link_self,'Принятые обязательства по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201520',@link_self,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201530',@link_self,'Принятые обязательства по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201540',@link_self,'Принятые обязательства по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201550',@link_self,'Принятые обязательства по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201800',@link_self,'Принятые обязательства по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201810',@link_self,'Принятые обязательства по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750201820',@link_self,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202000',@link_self,'Принятые денежные обязательства','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202200',@link_self,'Принятые денежные обязательства по расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202210',@link_self,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202211',@link_self,'Принятые денежные обязательства по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202212',@link_self,'Принятые денежные бюджетные обязательства по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202213',@link_self,'Принятые денежные обязательства по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202220',@link_self,'Принятые денежные обязательства по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202221',@link_self,'Принятые денежные обязательства по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202222',@link_self,'Принятые денежные обязательства по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202223',@link_self,'Принятые денежные обязательства по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202224',@link_self,'Принятые денежные обязательства по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202225',@link_self,'Принятые денежные обязательства по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202226',@link_self,'Принятые денежные обязательства по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202240',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202241',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202242',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202250',@link_self,'Принятые денежные обязательства по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202253',@link_self,'Принятые денежные обязательства по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202260',@link_self,'Принятые денежные обязательства по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202262',@link_self,'Принятые денежные обязательства по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202263',@link_self,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202290',@link_self,'Принятые денежные обязательства по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202300',@link_self,'Принятые денежные обязательства по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202310',@link_self,'Принятые денежные обязательства по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202320',@link_self,'Принятые денежные обязательства по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202330',@link_self,'Принятые денежные обязательства по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750202340',@link_self,'Принятые денежные обязательства по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750210000',@link_self,'Принятые обязательства  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства  на текущий финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750220000',@link_self,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750230000',@link_self,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750240000',@link_self,'Принятые обязательства на второй год, следующий за очередным','ПлСчет_Каз_2011',0,'',0,'','Принятые обязательства на второй год, следующий за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750300000',@link_self,'Бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301000',@link_self,'Доведенные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301200',@link_self,'Доведенные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301210',@link_self,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301211',@link_self,'Доведенные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301212',@link_self,'Доведенные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301213',@link_self,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301220',@link_self,'Доведенные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301221',@link_self,'Доведенные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301222',@link_self,'Доведенные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301223',@link_self,'Доведенные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301224',@link_self,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301225',@link_self,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301226',@link_self,'Доведенные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301230',@link_self,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301231',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301232',@link_self,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301240',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301241',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301242',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301250',@link_self,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301251',@link_self,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301252',@link_self,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301253',@link_self,'Доведенные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301260',@link_self,'Доведенные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301261',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301262',@link_self,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301263',@link_self,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301290',@link_self,'Доведенные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301300',@link_self,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301310',@link_self,'Доведенные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301320',@link_self,'Доведенные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301330',@link_self,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301340',@link_self,'Доведенные бюджетные ассигнования на по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301500',@link_self,'Доведенные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301520',@link_self,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301530',@link_self,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301540',@link_self,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301550',@link_self,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301800',@link_self,'Доведенные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301810',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750301820',@link_self,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302000',@link_self,'Бюджетные ассигнования к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302200',@link_self,'Бюджетные ассигнования по  расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по  расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302210',@link_self,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302211',@link_self,'Бюджетные ассигнования по заработной плате к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302212',@link_self,'Бюджетные ассигнования по прочим выплатам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302213',@link_self,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302220',@link_self,'Бюджетные ассигнования по оплате работ,  услуг к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302221',@link_self,'Бюджетные ассигнования по услугам связи к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302222',@link_self,'Бюджетные ассигнования по транспортным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302223',@link_self,'Бюджетные ассигнования по коммунальным услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302224',@link_self,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302225',@link_self,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302226',@link_self,'Бюджетные ассигнования по прочим работам, услугам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302230',@link_self,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302231',@link_self,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302232',@link_self,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302240',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302241',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302242',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302250',@link_self,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302251',@link_self,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302252',@link_self,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302253',@link_self,'Бюджетные ассигнования по перечислениям международным организациям к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302260',@link_self,'Бюджетные ассигнования по социальному обеспечению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302261',@link_self,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302262',@link_self,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302263',@link_self,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302290',@link_self,'Бюджетные ассигнования по прочим расходам к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302300',@link_self,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302310',@link_self,'Бюджетные ассигнования по приобретению основных средств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302320',@link_self,'Бюджетные ассигнования по приобретению нематериальных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302330',@link_self,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302340',@link_self,'Бюджетные ассигнования по приобретению материальных запасов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302500',@link_self,'Бюджетные ассигнования по приобретению финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302520',@link_self,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302530',@link_self,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302540',@link_self,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302550',@link_self,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302800',@link_self,'Бюджетные ассигнования по погашению долговых обязательств к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302810',@link_self,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750302820',@link_self,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303000',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303200',@link_self,'Бюджетные ассигнования получателей бюджетных средств по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303220',@link_self,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303221',@link_self,'Бюджетные ассигнования получателей бюджетных средств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303226',@link_self,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303260',@link_self,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303261',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303262',@link_self,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303300',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303310',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303500',@link_self,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303520',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303540',@link_self,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303550',@link_self,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303800',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303810',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750303820',@link_self,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304000',@link_self,'Переданные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304200',@link_self,'Переданные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304210',@link_self,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304211',@link_self,'Переданные бюджетные ассигнования  по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304212',@link_self,'Переданные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304213',@link_self,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304220',@link_self,'Переданные бюджетные ассигнования по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304221',@link_self,'Переданные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304222',@link_self,'Переданные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304223',@link_self,'Переданные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304224',@link_self,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304225',@link_self,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304226',@link_self,'Переданные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304230',@link_self,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304231',@link_self,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304232',@link_self,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304240',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304241',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304242',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304250',@link_self,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304251',@link_self,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304252',@link_self,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304253',@link_self,'Переданные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304260',@link_self,'Переданные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304261',@link_self,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304262',@link_self,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304263',@link_self,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304290',@link_self,'Переданные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304300',@link_self,'Переданные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304310',@link_self,'Переданные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304320',@link_self,'Переданные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304330',@link_self,'Переданные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304340',@link_self,'Переданные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304500',@link_self,'Переданные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304520',@link_self,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304530',@link_self,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304540',@link_self,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304550',@link_self,'Переданные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304800',@link_self,'Переданные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304810',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750304820',@link_self,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305000',@link_self,'Полученные бюджетные ассигнования','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305200',@link_self,'Полученные бюджетные ассигнования по расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305210',@link_self,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305211',@link_self,'Полученные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305212',@link_self,'Полученные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305213',@link_self,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305220',@link_self,'Полученные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305221',@link_self,'Полученные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305222',@link_self,'Полученные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305223',@link_self,'Полученные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305224',@link_self,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305225',@link_self,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305226',@link_self,'Полученные бюджетные ассигнования по прочим работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305230',@link_self,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305231',@link_self,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305232',@link_self,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305240',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305241',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305242',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305250',@link_self,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305251',@link_self,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305252',@link_self,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305253',@link_self,'Полученные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305260',@link_self,'Полученные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305261',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305262',@link_self,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305263',@link_self,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305290',@link_self,'Полученные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305300',@link_self,'Полученные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305310',@link_self,'Полученные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305320',@link_self,'Полученные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305330',@link_self,'Полученные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305340',@link_self,'Полученные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305500',@link_self,'Полученные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305520',@link_self,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305530',@link_self,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305540',@link_self,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305550',@link_self,'Полученные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305800',@link_self,'Полученные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305810',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750305820',@link_self,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306000',@link_self,'Бюджетные ассигнования в пути','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306200',@link_self,'Бюджетные ассигнования в пути по расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306210',@link_self,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306211',@link_self,'Бюджетные ассигнования в пути по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306212',@link_self,'Бюджетные ассигнования в пути по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306213',@link_self,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306220',@link_self,'Бюджетные ассигнования в пути по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306221',@link_self,'Бюджетные ассигнования в пути по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306222',@link_self,'Бюджетные ассигнования в пути по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306223',@link_self,'Бюджетные ассигнования в пути по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306224',@link_self,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306225',@link_self,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306226',@link_self,'Бюджетные ассигнования в пути по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306230',@link_self,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306231',@link_self,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306232',@link_self,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306240',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306241',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306242',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306250',@link_self,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306251',@link_self,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306252',@link_self,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306253',@link_self,'Бюджетные ассигнования в пути по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306260',@link_self,'Бюджетные ассигнования в пути по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306261',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306262',@link_self,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306263',@link_self,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306290',@link_self,'Бюджетные ассигнования в пути по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306300',@link_self,'Бюджетные ассигнования в пути по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306310',@link_self,'Бюджетные ассигнования в пути по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306320',@link_self,'Бюджетные ассигнования в пути по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306330',@link_self,'Бюджетные ассигнования в пути по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306340',@link_self,'Бюджетные ассигнования в пути по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306500',@link_self,'Бюджетные ассигнования в пути по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306520',@link_self,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306530',@link_self,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306540',@link_self,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306550',@link_self,'Бюджетные ассигнования в пути по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306800',@link_self,'Бюджетные ассигнования в пути по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306810',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750306820',@link_self,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309000',@link_self,'Утвержденные бюджетные  ассигнования','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные  ассигнования','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309200',@link_self,'Утвержденные бюджетные ассигнования по  расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309210',@link_self,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309211',@link_self,'Утвержденные бюджетные ассигнования по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309212',@link_self,'Утвержденные бюджетные ассигнования по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309213',@link_self,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309220',@link_self,'Утвержденные бюджетные ассигнования по оплате работ,  услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309221',@link_self,'Утвержденные бюджетные ассигнования по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309222',@link_self,'Утвержденные бюджетные ассигнования по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309223',@link_self,'Утвержденные бюджетные ассигнования по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309224',@link_self,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309225',@link_self,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309226',@link_self,'Утвержденные бюджетные ассигнования по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309230',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309231',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309232',@link_self,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309240',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309241',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309242',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309250',@link_self,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309251',@link_self,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309252',@link_self,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309253',@link_self,'Утвержденные бюджетные ассигнования по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309260',@link_self,'Утвержденные бюджетные ассигнования по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309261',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309262',@link_self,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309263',@link_self,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309290',@link_self,'Утвержденные бюджетные ассигнования по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309300',@link_self,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309310',@link_self,'Утвержденные бюджетные ассигнования по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309320',@link_self,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309330',@link_self,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309340',@link_self,'Утвержденные бюджетные ассигнования по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309500',@link_self,'Утвержденные бюджетные ассигнования по приобретению финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309520',@link_self,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309530',@link_self,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309540',@link_self,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309550',@link_self,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309800',@link_self,'Утвержденные бюджетные ассигнования по погашению долговых обязательств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309810',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750309820',@link_self,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','ПлСчет_Каз_2011',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750310000',@link_self,'Бюджетные ассигнования текущего финансового года','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования текущего финансового года','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750320000',@link_self,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750330000',@link_self,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750340000',@link_self,'Бюджетные ассигнования второго года, следующего за очередным','ПлСчет_Каз_2011',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400000',@link_self,'Утвержденные сметные (плановые) назначения по выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400200',@link_self,'Утвержденные сметные (плановые) назначения по расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400210',@link_self,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400211',@link_self,'Утвержденные сметные (плановые) назначения по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400212',@link_self,'Утвержденные сметные (плановые) назначения по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400213',@link_self,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400220',@link_self,'Утвержденные сметные (плановые) назначения по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400221',@link_self,'Утвержденные сметные (плановые) назначения по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400222',@link_self,'Утвержденные сметные (плановые) назначения по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400223',@link_self,'Утвержденные сметные (плановые) назначения по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400224',@link_self,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400225',@link_self,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400226',@link_self,'Утвержденные сметные (плановые) назначения по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400240',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400241',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400242',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400250',@link_self,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400252',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400253',@link_self,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400260',@link_self,'Утвержденные сметные (плановые) назначения по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400262',@link_self,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400263',@link_self,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400290',@link_self,'Утвержденные сметные (плановые) назначения по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400300',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400310',@link_self,'Утвержденные сметные (плановые) назначения по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400320',@link_self,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400330',@link_self,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750400340',@link_self,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750410000',@link_self,'Сметные (плановые) назначения  на текущий финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750420000',@link_self,'Сметные (плановые) назначения на очередной финансовый год','ПлСчет_Каз_2011',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600000',@link_self,'Право на принятие обязательств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600200',@link_self,'Право на принятие обязательств по расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600210',@link_self,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600211',@link_self,'Право на принятие обязательств по заработной плате','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по заработной плате','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600212',@link_self,'Право на принятие обязательств по прочим выплатам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим выплатам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600213',@link_self,'Право на принятие обязательств по начислениям на выплаты по оплате труда','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600220',@link_self,'Право на принятие обязательств по оплате работ, услуг','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по оплате работ, услуг','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600221',@link_self,'Право на принятие обязательств по услугам связи','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по услугам связи','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600222',@link_self,'Право на принятие обязательств по транспортным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по транспортным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600223',@link_self,'Право на принятие обязательств по коммунальным услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по коммунальным услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600224',@link_self,'Право на принятие обязательств по арендной плате за пользование имуществом','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600225',@link_self,'Право на принятие обязательств по работам, услугам по содержанию имущества','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600226',@link_self,'Право на принятие обязательств по прочим работам, услугам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим работам, услугам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600240',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600241',@link_self,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600242',@link_self,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600250',@link_self,'Право на принятие обязательств по безвозмездным перечислениям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600252',@link_self,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600253',@link_self,'Право на принятие обязательств по  перечислениям международным организациям','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600260',@link_self,'Право на принятие обязательств по социальному обеспечению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по социальному обеспечению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600262',@link_self,'Право на принятие обязательств по пособиям по социальной помощи населению','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600263',@link_self,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600290',@link_self,'Право на принятие обязательств по прочим расходам','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по прочим расходам','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600300',@link_self,'Право на принятие обязательств по приобретению нефинансовых активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600310',@link_self,'Право на принятие обязательств по приобретению основных средств','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению основных средств','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600320',@link_self,'Право на принятие обязательств по приобретению нематериальных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600330',@link_self,'Право на принятие обязательств по приобретению непроизведенных активов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'750600340',@link_self,'Право на принятие обязательств по приобретению материальных запасов','ПлСчет_Каз_2011',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов','19000101','19000101'
GO

GO


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
delete report_control_protokol
delete report_kbk where code_form= 'ПлСчет_Каз_2011'
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 '010000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010120000',0,'ПлСчет_Каз_2011',1,'Основные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010121000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010121310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010121410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010122000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010122310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010122410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010123000',0,'ПлСчет_Каз_2011',1,'Сооружения - особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010123310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010123410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010124000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010124310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010124410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования– особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010125000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010125310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010125410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010126000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010126310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010126410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010127310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010127410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010128000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010128310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010128410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', NULL,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 '010310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,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 '010546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,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 '010981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '010991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,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 '020315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', NULL,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 '020581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,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 '020733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '020982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,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 '021002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '021553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,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 '030114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,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 '030272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,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 '030404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,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 '030712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,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 '030713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,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 '030715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '030900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', NULL,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 '040200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '040230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,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 '050101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,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 '050104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,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 '050109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', NULL,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 '050301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,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 '050304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,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 '050306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,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 '050600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '10714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,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 '110240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,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 '110544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,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 '110981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '110991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,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 '120314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,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 '120575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,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 '120731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,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 '121002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,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 '130114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,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 '130270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,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 '130404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,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 '130712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,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 '130713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,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 '130715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,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 '140140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,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 '150101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,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 '150104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,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 '150109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,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 '150300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,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 '150304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,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 '150306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', NULL,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 '150600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210120000',0,'ПлСчет_Каз_2011',1,'Основные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210121000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210121310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210121410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210122000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210122310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210122410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210123000',0,'ПлСчет_Каз_2011',1,'Сооружения - особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210123310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210123410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210124000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210124310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210124410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования– особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210125000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210125310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210125410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210126000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210126310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210126410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210127310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210127410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210128000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – особо ценное движимое имущество учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210128310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210128410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – особо ценного движимого имущества учреждения',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,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 '210143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,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 '210532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,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 '210961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '210991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,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 '220223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,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 '220552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,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 '220700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,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 '220982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '220982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', NULL,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 '221534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,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 '230241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,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 '230404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,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 '230406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,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 '230713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,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 '230714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', NULL,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 '240120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,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 '250100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,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 '250103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,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 '250106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,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 '250202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,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 '250302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,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 '250305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,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 '250400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '30714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,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 '310142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,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 '310532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,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 '310961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '310991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,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 '320223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,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 '320551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,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 '320691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', NULL,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 '320981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '320982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,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 '321533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '321553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,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 '330241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,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 '330404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,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 '330405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,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 '330713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,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 '330714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '330900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', NULL,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 '340120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,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 '340230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,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 '350103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,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 '350106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,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 '350202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,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 '350302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,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 '350305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,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 '350400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,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 '410142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,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 '410532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,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 '410960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '410991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,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 '420222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,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 '420551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,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 '420690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,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 '420980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '420982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Расходы на оплату работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Расходы на транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,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 '421533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '421553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Доходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,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 '430234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,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 '430404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,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 '430405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,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 '430713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,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 '430714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Вложения в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение вложений в управляющие компании', NULL,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 '440120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Расчеты по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,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 '440220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,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 '450103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,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 '450106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,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 '450202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,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 '450302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,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 '450305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Непроизведенные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,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 '450400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Основные средства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Право на принятие обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Право на принятие обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', NULL,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 '510141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Бюджетные ассигнования текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные  ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Бюджетные ассигнования в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Бюджетные ассигнования в пути по расходам', NULL,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 '510530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', NULL,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 '510856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Бюджетные ассигнования к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '510991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Принятые денежные обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые обязательства  на текущий финансовый год', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Бюджетные ассигнования', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', NULL,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 '520221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Принятые обязательства по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Принятые денежные обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые денежные обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Принятые денежные обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Принятые денежные обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Принятые денежные обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Принятые обязательства по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Принятые обязательства по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Принятые обязательства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Принятые обязательства по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Принятые обязательства по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Принятые обязательства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Принятые обязательства по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Принятые обязательства по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Принятые обязательства по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,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 '520541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Лимиты бюджетных обязательств в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', NULL,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 '520663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Выбытия средств бюджета по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', NULL,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 '520974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '520982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Доведенные лимиты бюджетных обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Поступления в бюджет от реализации материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Поступления в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Выбытия средств бюджета по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Выбытия средств бюджета по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Выбытия средств бюджета по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Выбытия средств бюджета по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Результат по кассовым операциям бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Поступления в бюджет по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Поступления в бюджет по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Поступления в бюджет по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Поступления в бюджет по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Поступления в бюджет по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Поступления в бюджет от реализации основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Расходы на обслуживание внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Расходы на обслуживание внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Расходы на безвозмездные перечисления организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Расходы на перечисления международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Расходы на социальное обеспечение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Расходы на пособия по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Расходование материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Чрезвычайные расходы по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Прочие расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Финансовый результат прошлых отчетных периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Доходы будущих периодов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Доходы от поступления от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Доходы по операциям с активами', NULL,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 '521532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Доходы от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Чрезвычайные доходы от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Прочие доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Расходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Расходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Расходы по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Расходы по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Расходы на начисления на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Расходы на оплату работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Расходы на услуги связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Расходы на транспортные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Расходы на коммунальные услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Расходы на арендную плату за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Расходы на работы, услуги по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Расходы на прочие работы, услуги', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '521553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Финансовый результат хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Доходы текущего финансового года', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Доходы хозяйствующего субъекта', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Налоговые доходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Доходы от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Доходы от  оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Доходы от сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', NULL,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 '530234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям иных организаций по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям автономных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', NULL,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 '530404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', NULL,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 '530405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты с прочими кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Внутриведомственные расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Внутриведомственные расчеты по заработной плате', NULL,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 '530713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Прочие расчеты с кредиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по  прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по платежам в бюджеты', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,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 '530714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по принятым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Вложения в иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Вложения в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Увеличение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Уменьшение вложений в управляющие компании', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Вложения в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Увеличение вложений в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Уменьшение вложений в доли в международные организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Вложения в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение вложений в прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','ОБЯЗАТЕЛЬСТВА', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Расчеты по долговым обязательствам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', NULL,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 '540120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Увеличение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Уменьшение вложений в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Вложения в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Увеличение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Уменьшение вложений в векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Вложения в акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Вложения в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Увеличение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Уменьшение вложений в акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Вложения в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Вложения в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Увеличение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расчеты по поступлениям от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расчеты по поступлениям внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расчеты по поступлениям внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Расчеты с прочими дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Расчеты с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Увеличение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Уменьшение расчетов с учредителем', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Внутренние расчеты по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Внутренние расчеты по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Вложения в финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Вложения в ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Вложения в облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Расчеты по поступившим налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Расчеты по поступившим доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты по поступившим прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Расчет по поступлениям от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Расчеты по поступлениям от возврата депозитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по поступившим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Прочие расчеты с дебиторами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', NULL,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 '540220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Расчеты по ущербу имуществу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Расчеты по ущербу нефинансовым активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','Расчеты по ущербу  нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Расчеты по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Расчеты по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Расчеты по прочему ущербу', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Расчеты по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Расчеты с подотчетными лицами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Расчеты по предоставленным займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', NULL,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 '550103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Расчеты по кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансам по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Расчеты по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Расчеты по авансам по работам, услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Расчеты по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Расчеты с плательщиками прочих доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Расчеты по выданным авансам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,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 '550106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Расчеты по доходам от операций с активами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по доходам от операций с основными средствами', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Доли в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Увеличение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Уменьшение стоимости долей в международных организациях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Прочие финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Увеличение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Расчеты по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Расчеты с плательщиками налоговых доходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Расчеты по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с плательщиками доходов от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Расчеты по суммам принудительного изъятия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Уменьшение стоимости векселей', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Иные ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Акции и иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Акции', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение стоимости акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Участие в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Иные формы участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Увеличение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Иные финансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Активы в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Средства на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Финансовые вложения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Ценные бумаги, кроме акций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Облигации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Увеличение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Уменьшение стоимости облигаций', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Векселя', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Средства на счетах бюджета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', NULL,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 '550202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Средства бюджета на депозитных счетах', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Средства бюджета на депозитных счетах в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Средства бюджета на депозитных счетах в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Денежные средства  в кассе учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Касса', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Поступления средств в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Выбытия средств из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Денежные документы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Поступления денежных документов в кассу учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия денежных документов из кассы учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Средства на счетах бюджета', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Издержки обращения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Издержки обращения в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Издержки обращения в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Издержки обращения в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Издержки обращения в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Издержки обращения в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Издержки обращения в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Издержки обращения в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Издержки обращения в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Издержки обращения в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Денежные средства учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Общехозяйственные расходы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Себестоимость готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', NULL,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 '550302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Нефинансовые активы имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Нефинансовые активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Недвижимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Движимое имущество, составляющее казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Драгоценности и ювелирные изделия', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Нематериальные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Непроизведенные активы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Материальные запасы, составляющие казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Нефинансовые активы в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Основные средства - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Материальные запасы - предметы лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Вложения в иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Вложения в предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Вложения в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Товары –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Материальные запасы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Строительные материалы - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Прочие материальные запасы -  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Вложения в нефинансовые активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Вложения в недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Продукты питания - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,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 '550305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Амортизация транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Амортизация имущества, составляющего казну', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Амортизация движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Материальные запасы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Амортизация предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Амортизация сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Амортизация  иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Нематериальные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Нематериальные активы –  предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Непроизведенные активы', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Земля - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Амортизация', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Амортизация недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Сооружения - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Машины и оборудование – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Транспортные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Библиотечный фонд – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', NULL,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 '550400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Прочие основные средства – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Основные средства - предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Жилые помещения - предметы  лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Нежилые помещения – предметы лизинга', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Сооружения - недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Основные средства –  иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Сооружения – иное движимое имущество учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по социальному обеспечению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по прочим расходам', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по приобретению основных средств', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', '19000101','19000101',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 '610141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', '19000101','19000101',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 '610530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', '19000101','19000101',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 '610856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '610991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', '19000101','19000101',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 '620221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', '19000101','19000101',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 '620541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', '19000101','19000101',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 '620662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', '19000101','19000101',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 '620973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '620982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', '19000101','19000101',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 '621531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '621553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', '19000101','19000101',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 '630233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', '19000101','19000101',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 '630404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', '19000101','19000101',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 '630405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', '19000101','19000101',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 '630713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', '19000101','19000101',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 '630714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', '19000101','19000101',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 '640110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', '19000101','19000101',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 '640220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',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 '650103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', '19000101','19000101',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 '650106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', '19000101','19000101',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 '650201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', '19000101','19000101',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 '650302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',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 '650305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', '19000101','19000101',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 '650330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710000000',0,'ПлСчет_Каз_2011',1,'НЕФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','НЕФИНАНСОВЫЕ АКТИВЫ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710100000',0,'ПлСчет_Каз_2011',1,'Основные средства',0,'',0,'','Основные средства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710110000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения',0,'',0,'','Основные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710111000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – недвижимое имущество учреждения',0,'',0,'','Жилые помещения – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710111310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710111410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710112000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – недвижимое имущество учреждения',0,'',0,'','Нежилые помещения – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710112310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710112410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710113000',0,'ПлСчет_Каз_2011',1,'Сооружения - недвижимое имущество учреждения',0,'',0,'','Сооружения - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710113310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710113410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710115000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – недвижимое имущество учреждения',0,'',0,'','Транспортные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710115310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710115410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710118000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – недвижимое имущество учреждения',0,'',0,'','Прочие основные средства – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710118310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710118410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710130000',0,'ПлСчет_Каз_2011',1,'Основные средства –  иное движимое имущество учреждения',0,'',0,'','Основные средства –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710131000',0,'ПлСчет_Каз_2011',1,'Жилые помещения – иное движимое имущество учреждения',0,'',0,'','Жилые помещения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710131310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости жилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710131410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости жилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710132000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – иное движимое имущество учреждения',0,'',0,'','Нежилые помещения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710132310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нежилых помещений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710132410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710133000',0,'ПлСчет_Каз_2011',1,'Сооружения – иное движимое имущество учреждения',0,'',0,'','Сооружения – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710133310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости сооружений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710133410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости сооружений – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710134000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – иное движимое имущество учреждения',0,'',0,'','Машины и оборудование – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710134310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости машин и оборудования – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710134410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости машин и оборудования – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710135000',0,'ПлСчет_Каз_2011',1,'Транспортные средства – иное движимое имущество учреждения',0,'',0,'','Транспортные средства – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710135310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости транспортных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710135410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости транспортных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710136000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – иное движимое имущество учреждения',0,'',0,'','Производственный и хозяйственный инвентарь – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710136310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710136410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710137000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – иное движимое имущество учреждения',0,'',0,'','Библиотечный фонд – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710137310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости библиотечного фонда – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710137410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости библиотечного фонда – иного движимого имущества учреждения', '19000101','19000101',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 '710138000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – иное движимое имущество учреждения',0,'',0,'','Прочие основные средства – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710138310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих основных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710138410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих основных средств – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710140000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга',0,'',0,'','Основные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710141000',0,'ПлСчет_Каз_2011',1,'Жилые помещения - предметы  лизинга',0,'',0,'','Жилые помещения - предметы  лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710141310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости жилых помещений - предметов лизинга',0,'',0,'','Увеличение стоимости жилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710141410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости жилых помещений -предметов лизинга',0,'',0,'','Уменьшение стоимости жилых помещений -предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710142000',0,'ПлСчет_Каз_2011',1,'Нежилые помещения – предметы лизинга',0,'',0,'','Нежилые помещения – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710142310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Увеличение стоимости нежилых помещений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710142410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нежилых помещений – предметов лизинга',0,'',0,'','Уменьшение стоимости нежилых помещений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710143000',0,'ПлСчет_Каз_2011',1,'Сооружения - предметы лизинга',0,'',0,'','Сооружения - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710143310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости сооружений – предметов лизинга',0,'',0,'','Увеличение стоимости сооружений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710143410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости сооружений – предметов лизинга',0,'',0,'','Уменьшение стоимости сооружений – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710144000',0,'ПлСчет_Каз_2011',1,'Машины и оборудование – предметы лизинга',0,'',0,'','Машины и оборудование – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710144310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Увеличение стоимости машин и оборудования – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710144410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости машин и оборудования – предметов лизинга',0,'',0,'','Уменьшение стоимости машин и оборудования – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710145000',0,'ПлСчет_Каз_2011',1,'Транспортные средства - предметы лизинга',0,'',0,'','Транспортные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710145310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости транспортных средств – предметов лизинга',0,'',0,'','Увеличение стоимости транспортных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710145410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение стоимости транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710146000',0,'ПлСчет_Каз_2011',1,'Производственный и хозяйственный инвентарь – предметы лизинга',0,'',0,'','Производственный и хозяйственный инвентарь – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710146310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Увеличение стоимости производственного и хозяйственного инвентаря – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710146410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга',0,'',0,'','Уменьшение стоимости производственного и хозяйственного инвентаря – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710147000',0,'ПлСчет_Каз_2011',1,'Библиотечный фонд – предметы лизинга',0,'',0,'','Библиотечный фонд – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710147310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Увеличение стоимости библиотечного фонда – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710147410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости библиотечного фонда – предметов лизинга',0,'',0,'','Уменьшение стоимости библиотечного фонда – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710148000',0,'ПлСчет_Каз_2011',1,'Прочие основные средства – предметы лизинга',0,'',0,'','Прочие основные средства – предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710148310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Увеличение стоимости прочих основных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710148410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих основных средств – предметов лизинга',0,'',0,'','Уменьшение стоимости прочих основных средств – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710200000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы',0,'',0,'','Нематериальные активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710230000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  иное движимое имущество учреждения',0,'',0,'','Нематериальные активы –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710230320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости нематериальных активов – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710230420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости нематериальных активов – иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710240000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы –  предметы лизинга',0,'',0,'','Нематериальные активы –  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710240320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Увеличение стоимости нематериальных активов – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710240420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов – предметов лизинга',0,'',0,'','Уменьшение стоимости нематериальных активов – предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710300000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы',0,'',0,'','Непроизведенные активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710310000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы – недвижимое имущество учреждения',0,'',0,'','Непроизведенные активы – недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710311000',0,'ПлСчет_Каз_2011',1,'Земля - недвижимое имущество учреждения',0,'',0,'','Земля - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710311330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости земли - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710311430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости земли - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости земли - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710312000',0,'ПлСчет_Каз_2011',1,'Ресурсы недр - недвижимое имущество учреждения',0,'',0,'','Ресурсы недр - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710312330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости ресурсов недр -недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости ресурсов недр -недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710312430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости ресурсов недр - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710313000',0,'ПлСчет_Каз_2011',1,'Прочие непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Прочие непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710313330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710313430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих непроизведенных активов - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710400000',0,'ПлСчет_Каз_2011',1,'Амортизация',0,'',0,'','Амортизация', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710410000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества учреждения',0,'',0,'','Амортизация недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710411000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710411410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710412000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710412410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710413000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - недвижимого имущества учреждения',0,'',0,'','Амортизация сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710413410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710415000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710415410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710418000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710418410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - недвижимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710430000',0,'ПлСчет_Каз_2011',1,'Амортизация  иного движимого имущества учреждения',0,'',0,'','Амортизация  иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710431000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация жилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710431410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710432000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Амортизация нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710432410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710433000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - иного движимого имущества учреждения',0,'',0,'','Амортизация сооружений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710433410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710434000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Амортизация машин и оборудования - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710434410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710435000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация транспортных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710435410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710436000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710436410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710437000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Амортизация библиотечного фонда - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710437410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710438000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Амортизация прочих основных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710438410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710439000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Амортизация нематериальных активов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710439420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710440000',0,'ПлСчет_Каз_2011',1,'Амортизация предметов лизинга',0,'',0,'','Амортизация предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710441000',0,'ПлСчет_Каз_2011',1,'Амортизация жилых помещений - предметов  лизинга',0,'',0,'','Амортизация жилых помещений - предметов  лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710441410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости жилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710442000',0,'ПлСчет_Каз_2011',1,'Амортизация нежилых помещений - предметов лизинга',0,'',0,'','Амортизация нежилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710442410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нежилых помещений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710443000',0,'ПлСчет_Каз_2011',1,'Амортизация сооружений - предметов лизинга',0,'',0,'','Амортизация сооружений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710443410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости сооружений - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости сооружений - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710444000',0,'ПлСчет_Каз_2011',1,'Амортизация машин и оборудования - предметов лизинга',0,'',0,'','Амортизация машин и оборудования - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710444410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости машин и оборудования - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710445000',0,'ПлСчет_Каз_2011',1,'Амортизация транспортных средств - предметов лизинга',0,'',0,'','Амортизация транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710445410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости транспортных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710446000',0,'ПлСчет_Каз_2011',1,'Амортизация производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Амортизация производственного и хозяйственного инвентаря - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710446410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости производственного и хозяйственного инвентаря - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710447000',0,'ПлСчет_Каз_2011',1,'Амортизация библиотечного фонда -  предмета лизинга',0,'',0,'','Амортизация библиотечного фонда -  предмета лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710447410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости библиотечного фонда - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710448000',0,'ПлСчет_Каз_2011',1,'Амортизация прочих основных средств - предметов лизинга',0,'',0,'','Амортизация прочих основных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710448410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости прочих основных средств - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710449000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов - предметов лизинга',0,'',0,'','Амортизация нематериальных активов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710449420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710450000',0,'ПлСчет_Каз_2011',1,'Амортизация имущества, составляющего казну',0,'',0,'','Амортизация имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710451000',0,'ПлСчет_Каз_2011',1,'Амортизация недвижимого имущества в составе имущества казны',0,'',0,'','Амортизация недвижимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710451410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости недвижимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710458000',0,'ПлСчет_Каз_2011',1,'Амортизация движимого имущества в составе имущества казны',0,'',0,'','Амортизация движимого имущества в составе имущества казны', '19000101','19000101',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 '710458410',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости движимого имущества в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710459000',0,'ПлСчет_Каз_2011',1,'Амортизация нематериальных активов в составе имущества казны',0,'',0,'','Амортизация нематериальных активов в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710459420',0,'ПлСчет_Каз_2011',1,'Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны',0,'',0,'','Уменьшение за счет амортизации стоимости нематериальных активов в составе имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710500000',0,'ПлСчет_Каз_2011',1,'Материальные запасы',0,'',0,'','Материальные запасы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710530000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - иное движимое имущество учреждения',0,'',0,'','Материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710531000',0,'ПлСчет_Каз_2011',1,'Медикаменты и перевязочные средств - иное движимое имущество учреждения',0,'',0,'','Медикаменты и перевязочные средств - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710531340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710531440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости медикаментов и перевязочных средств - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710532000',0,'ПлСчет_Каз_2011',1,'Продукты питания - иное движимое имущество учреждения',0,'',0,'','Продукты питания - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710532340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости продуктов питания - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710532440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости продуктов питания - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости продуктов питания - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710533000',0,'ПлСчет_Каз_2011',1,'Горюче-смазочные материалы - иное движимое имущество учреждения',0,'',0,'','Горюче-смазочные материалы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710533340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710533440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости горюче-смазочных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710534000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - иное движимое имущество учреждения',0,'',0,'','Строительные материалы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710534340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости строительных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710534440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости строительных материалов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710535000',0,'ПлСчет_Каз_2011',1,'Мягкий инвентарь - иное движимое имущество учреждения',0,'',0,'','Мягкий инвентарь - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710535340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости мягкого инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710535440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости мягкого инвентаря - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710536000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы - иное движимое имущество учреждения',0,'',0,'','Прочие материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710536340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости прочих материальных запасов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710536440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости прочих материальных запасов - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710537000',0,'ПлСчет_Каз_2011',1,'Готовая продукция - иное движимое имущество учреждения',0,'',0,'','Готовая продукция - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710537340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости готовой продукции - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710537440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости готовой продукции - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости готовой продукции - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710538000',0,'ПлСчет_Каз_2011',1,'Товары –  иное движимое имущество учреждения',0,'',0,'','Товары –  иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710538340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710538440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Уменьшение стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710539000',0,'ПлСчет_Каз_2011',1,'Наценка на товары – иное движимое имущество учреждения',0,'',0,'','Наценка на товары – иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710539340',0,'ПлСчет_Каз_2011',1,'Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения',0,'',0,'','Увеличение за счет наценки стоимости товаров - иного движимого имущества учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710540000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга',0,'',0,'','Материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710544000',0,'ПлСчет_Каз_2011',1,'Строительные материалы - предметы лизинга',0,'',0,'','Строительные материалы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710544340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости строительных материалов - предметов лизинга',0,'',0,'','Увеличение стоимости строительных материалов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710544440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости строительных материалов - предметов лизинга',0,'',0,'','Уменьшение стоимости строительных материалов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710546000',0,'ПлСчет_Каз_2011',1,'Прочие материальные запасы -  предметы лизинга',0,'',0,'','Прочие материальные запасы -  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710546340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Увеличение стоимости прочих материальных запасов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710546440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих материальных запасов - предметов лизинга',0,'',0,'','Уменьшение стоимости прочих материальных запасов - предметов лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710600000',0,'ПлСчет_Каз_2011',1,'Вложения в нефинансовые активы',0,'',0,'','Вложения в нефинансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710610000',0,'ПлСчет_Каз_2011',1,'Вложения в недвижимое имущество учреждения',0,'',0,'','Вложения в недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710611000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - недвижимое имущество учреждения',0,'',0,'','Вложения в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710611310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710611410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710613000',0,'ПлСчет_Каз_2011',1,'Вложения в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Вложения в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710613330',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Увеличение вложений в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710613430',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения',0,'',0,'','Уменьшение вложений в непроизведенные активы - недвижимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710630000',0,'ПлСчет_Каз_2011',1,'Вложения в иное движимое имущество учреждения',0,'',0,'','Вложения в иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710631000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - иное движимое имущество учреждения',0,'',0,'','Вложения в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710631310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710631410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в основные средства - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710632000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Вложения в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710632320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710632420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в нематериальные активы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710634000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Вложения в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710634340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Увеличение вложений в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710634440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - иное движимое имущество учреждения',0,'',0,'','Уменьшение вложений в материальные запасы - иное движимое имущество учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710640000',0,'ПлСчет_Каз_2011',1,'Вложения в предметы лизинга',0,'',0,'','Вложения в предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710641000',0,'ПлСчет_Каз_2011',1,'Вложения в основные средства - предметы лизинга',0,'',0,'','Вложения в основные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710641310',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в основные средства - предметы лизинга',0,'',0,'','Увеличение вложений в основные средства - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710641410',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в основные средства - предмета лизинга',0,'',0,'','Уменьшение вложений в основные средства - предмета лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710642000',0,'ПлСчет_Каз_2011',1,'Вложения в нематериальные активы - предметы лизинга',0,'',0,'','Вложения в нематериальные активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710642320',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в нематериальные активы - предметы лизинга',0,'',0,'','Увеличение вложений в нематериальные активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710642420',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в нематериальные  активы - предметы лизинга',0,'',0,'','Уменьшение вложений в нематериальные  активы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710644000',0,'ПлСчет_Каз_2011',1,'Вложения в материальные запасы -  предметы лизинга',0,'',0,'','Вложения в материальные запасы -  предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710644340',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в материальные запасы - предметы лизинга',0,'',0,'','Увеличение вложений в материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710644440',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в материальные запасы - предметы лизинга',0,'',0,'','Уменьшение вложений в материальные запасы - предметы лизинга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710700000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы в пути',0,'',0,'','Нефинансовые активы в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710710000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество учреждения в пути',0,'',0,'','Недвижимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710711000',0,'ПлСчет_Каз_2011',1,'Основные средства – недвижимое имущество учреждения в пути',0,'',0,'','Основные средства – недвижимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710711310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств – недвижимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710711410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств – недвижимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710730000',0,'ПлСчет_Каз_2011',1,'Иное движимое имущество учреждения в пути',0,'',0,'','Иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710731000',0,'ПлСчет_Каз_2011',1,'Основные средства - иное движимое имущество учреждения в пути',0,'',0,'','Основные средства - иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710731310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости основных средств - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710731410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости основных средств - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710733000',0,'ПлСчет_Каз_2011',1,'Материальные запасы – иное движимое имущество учреждения в пути',0,'',0,'','Материальные запасы – иное движимое имущество учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710733340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Увеличение стоимости материальных запасов - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710733440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути',0,'',0,'','Уменьшение стоимости материальных запасов - иного движимого имущества учреждения в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710740000',0,'ПлСчет_Каз_2011',1,'Предметы лизинга в пути',0,'',0,'','Предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710741000',0,'ПлСчет_Каз_2011',1,'Основные средства - предметы лизинга в пути',0,'',0,'','Основные средства - предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710741310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Увеличение стоимости основных средств - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710741410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости основных средств - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости основных средств - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710743000',0,'ПлСчет_Каз_2011',1,'Материальные запасы - предметы лизинга в пути',0,'',0,'','Материальные запасы - предметы лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710743340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Увеличение стоимости материальных запасов - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710743440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов - предметов лизинга в пути',0,'',0,'','Уменьшение стоимости материальных запасов - предметов лизинга в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710800000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы имущества казны',0,'',0,'','Нефинансовые активы имущества казны', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710850000',0,'ПлСчет_Каз_2011',1,'Нефинансовые активы, составляющие казну',0,'',0,'','Нефинансовые активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710851000',0,'ПлСчет_Каз_2011',1,'Недвижимое имущество, составляющее казну',0,'',0,'','Недвижимое имущество, составляющее казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710851310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости недвижимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710851410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости недвижимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости недвижимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710852000',0,'ПлСчет_Каз_2011',1,'Движимое имущество, составляющее казну',0,'',0,'','Движимое имущество, составляющее казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710852310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости движимого имущества, составляющего казну',0,'',0,'','Увеличение стоимости движимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710852410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости движимого имущества, составляющего казну',0,'',0,'','Уменьшение стоимости движимого имущества, составляющего казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710853000',0,'ПлСчет_Каз_2011',1,'Драгоценности и ювелирные изделия',0,'',0,'','Драгоценности и ювелирные изделия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710853310',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости драгоценных и ювелирных изделий',0,'',0,'','Увеличение стоимости драгоценных и ювелирных изделий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710853410',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости драгоценных и ювелирных изделий',0,'',0,'','Уменьшение стоимости драгоценных и ювелирных изделий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710854000',0,'ПлСчет_Каз_2011',1,'Нематериальные активы, составляющие казну',0,'',0,'','Нематериальные активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710854320',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости нематериальных активов, составляющих казну',0,'',0,'','Увеличение стоимости нематериальных активов, составляющих казну', '19000101','19000101',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 '710854420',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости нематериальных активов, составляющих казну',0,'',0,'','Уменьшение стоимости нематериальных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710855000',0,'ПлСчет_Каз_2011',1,'Непроизведенные активы, составляющие казну',0,'',0,'','Непроизведенные активы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710855330',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Увеличение стоимости непроизведенных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710855430',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости непроизведенных активов, составляющих казну',0,'',0,'','Уменьшение стоимости непроизведенных активов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710856000',0,'ПлСчет_Каз_2011',1,'Материальные запасы, составляющие казну',0,'',0,'','Материальные запасы, составляющие казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710856340',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости материальных запасов, составляющих казну',0,'',0,'','Увеличение стоимости материальных запасов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710856440',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости материальных запасов, составляющих казну',0,'',0,'','Уменьшение стоимости материальных запасов, составляющих казну', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710900000',0,'ПлСчет_Каз_2011',1,'Затраты на изготовление готовой продукции, выполнение работ, услуг',0,'',0,'','Затраты на изготовление готовой продукции, выполнение работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710960000',0,'ПлСчет_Каз_2011',1,'Себестоимость готовой продукции, работ, услуг',0,'',0,'','Себестоимость готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961211',0,'ПлСчет_Каз_2011',1,'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961212',0,'ПлСчет_Каз_2011',1,'Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие выплаты в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961213',0,'ПлСчет_Каз_2011',1,'Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на начисления на выплаты по оплате труда в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961221',0,'ПлСчет_Каз_2011',1,'Затраты на услуги связи в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на услуги связи в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961222',0,'ПлСчет_Каз_2011',1,'Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на транспортные услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961223',0,'ПлСчет_Каз_2011',1,'Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на коммунальные услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961224',0,'ПлСчет_Каз_2011',1,'Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на арендную плату за пользование имуществом в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961225',0,'ПлСчет_Каз_2011',1,'Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на работы, услуги по содержанию имущества в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961226',0,'ПлСчет_Каз_2011',1,'Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг',0,'',0,'','Затраты на прочие работы, услуги в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961271',0,'ПлСчет_Каз_2011',1,'Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Амортизация основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов в себестоимости готовой продукции, работ, услуг',0,'',0,'','Расходование материальных запасов в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710961290',0,'ПлСчет_Каз_2011',1,'Прочие затраты в себестоимости готовой продукции, работ, услуг',0,'',0,'','Прочие затраты в себестоимости готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710970000',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971211',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971212',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971213',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971221',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971222',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971223',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971224',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971225',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971226',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Накладные расходы производства готовой продукции в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971271',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971272',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710971290',0,'ПлСчет_Каз_2011',1,'Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Накладные расходы производства готовой продукции, работ, услуг в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710980000',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы',0,'',0,'','Общехозяйственные расходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981211',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981212',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981213',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981221',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981222',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981223',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981224',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981225',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981226',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг',0,'',0,'','Общехозяйственные расходы производства готовой продукции в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981271',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981272',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710981290',0,'ПлСчет_Каз_2011',1,'Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов',0,'',0,'','Общехозяйственные расходы на производство готовой продукции, работ, услуг в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710990000',0,'ПлСчет_Каз_2011',1,'Издержки обращения',0,'',0,'','Издержки обращения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991211',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части заработной платы',0,'',0,'','Издержки обращения в части заработной платы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991212',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих выплат',0,'',0,'','Издержки обращения в части прочих выплат', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991213',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части начислений на выплаты по оплате труда',0,'',0,'','Издержки обращения в части начислений на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991221',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части услуг связи',0,'',0,'','Издержки обращения в части услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991222',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части транспортных услуг',0,'',0,'','Издержки обращения в части транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991223',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части коммунальных услуг',0,'',0,'','Издержки обращения в части коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991224',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части арендной платы за пользование имуществом',0,'',0,'','Издержки обращения в части арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991225',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части содержания имущества',0,'',0,'','Издержки обращения в части содержания имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991226',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих работ, услуг',0,'',0,'','Издержки обращения в части прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991271',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части амортизации основных средств и нематериальных активов',0,'',0,'','Издержки обращения в части амортизации основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991272',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части расходования материальных запасов',0,'',0,'','Издержки обращения в части расходования материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '710991290',0,'ПлСчет_Каз_2011',1,'Издержки обращения в части прочих расходов',0,'',0,'','Издержки обращения в части прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЕ АКТИВЫ',0,'',0,'','ФИНАНСОВЫЕ АКТИВЫ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720100000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения',0,'',0,'','Денежные средства учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720110000',0,'ПлСчет_Каз_2011',1,'Денежные средства на лицевых счетах учреждения в органе казначейства',0,'',0,'','Денежные средства на лицевых счетах учреждения в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720111000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на лицевых счетах в органе казначейства',0,'',0,'','Денежные средства учреждения на лицевых счетах в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720111510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на лицевые счета в органе казначейства',0,'',0,'','Поступления денежных средств учреждения на лицевые счета в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720111610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с лицевых счетов в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения с лицевых счетов в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720113000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в пути в органе казначейства',0,'',0,'','Денежные средства учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720113510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в пути в органе казначейства',0,'',0,'','Поступления денежных средств учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720113610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в пути в органе казначейства',0,'',0,'','Выбытия денежных средств учреждения в пути в органе казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720120000',0,'ПлСчет_Каз_2011',1,'Денежные средства на счетах учреждения в кредитной организации',0,'',0,'','Денежные средства на счетах учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720121000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения на счетах в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720121510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720121610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения со счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения со счетов в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720122000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения, размещенные на депозиты в кредитной организации',0,'',0,'','Денежные средства учреждения, размещенные на депозиты в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720122510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения на депозитные счета в кредитной организации',0,'',0,'','Поступления денежных средств учреждения на депозитные счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720122610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения с депозитных счетов в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения с депозитных счетов в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720123000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в кредитной организации в пути',0,'',0,'','Денежные средства учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720123510',0,'ПлСчет_Каз_2011',1,'Поступление денежных средств учреждения в кредитной организации в пути',0,'',0,'','Поступление денежных средств учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720123610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в кредитной организации в пути',0,'',0,'','Выбытия денежных средств учреждения в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720126000',0,'ПлСчет_Каз_2011',1,'Аккредитивы на счетах учреждения в кредитной организации',0,'',0,'','Аккредитивы на счетах учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720126510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств на аккредитивный счет учреждения в кредитной организации',0,'',0,'','Поступления денежных средств на аккредитивный счет учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720126610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации',0,'',0,'','Выбытия денежных средств с аккредитивного счета учреждения в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720127000',0,'ПлСчет_Каз_2011',1,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации',0,'',0,'','Денежные средства учреждения в иностранной валюте на счетах в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720127510',0,'ПлСчет_Каз_2011',1,'Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации',0,'',0,'','Поступления денежных средств учреждения в иностранной валюте на счет в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720127610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации',0,'',0,'','Выбытия денежных средств учреждения в иностранной валюте со счета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720130000',0,'ПлСчет_Каз_2011',1,'Денежные средства  в кассе учреждения',0,'',0,'','Денежные средства  в кассе учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720134000',0,'ПлСчет_Каз_2011',1,'Касса',0,'',0,'','Касса', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720134510',0,'ПлСчет_Каз_2011',1,'Поступления средств в кассу учреждения',0,'',0,'','Поступления средств в кассу учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720134610',0,'ПлСчет_Каз_2011',1,'Выбытия средств из кассы учреждения',0,'',0,'','Выбытия средств из кассы учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720135000',0,'ПлСчет_Каз_2011',1,'Денежные документы',0,'',0,'','Денежные документы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720135510',0,'ПлСчет_Каз_2011',1,'Поступления денежных документов в кассу учреждения',0,'',0,'','Поступления денежных документов в кассу учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720135610',0,'ПлСчет_Каз_2011',1,'Выбытия денежных документов из кассы учреждения',0,'',0,'','Выбытия денежных документов из кассы учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720200000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета',0,'',0,'','Средства на счетах бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720210000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720211000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в органе Федерального казначейства',0,'',0,'','Средства на счетах бюджета в рублях в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720211510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в рублях в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720211610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в рублях  в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720212000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Средства на счетах бюджета в органе Федерального казначейства в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720212510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счетах бюджета в органе Федерального казначейства в пути',0,'',0,'','Поступления средств на счетах бюджета в органе Федерального казначейства в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720212610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в органе Федерального казначейства в пути',0,'',0,'','Выбытия средств со счетов бюджета в органе Федерального казначейства в пути', '19000101','19000101',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 '720213000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства',0,'',0,'','Средства на счетах бюджета в иностранной валюте в органах Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720213510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720213610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в органе Федерального казначейства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720220000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации',0,'',0,'','Средства на счетах бюджета в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720221000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в рублях в кредитной организации',0,'',0,'','Средства на счетах бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720221510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в рублях в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720221610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в рублях в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в рублях в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720222000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в кредитной организации в пути',0,'',0,'','Средства на счетах бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720222510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в кредитной организации в пути',0,'',0,'','Поступления средств на счета бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720222610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в кредитной организации в пути',0,'',0,'','Выбытия средств со счетов бюджета в кредитной организации в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720223000',0,'ПлСчет_Каз_2011',1,'Средства на счетах бюджета в иностранной валюте в кредитной организации',0,'',0,'','Средства на счетах бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720223510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета бюджета в иностранной валюте в кредитной организации',0,'',0,'','Поступления средств на счета бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720223610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации',0,'',0,'','Выбытия средств со счетов бюджета в иностранной валюте в кредитной организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720230000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах',0,'',0,'','Средства бюджета на депозитных счетах', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720231000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в рублях',0,'',0,'','Средства бюджета на депозитных счетах в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720231510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в рублях',0,'',0,'','Поступления средств бюджета на депозитные счета в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720231610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в рублях',0,'',0,'','Выбытия средств бюджета с депозитных счетов в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720232000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в пути',0,'',0,'','Средства бюджета на депозитных счетах в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720232510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в пути',0,'',0,'','Поступления средств бюджета на депозитные счета в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720232610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в пути',0,'',0,'','Выбытия средств бюджета с депозитных счетов в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720233000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на депозитных счетах в иностранной валюте',0,'',0,'','Средства бюджета на депозитных счетах в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720233510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на депозитные счета в  иностранной валюте',0,'',0,'','Поступления средств бюджета на депозитные счета в  иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720233610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета с депозитных счетов в  иностранной валюте',0,'',0,'','Выбытия средств бюджета с депозитных счетов в  иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720300000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720301000',0,'ПлСчет_Каз_2011',1,'Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Средства поступлений, распределяемые между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720301510',0,'ПлСчет_Каз_2011',1,'Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Поступления средств, распределяемых между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720301610',0,'ПлСчет_Каз_2011',1,'Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств, распределяемых между бюджетами бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720310000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720312000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджета на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720312510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720312610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720313000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720313510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720313610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720314000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720314510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720314610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720315000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720315510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание',0,'',0,'','Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720315610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание',0,'',0,'','Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720320000',0,'ПлСчет_Каз_2011',1,'Средства на счетах органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Средства на счетах органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720320510',0,'ПлСчет_Каз_2011',1,'Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Поступления средств на счета органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720320610',0,'ПлСчет_Каз_2011',1,'Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути',0,'',0,'','Выбытия средств со счетов органа, осуществляющего кассовое обслуживание, в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720330000',0,'ПлСчет_Каз_2011',1,'Средства на счетах для выплаты наличных денег',0,'',0,'','Средства на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720332000',0,'ПлСчет_Каз_2011',1,'Средства бюджета на счетах для выплаты наличных денег',0,'',0,'','Средства бюджета на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720332510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджета на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджета на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720332610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджета со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720333000',0,'ПлСчет_Каз_2011',1,'Средства бюджетных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства бюджетных учреждений на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720333510',0,'ПлСчет_Каз_2011',1,'Поступления средств бюджетных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств бюджетных учреждений на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720333610',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств бюджетных учреждений со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720334000',0,'ПлСчет_Каз_2011',1,'Средства автономных учреждений на счетах для выплаты наличных денег',0,'',0,'','Средства автономных учреждений на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720334510',0,'ПлСчет_Каз_2011',1,'Поступления средств автономных учреждений на счета для выплаты наличных денег',0,'',0,'','Поступления средств автономных учреждений на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720334610',0,'ПлСчет_Каз_2011',1,'Выбытия средств автономных учреждений со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств автономных учреждений со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720335000',0,'ПлСчет_Каз_2011',1,'Средства иных организаций на счетах для выплаты наличных денег',0,'',0,'','Средства иных организаций на счетах для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720335510',0,'ПлСчет_Каз_2011',1,'Поступления средств иных организаций на счета для выплаты наличных денег',0,'',0,'','Поступления средств иных организаций на счета для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720335610',0,'ПлСчет_Каз_2011',1,'Выбытия средств иных организаций со счетов для выплаты наличных денег',0,'',0,'','Выбытия средств иных организаций со счетов для выплаты наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720400000',0,'ПлСчет_Каз_2011',1,'Финансовые вложения',0,'',0,'','Финансовые вложения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720420000',0,'ПлСчет_Каз_2011',1,'Ценные бумаги, кроме акций',0,'',0,'','Ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720421000',0,'ПлСчет_Каз_2011',1,'Облигации',0,'',0,'','Облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720421520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости облигаций',0,'',0,'','Увеличение стоимости облигаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720421620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости облигаций',0,'',0,'','Уменьшение стоимости облигаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720422000',0,'ПлСчет_Каз_2011',1,'Векселя',0,'',0,'','Векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720422520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости векселей',0,'',0,'','Увеличение стоимости векселей', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720422620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости векселей',0,'',0,'','Уменьшение стоимости векселей', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720423000',0,'ПлСчет_Каз_2011',1,'Иные ценные бумаги, кроме акций',0,'',0,'','Иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720423520',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Увеличение стоимости иных ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720423620',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных ценных бумаг, кроме акций',0,'',0,'','Уменьшение стоимости иных ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720430000',0,'ПлСчет_Каз_2011',1,'Акции и иные формы участия в капитале',0,'',0,'','Акции и иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720431000',0,'ПлСчет_Каз_2011',1,'Акции',0,'',0,'','Акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720431530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости акций',0,'',0,'','Увеличение стоимости акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720431630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости акций',0,'',0,'','Уменьшение стоимости акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720432000',0,'ПлСчет_Каз_2011',1,'Уставной фонд государственных (муниципальных) предприятий',0,'',0,'','Уставной фонд государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720432530',0,'ПлСчет_Каз_2011',1,'Увеличение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Увеличение уставного фонда государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720432630',0,'ПлСчет_Каз_2011',1,'Уменьшение уставного фонда государственных (муниципальных) предприятий',0,'',0,'','Уменьшение уставного фонда государственных (муниципальных) предприятий', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720433000',0,'ПлСчет_Каз_2011',1,'Участие в государственных (муниципальных) учреждениях',0,'',0,'','Участие в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720433530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Увеличение стоимости участия в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720433630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости участия в государственных (муниципальных) учреждениях',0,'',0,'','Уменьшение стоимости участия в государственных (муниципальных) учреждениях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720434000',0,'ПлСчет_Каз_2011',1,'Иные формы участия в капитале',0,'',0,'','Иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720434530',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости иных форм участия в капитале',0,'',0,'','Увеличение стоимости иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720434630',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости иных форм участия в капитале',0,'',0,'','Уменьшение стоимости иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720450000',0,'ПлСчет_Каз_2011',1,'Иные финансовые активы',0,'',0,'','Иные финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720451000',0,'ПлСчет_Каз_2011',1,'Активы в управляющих компаниях',0,'',0,'','Активы в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720451550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости активов в управляющих компаниях',0,'',0,'','Увеличение стоимости активов в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720451650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости активов в управляющих компаниях',0,'',0,'','Уменьшение стоимости активов в управляющих компаниях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720452000',0,'ПлСчет_Каз_2011',1,'Доли в международных организациях',0,'',0,'','Доли в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720452550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости долей в международных организациях',0,'',0,'','Увеличение стоимости долей в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720452650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости долей в международных организациях',0,'',0,'','Уменьшение стоимости долей в международных организациях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720453000',0,'ПлСчет_Каз_2011',1,'Прочие финансовые активы',0,'',0,'','Прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720453550',0,'ПлСчет_Каз_2011',1,'Увеличение стоимости прочих финансовых активов',0,'',0,'','Увеличение стоимости прочих финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720453650',0,'ПлСчет_Каз_2011',1,'Уменьшение стоимости прочих финансовых активов',0,'',0,'','Уменьшение стоимости прочих финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720500000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам',0,'',0,'','Расчеты по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720510000',0,'ПлСчет_Каз_2011',1,'Расчеты по налоговым доходам',0,'',0,'','Расчеты по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720511000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками налоговых доходов',0,'',0,'','Расчеты с плательщиками налоговых доходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720511560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по налоговым доходам',0,'',0,'','Увеличение дебиторской задолженности по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720511660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по налоговым доходам',0,'',0,'','Уменьшение дебиторской задолженности по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720520000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от собственности',0,'',0,'','Расчеты по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720521000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от собственности',0,'',0,'','Расчеты с плательщиками доходов от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720521560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от собственности',0,'',0,'','Увеличение дебиторской задолженности по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720521660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от собственности',0,'',0,'','Уменьшение дебиторской задолженности по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720530000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от оказания платных работ, услуг',0,'',0,'','Расчеты по доходам от оказания платных работ, услуг', '19000101','19000101',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 '720531000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками доходов от оказания платных работ, услуг',0,'',0,'','Расчеты с плательщиками доходов от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720531560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Увеличение дебиторской задолженности по доходам от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720531660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности по доходам от оказания платных работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720540000',0,'ПлСчет_Каз_2011',1,'Расчеты по суммам принудительного изъятия',0,'',0,'','Расчеты по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720541000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками сумм принудительного изъятия',0,'',0,'','Расчеты с плательщиками сумм принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720541560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Увеличение дебиторской задолженности по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720541660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по суммам принудительного изъятия',0,'',0,'','Уменьшение дебиторской задолженности по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720550000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от бюджетов',0,'',0,'','Расчеты по поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720551000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720551560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720551660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720552000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720552560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720552660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720553000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720553560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Увеличение дебиторской задолженности по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720553660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций',0,'',0,'','Уменьшение дебиторской задолженности по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720560000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720561000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками  страховых взносов на обязательное социальное страхование',0,'',0,'','Расчеты с плательщиками  страховых взносов на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720561560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Увеличение дебиторской задолженности по страховым взносам на обязательное социальные страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720561660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование',0,'',0,'','Уменьшение дебиторской задолженности по страховым взносам на обязательное социальные страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720570000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с активами',0,'',0,'','Расчеты по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720571000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с основными средствами',0,'',0,'','Расчеты по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720571560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720571660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с основными средствами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с основными средствами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720572000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с нематериальными активами',0,'',0,'','Расчеты по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720572560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720572660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с нематериальными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720573000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с непроизведенными активами',0,'',0,'','Расчеты по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720573560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720573660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с непроизведенными активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720574000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с материальными запасами',0,'',0,'','Расчеты по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720574560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720574660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с материальными запасами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с материальными запасами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720575000',0,'ПлСчет_Каз_2011',1,'Расчеты по доходам от операций с финансовыми  активами',0,'',0,'','Расчеты по доходам от операций с финансовыми  активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720575560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Увеличение дебиторской задолженности по доходам от операций с финансовыми активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720575660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами',0,'',0,'','Уменьшение дебиторской задолженности по доходам от операций с финансовыми активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720580000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим доходам',0,'',0,'','Расчеты по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720581000',0,'ПлСчет_Каз_2011',1,'Расчеты с плательщиками прочих доходов',0,'',0,'','Расчеты с плательщиками прочих доходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720581560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по прочим доходам',0,'',0,'','Увеличение дебиторской задолженности по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720581660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по прочим доходам',0,'',0,'','Уменьшение дебиторской задолженности по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выданным авансам',0,'',0,'','Расчеты по выданным авансам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720610000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720612000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим выплатам',0,'',0,'','Расчеты по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720612560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720612660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720613000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720613560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720613660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности по авансам по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720620000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам',0,'',0,'','Расчеты по авансам по работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720621000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по услугам связи',0,'',0,'','Расчеты по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720621560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Увеличение дебиторской задолженности по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720621660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по услугам связи',0,'',0,'','Уменьшение дебиторской задолженности по авансам по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720622000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по транспортным услугам',0,'',0,'','Расчеты по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720622560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720622660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по транспортным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720623000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по коммунальным услугам',0,'',0,'','Расчеты по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720623560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720623660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по коммунальным услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720624000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по арендной плате за пользование имуществом',0,'',0,'','Расчеты по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720624560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720624660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности по авансам по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720625000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720625560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720625660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности по авансам по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720626000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим  работам, услугам',0,'',0,'','Расчеты по авансам по прочим  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720626560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по авансам по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720626660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по прочим работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по авансам по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720630000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по поступлению нефинансовых активов',0,'',0,'','Расчеты по авансам по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720631000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению основных средств',0,'',0,'','Расчеты по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720631560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720631660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720632000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению нематериальных активов',0,'',0,'','Расчеты по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720632560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720632660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720633000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению непроизведенных активов',0,'',0,'','Расчеты по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720633560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720633660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720634000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по приобретению материальных запасов',0,'',0,'','Расчеты по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720634560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720634660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720640000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720641000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720641560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720641660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720642000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по авансовым  безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720642560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720642660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение дебиторской задолженности по авансовым безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720650000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по авансовым безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720651000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720651560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720651660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720652000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720652560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720652660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720653000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансовым перечислениям международным организациям',0,'',0,'','Расчеты по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720653560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Увеличение дебиторской задолженности по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720653660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям',0,'',0,'','Уменьшение дебиторской задолженности по авансовым перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720660000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по социальному обеспечению',0,'',0,'','Расчеты по авансам по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720661000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',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 '720661560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720661660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720662000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пособиям по социальной помощи населению',0,'',0,'','Расчеты по авансам по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720662560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности по авансам по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720662660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720663000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720663560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720663660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности по авансам по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720690000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по прочим расходам',0,'',0,'','Расчеты по авансам по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720691000',0,'ПлСчет_Каз_2011',1,'Расчеты по авансам по оплате прочих расходов',0,'',0,'','Расчеты по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720691560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720691660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по авансам по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности по авансам по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720700000',0,'ПлСчет_Каз_2011',1,'Расчеты по кредитам, займам (ссудам)',0,'',0,'','Расчеты по кредитам, займам (ссудам)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720710000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным кредитам, займам (ссудам)',0,'',0,'','Расчеты по предоставленным кредитам, займам (ссудам)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720711000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720711540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720711640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720713000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720713540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720713640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720714000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам, ссудам',0,'',0,'','Расчеты по предоставленным займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720714540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам, ссудам',0,'',0,'','Увеличение задолженности дебиторов по займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720714640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам, ссудам',0,'',0,'','Уменьшение задолженности дебиторов по займам, ссудам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720720000',0,'ПлСчет_Каз_2011',1,'Расчеты в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720721000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720721540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720721640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720723000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными дебиторами по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720723540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720723640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности иных дебиторов по бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720724000',0,'ПлСчет_Каз_2011',1,'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720724540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720724640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности дебиторов по займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720730000',0,'ПлСчет_Каз_2011',1,'Расчеты с дебиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с дебиторами по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720731000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720731540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720731640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720733000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными дебиторами  по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720733540',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности иных дебиторов по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720733640',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности иных дебиторов по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720800000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами',0,'',0,'','Расчеты с подотчетными лицами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720810000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720811000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по заработной плате',0,'',0,'','Расчеты с подотчетными лицами по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720811560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720811660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по заработной плате',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720812000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим выплатам',0,'',0,'','Расчеты с подотчетными лицами по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720812560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720812660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720813000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты с подотчетными лицами по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720813560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720813660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720820000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по работам, услугам',0,'',0,'','Расчеты с подотчетными лицами по работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720821000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате услуг связи',0,'',0,'','Расчеты с подотчетными лицами по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720821560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720821660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате услуг связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720822000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате транспортных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720822560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720822660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате транспортных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720823000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате коммунальных услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720823560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720823660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате коммунальных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720824000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом',0,'',0,'','Расчеты с подотчетными лицами по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720824560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720824660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате арендной платы за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720825000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества',0,'',0,'','Расчеты с подотчетными лицами по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720825560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720825660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате работ, услуг по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720826000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих работ, услуг',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720826560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720826660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720830000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по поступлению нефинансовых активов',0,'',0,'','Расчеты с подотчетными лицами по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720831000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению основных средств',0,'',0,'','Расчеты с подотчетными лицами по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720831560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720831660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720832000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению нематериальных активов',0,'',0,'','Расчеты с подотчетными лицами по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720832560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720832660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720834000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по приобретению материальных запасов',0,'',0,'','Расчеты с подотчетными лицами по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720834560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720834660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720860000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по социальному обеспечению',0,'',0,'','Расчеты с подотчетными лицами по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720861000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720861560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720861660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий и выплат по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720862000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению',0,'',0,'','Расчеты с подотчетными лицами по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720862560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720862660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пособий по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720863000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Расчеты с подотчетными лицами по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720863560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720863660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате пенсий, пособий, выплачиваемых организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720890000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по прочим расходам',0,'',0,'','Расчеты с подотчетными лицами по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720891000',0,'ПлСчет_Каз_2011',1,'Расчеты с подотчетными лицами по оплате прочих расходов',0,'',0,'','Расчеты с подотчетными лицами по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720891560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Увеличение дебиторской задолженности подотчетных лиц по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720891660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов',0,'',0,'','Уменьшение дебиторской задолженности подотчетных лиц по оплате прочих расходов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720900000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу имуществу',0,'',0,'','Расчеты по ущербу имуществу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720970000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу нефинансовым активам',0,'',0,'','Расчеты по ущербу нефинансовым активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720971000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу основным средствам',0,'',0,'','Расчеты по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720971560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Увеличение дебиторской задолженности по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720971660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу основным средствам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу основным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720972000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу  нематериальным активам',0,'',0,'','Расчеты по ущербу  нематериальным активам', '19000101','19000101',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 '720972560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу нематериальным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720972660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу нематериальным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу нематериальным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720973000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу непроизведенным активам',0,'',0,'','Расчеты по ущербу непроизведенным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720973560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Увеличение дебиторской задолженности по ущербу непроизведенным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720973660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу непроизведенным активам',0,'',0,'','Уменьшение дебиторской задолженности по ущербу непроизведенным активам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720974000',0,'ПлСчет_Каз_2011',1,'Расчеты по ущербу материальных запасов',0,'',0,'','Расчеты по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720974560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Увеличение дебиторской задолженности по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720974660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по ущербу материальных запасов',0,'',0,'','Уменьшение дебиторской задолженности по ущербу материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720980000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочему ущербу',0,'',0,'','Расчеты по прочему ущербу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720981000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам денежных средств',0,'',0,'','Расчеты по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720981560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Увеличение дебиторской задолженности по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720981660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам денежных средств',0,'',0,'','Уменьшение дебиторской задолженности по недостачам денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720982000',0,'ПлСчет_Каз_2011',1,'Расчеты по недостачам иных финансовых активов',0,'',0,'','Расчеты по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720982560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Увеличение дебиторской задолженности по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '720982660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по недостачам иных финансовых активов',0,'',0,'','Уменьшение дебиторской задолженности по недостачам иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721000000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с дебиторами',0,'',0,'','Прочие расчеты с дебиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721001000',0,'ПлСчет_Каз_2011',1,'Расчеты по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Расчеты по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721001560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Увеличение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721001660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам',0,'',0,'','Уменьшение дебиторской задолженности по НДС по приобретенным материальным ценностям, работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002100',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002110',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет налоговым доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002120',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от собственности',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002130',0,'ПлСчет_Каз_2011',1,'Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг',0,'',0,'','Расчеты  с финансовым органом по поступившим в бюджет доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002140',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002150',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты с финансовым органом по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002151',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты с финансовым органом по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002152',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты с финансовым органом по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002153',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты с финансовым органом по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002160',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002170',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002171',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002173',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002180',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступившим в бюджет прочим доходам',0,'',0,'','Расчеты с финансовым органом по поступившим в бюджет прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002400',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002410',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002420',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002430',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002440',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002600',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002620',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002630',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002640',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002650',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002700',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет от заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002710',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721002720',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований',0,'',0,'','Расчеты с финансовым органом по поступлениям в бюджет внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721003000',0,'ПлСчет_Каз_2011',1,'Расчеты с финансовым органом по наличным денежным средствам',0,'',0,'','Расчеты с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721003560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Увеличение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721003660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам',0,'',0,'','Уменьшение дебиторской задолженности по операциям с финансовым органом по наличным денежным средствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004000',0,'ПлСчет_Каз_2011',1,'Расчеты по распределенным поступлениям к зачислению в бюджет',0,'',0,'','Расчеты по распределенным поступлениям к зачислению в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004100',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам',0,'',0,'','Расчеты по поступившим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004110',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим налоговым доходам',0,'',0,'','Расчеты по поступившим налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004120',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от собственности',0,'',0,'','Расчеты по поступившим доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004130',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от оказания платных услуг',0,'',0,'','Расчеты по поступившим доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004140',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим суммам принудительного изъятия',0,'',0,'','Расчеты по поступившим суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004150',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004151',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004152',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004153',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004160',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по поступившим в бюджет страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004170',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от операций с активами',0,'',0,'','Расчеты по поступившим доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004171',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим доходам от переоценки активов',0,'',0,'','Расчеты по поступившим доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004180',0,'ПлСчет_Каз_2011',1,'Расчеты по поступившим прочим доходам',0,'',0,'','Расчеты по поступившим прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004400',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нефинансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004410',0,'ПлСчет_Каз_2011',1,'Расчет по поступлениям от выбытия основных средств',0,'',0,'','Расчет по поступлениям от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004420',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия нематериальных активов',0,'',0,'','Расчеты по поступлениям от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004430',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия непроизведенных активов',0,'',0,'','Расчеты по поступлениям от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004440',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия материальных запасов',0,'',0,'','Расчеты по поступлениям от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004600',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004610',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата депозитов',0,'',0,'','Расчеты по поступлениям от возврата депозитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004620',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия ценных бумаг, кроме акций',0,'',0,'','Расчеты по поступлениям от выбытия ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004630',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия акций и иных форм участия в капитале',0,'',0,'','Расчеты по поступлениям от выбытия акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004640',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от возврата бюджетных ссуд и кредитов',0,'',0,'','Расчеты по поступлениям от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004650',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от выбытия иных финансовых активов',0,'',0,'','Расчеты по поступлениям от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004700',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям от заимствований',0,'',0,'','Расчеты по поступлениям от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004710',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внутренних заимствований',0,'',0,'','Расчеты по поступлениям внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721004720',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлениям внешних заимствований',0,'',0,'','Расчеты по поступлениям внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721005000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими дебиторами',0,'',0,'','Расчеты с прочими дебиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721005560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих дебиторов',0,'',0,'','Увеличение дебиторской задолженности прочих дебиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721005660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих дебиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих дебиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721006000',0,'ПлСчет_Каз_2011',1,'Расчеты с учредителем',0,'',0,'','Расчеты с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721006560',0,'ПлСчет_Каз_2011',1,'Увеличение расчетов с учредителем',0,'',0,'','Увеличение расчетов с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721006660',0,'ПлСчет_Каз_2011',1,'Уменьшение расчетов с учредителем',0,'',0,'','Уменьшение расчетов с учредителем', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721100000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721100560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721100660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721200000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721200560',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение дебиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721200660',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721500000',0,'ПлСчет_Каз_2011',1,'Вложения в финансовые активы',0,'',0,'','Вложения в финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721520000',0,'ПлСчет_Каз_2011',1,'Вложения в ценные бумаги, кроме акций',0,'',0,'','Вложения в ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721521000',0,'ПлСчет_Каз_2011',1,'Вложения в облигации',0,'',0,'','Вложения в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721521520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в облигации',0,'',0,'','Увеличение вложений в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721521620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в облигации',0,'',0,'','Уменьшение вложений в облигации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721522000',0,'ПлСчет_Каз_2011',1,'Вложения в векселя',0,'',0,'','Вложения в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721522520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в векселя',0,'',0,'','Увеличение вложений в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721522620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в векселя',0,'',0,'','Уменьшение вложений в векселя', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721523000',0,'ПлСчет_Каз_2011',1,'Вложения в иные ценные бумаги, кроме акций',0,'',0,'','Вложения в иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721523520',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Увеличение вложений в иные ценные бумаги, кроме акций', '19000101','19000101',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 '721523620',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные ценные бумаги, кроме акций',0,'',0,'','Уменьшение вложений в иные ценные бумаги, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721530000',0,'ПлСчет_Каз_2011',1,'Вложения в акции и иные формы участия в капитале',0,'',0,'','Вложения в акции и иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721531000',0,'ПлСчет_Каз_2011',1,'Вложения в акции',0,'',0,'','Вложения в акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721531530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в акции',0,'',0,'','Увеличение вложений в акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721531630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в акции',0,'',0,'','Уменьшение вложений в акции', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721532000',0,'ПлСчет_Каз_2011',1,'Вложения  в государственные (муниципальные) предприятия',0,'',0,'','Вложения  в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721532530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) предприятия',0,'',0,'','Увеличение вложений в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721532630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) предприятия',0,'',0,'','Уменьшение вложений в государственные (муниципальные) предприятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721533000',0,'ПлСчет_Каз_2011',1,'Вложения в государственные (муниципальные) учреждения',0,'',0,'','Вложения в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721533530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в государственные (муниципальные) учреждения',0,'',0,'','Увеличение вложений в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721533630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в государственные (муниципальные) учреждения',0,'',0,'','Уменьшение вложений в государственные (муниципальные) учреждения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721534000',0,'ПлСчет_Каз_2011',1,'Вложения в иные формы участия в капитале',0,'',0,'','Вложения в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721534530',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в иные формы участия в капитале',0,'',0,'','Увеличение вложений в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721534630',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в иные формы участия в капитале',0,'',0,'','Уменьшение вложений в иные формы участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721550000',0,'ПлСчет_Каз_2011',1,'Вложения в иные финансовые активы',0,'',0,'','Вложения в иные финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721551000',0,'ПлСчет_Каз_2011',1,'Вложения в управляющие компании',0,'',0,'','Вложения в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721551550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в управляющие компании',0,'',0,'','Увеличение вложений в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721551650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в управляющие компании',0,'',0,'','Уменьшение вложений в управляющие компании', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721552000',0,'ПлСчет_Каз_2011',1,'Вложения в международные организации',0,'',0,'','Вложения в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721552550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в международные организации',0,'',0,'','Увеличение вложений в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721552650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в доли в международные организации',0,'',0,'','Уменьшение вложений в доли в международные организации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721553000',0,'ПлСчет_Каз_2011',1,'Вложения в прочие финансовые активы',0,'',0,'','Вложения в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721553550',0,'ПлСчет_Каз_2011',1,'Увеличение вложений в прочие финансовые активы',0,'',0,'','Увеличение вложений в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '721553650',0,'ПлСчет_Каз_2011',1,'Уменьшение вложений в прочие финансовые активы',0,'',0,'','Уменьшение вложений в прочие финансовые активы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730000000',0,'ПлСчет_Каз_2011',1,'ОБЯЗАТЕЛЬСТВА',0,'',0,'','ОБЯЗАТЕЛЬСТВА', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730100000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по долговым обязательствам',0,'',0,'','Расчеты с кредиторами по долговым обязательствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730110000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в рублях',0,'',0,'','Расчеты по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730111000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730111710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730111810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730112000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730112710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730112810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730113000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730113710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730113810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730114000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730114710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730114810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730120000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)',0,'',0,'','Расчеты по долговым обязательствам по целевым иностранным кредитам (заимствованиям)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730121000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730121710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730121810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730123000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730123720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730123820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730124000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730124720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Увеличение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730124820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','Уменьшение задолженности по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730130000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730131000',0,'ПлСчет_Каз_2011',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730131710',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730131810',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730133000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730133720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Увеличение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730133820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям',0,'',0,'','Уменьшение задолженности перед иными кредиторами по заимствованиям по государственным (муниципальным) гарантиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730140000',0,'ПлСчет_Каз_2011',1,'Расчеты по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730142000',0,'ПлСчет_Каз_2011',1,'Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Расчеты с кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730142720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Увеличение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730142820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте',0,'',0,'','Уменьшение задолженности перед кредиторами по государственным (муниципальным) ценным бумагам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730143000',0,'ПлСчет_Каз_2011',1,'Расчеты с иными кредиторами по  государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Расчеты с иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730143720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте',0,'',0,'','Увеличение задолженности перед иными кредиторами по государственному (муниципальному) долгу  в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730143820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте',0,'',0,'','Уменьшение задолженности перед иными кредиторами по государственному (муниципальному) долгу в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730144000',0,'ПлСчет_Каз_2011',1,'Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом',0,'',0,'','Расчеты по заимствованиям в иностранной валюте, не являющимся  государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730144720',0,'ПлСчет_Каз_2011',1,'Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Увеличение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730144820',0,'ПлСчет_Каз_2011',1,'Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом',0,'',0,'','Уменьшение задолженности по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730200000',0,'ПлСчет_Каз_2011',1,'Расчеты по принятым обязательствам',0,'',0,'','Расчеты по принятым обязательствам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730210000',0,'ПлСчет_Каз_2011',1,'Расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730211000',0,'ПлСчет_Каз_2011',1,'Расчеты по заработной плате',0,'',0,'','Расчеты по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730211730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по заработной плате',0,'',0,'','Увеличение кредиторской задолженности по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730211830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по заработной плате',0,'',0,'','Уменьшение кредиторской задолженности по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730212000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим выплатам',0,'',0,'','Расчеты по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730212730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим выплатам',0,'',0,'','Увеличение кредиторской задолженности по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730212830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим выплатам',0,'',0,'','Уменьшение кредиторской задолженности по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730213000',0,'ПлСчет_Каз_2011',1,'Расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730213730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730213830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730220000',0,'ПлСчет_Каз_2011',1,'Расчеты по  работам, услугам',0,'',0,'','Расчеты по  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730221000',0,'ПлСчет_Каз_2011',1,'Расчеты по услугам связи',0,'',0,'','Расчеты по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730221730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по услугам связи',0,'',0,'','Увеличение кредиторской задолженности по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730221830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по услугам связи',0,'',0,'','Уменьшение кредиторской задолженности по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730222000',0,'ПлСчет_Каз_2011',1,'Расчеты по транспортным услугам',0,'',0,'','Расчеты по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730222730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по транспортным услугам',0,'',0,'','Увеличение кредиторской задолженности по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730222830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по транспортным услугам',0,'',0,'','Уменьшение кредиторской задолженности по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730223000',0,'ПлСчет_Каз_2011',1,'Расчеты по коммунальным услугам',0,'',0,'','Расчеты по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730223730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по коммунальным услугам',0,'',0,'','Увеличение кредиторской задолженности по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730223830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по коммунальным услугам',0,'',0,'','Уменьшение кредиторской задолженности по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730224000',0,'ПлСчет_Каз_2011',1,'Расчеты по арендной плате за пользование имуществом',0,'',0,'','Расчеты по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730224730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Увеличение кредиторской задолженности по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730224830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по арендной плате за пользование имуществом',0,'',0,'','Уменьшение кредиторской задолженности по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730225000',0,'ПлСчет_Каз_2011',1,'Расчеты по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730225730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Увеличение кредиторской задолженности по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730225830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества',0,'',0,'','Уменьшение кредиторской задолженности по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730226000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим работам, услугам',0,'',0,'','Расчеты по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730226730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Увеличение кредиторской задолженности по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730226830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим работам, услугам',0,'',0,'','Уменьшение кредиторской задолженности по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730230000',0,'ПлСчет_Каз_2011',1,'Расчеты по поступлению нефинансовых активов',0,'',0,'','Расчеты по поступлению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730231000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению основных средств',0,'',0,'','Расчеты по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730231730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению основных средств',0,'',0,'','Увеличение кредиторской задолженности по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730231830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению основных средств',0,'',0,'','Уменьшение кредиторской задолженности по приобретению основных средств', '19000101','19000101',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 '730232000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению нематериальных активов',0,'',0,'','Расчеты по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730232730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730232830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению нематериальных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730233000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению непроизведенных активов',0,'',0,'','Расчеты по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730233730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730233830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению непроизведенных активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730234000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению материальных запасов',0,'',0,'','Расчеты по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730234730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Увеличение кредиторской задолженности по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730234830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению материальных запасов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730240000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730241000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730241730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730241830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730242000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730242730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Увеличение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730242830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Уменьшение кредиторской задолженности по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730250000',0,'ПлСчет_Каз_2011',1,'Расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730251000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730251730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Увеличение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730251830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730252000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730252730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Увеличение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730252830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730253000',0,'ПлСчет_Каз_2011',1,'Расчеты по перечислениям международным организациям',0,'',0,'','Расчеты по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730253730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Увеличение кредиторской задолженности по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730253830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по перечислениям международным организациям',0,'',0,'','Уменьшение кредиторской задолженности по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730260000',0,'ПлСчет_Каз_2011',1,'Расчеты по социальному обеспечению',0,'',0,'','Расчеты по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730261000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730261730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730261830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730262000',0,'ПлСчет_Каз_2011',1,'Расчеты по пособиям по социальной помощи населению',0,'',0,'','Расчеты по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730262730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Увеличение кредиторской задолженности по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730262830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пособиям по социальной помощи населению',0,'',0,'','Уменьшение кредиторской задолженности по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730263000',0,'ПлСчет_Каз_2011',1,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730263730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Увеличение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730263830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Уменьшение кредиторской задолженности по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730270000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг и по иным финансовым вложениям',0,'',0,'','Расчеты по приобретению ценных бумаг и по иным финансовым вложениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730272000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730272730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Увеличение кредиторской задолженности по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730272830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций',0,'',0,'','Уменьшение кредиторской задолженности по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730273000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению акций и по иным формам  участия в капитале',0,'',0,'','Расчеты по приобретению акций и по иным формам  участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730273730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Увеличение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730273830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале',0,'',0,'','Уменьшение кредиторской задолженности по приобретению акций и по иным формам участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730275000',0,'ПлСчет_Каз_2011',1,'Расчеты по приобретению иных финансовых активов',0,'',0,'','Расчеты по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730275730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Увеличение кредиторской задолженности по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730275830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по приобретению иных финансовых активов',0,'',0,'','Уменьшение кредиторской задолженности по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730290000',0,'ПлСчет_Каз_2011',1,'Расчеты по  прочим расходам',0,'',0,'','Расчеты по  прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730291000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим расходам',0,'',0,'','Расчеты по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730291730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим расходам',0,'',0,'','Увеличение кредиторской задолженности по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730291830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим расходам',0,'',0,'','Уменьшение кредиторской задолженности по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730300000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам в бюджеты',0,'',0,'','Расчеты по платежам в бюджеты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730301000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на доходы физических лиц',0,'',0,'','Расчеты по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730301730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Увеличение кредиторской задолженности по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730301830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на доходы физических лиц',0,'',0,'','Уменьшение кредиторской задолженности по налогу на доходы физических лиц', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730302000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730302730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730302830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730303000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на прибыль организаций',0,'',0,'','Расчеты по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730303730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730303830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на прибыль организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на прибыль организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730304000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на добавленную стоимость',0,'',0,'','Расчеты по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730304730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Увеличение кредиторской задолженности по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730304830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на добавленную стоимость',0,'',0,'','Уменьшение кредиторской задолженности по налогу на добавленную стоимость', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730305000',0,'ПлСчет_Каз_2011',1,'Расчеты по прочим платежам в бюджет',0,'',0,'','Расчеты по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730305730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Увеличение кредиторской задолженности по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730305830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по прочим платежам в бюджет',0,'',0,'','Уменьшение кредиторской задолженности по прочим платежам в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730306000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730306730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Увеличение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730306830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний',0,'',0,'','Уменьшение кредиторской задолженности по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730307000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730307730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730307830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в Федеральный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730308000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730308730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730308830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное медицинское страхование в территориальный ФОМС', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730309000',0,'ПлСчет_Каз_2011',1,'Расчеты по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Расчеты по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730309730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Увеличение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730309830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование',0,'',0,'','Уменьшение кредиторской задолженности по дополнительным страховым взносам на пенсионное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730310000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730310730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730310830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730311000',0,'ПлСчет_Каз_2011',1,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730311730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Увеличение кредиторской задолженности  по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730311830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии',0,'',0,'','Уменьшение кредиторской задолженности  по  страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730312000',0,'ПлСчет_Каз_2011',1,'Расчеты по налогу на имущество организаций',0,'',0,'','Расчеты по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730312730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Увеличение кредиторской задолженности по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730312830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по налогу на имущество организаций',0,'',0,'','Уменьшение кредиторской задолженности по налогу на имущество организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730313000',0,'ПлСчет_Каз_2011',1,'Расчеты по земельному налогу',0,'',0,'','Расчеты по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730313730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по земельному налогу',0,'',0,'','Увеличение кредиторской задолженности по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730313830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по земельному налогу',0,'',0,'','Уменьшение кредиторской задолженности по земельному налогу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730400000',0,'ПлСчет_Каз_2011',1,'Прочие расчеты с кредиторами',0,'',0,'','Прочие расчеты с кредиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730401000',0,'ПлСчет_Каз_2011',1,'Расчеты по средствам, полученным во временное распоряжение',0,'',0,'','Расчеты по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730401730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Увеличение кредиторской задолженности по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730401830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение',0,'',0,'','Уменьшение кредиторской задолженности по средствам, полученным во временное распоряжение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730402000',0,'ПлСчет_Каз_2011',1,'Расчеты с депонентами',0,'',0,'','Расчеты с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730402730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Увеличение кредиторской задолженности по расчетам с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730402830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по расчетам с депонентами',0,'',0,'','Уменьшение кредиторской задолженности по расчетам с депонентами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730403000',0,'ПлСчет_Каз_2011',1,'Расчеты по удержаниям из выплат  по оплате труда',0,'',0,'','Расчеты по удержаниям из выплат  по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730403730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Увеличение кредиторской задолженности по удержаниям из выплат по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730403830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда',0,'',0,'','Уменьшение кредиторской задолженности по удержаниям из выплат по оплате труда', '19000101','19000101',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 '730404000',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты',0,'',0,'','Внутриведомственные расчеты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404100',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам',0,'',0,'','Внутриведомственные расчеты по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404110',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по налоговым доходам',0,'',0,'','Внутриведомственные расчеты по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404120',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от собственности',0,'',0,'','Внутриведомственные расчеты по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404130',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от оказания платных услуг',0,'',0,'','Внутриведомственные расчеты по доходам от оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404140',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам по суммам принудительного изъятия',0,'',0,'','Внутриведомственные расчеты по доходам по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404160',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование',0,'',0,'','Внутриведомственные расчеты по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404173',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным доходам от операций с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404180',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим доходам',0,'',0,'','Внутриведомственные расчеты по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404200',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по расходам',0,'',0,'','Внутриведомственные расчеты по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404210',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404211',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по заработной плате',0,'',0,'','Внутриведомственные расчеты по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404212',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим выплатам',0,'',0,'','Внутриведомственные расчеты по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404213',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по начислениям на выплаты по оплате труда',0,'',0,'','Внутриведомственные расчеты по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404220',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по оплате работ, услуг',0,'',0,'','Внутриведомственные расчеты по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404221',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по услугам связи',0,'',0,'','Внутриведомственные расчеты по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404222',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по транспортным услугам',0,'',0,'','Внутриведомственные расчеты по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404223',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по коммунальным услугам',0,'',0,'','Внутриведомственные расчеты по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404224',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по арендной плате за пользование имуществом',0,'',0,'','Внутриведомственные расчеты по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404225',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по работам, услугам по содержанию имущества',0,'',0,'','Внутриведомственные расчеты по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404226',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим работам, услугам',0,'',0,'','Внутриведомственные расчеты по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404230',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404231',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внутреннего долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404232',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по обслуживанию внешнего государственного долга',0,'',0,'','Внутриведомственные расчеты по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404240',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404241',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404242',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404250',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по безвозмездным перечислениям бюджетам',0,'',0,'','Внутриведомственные расчеты по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404251',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Внутриведомственные расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404252',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404253',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по перечислениям международным организациям',0,'',0,'','Внутриведомственные расчеты по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404260',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по социальному обеспечению',0,'',0,'','Внутриведомственные расчеты по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404261',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404262',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пособиям по социальной помощи населению',0,'',0,'','Внутриведомственные расчеты по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404263',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404273',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами',0,'',0,'','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404290',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по прочим расходам',0,'',0,'','Внутриведомственные расчеты по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404300',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404310',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению основных средств',0,'',0,'','Внутриведомственные расчеты по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404320',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению нематериальных активов',0,'',0,'','Внутриведомственные расчеты по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404330',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404340',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по приобретению материальных запасов',0,'',0,'','Внутриведомственные расчеты по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404400',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытий нефинансовых активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытий нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404410',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия основных средств',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404420',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия нематериальных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404430',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия непроизведенных активов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404440',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по доходам от выбытия материальных запасов',0,'',0,'','Внутриведомственные расчеты по доходам от выбытия материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404500',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404510',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404520',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по поступлению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404530',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале',0,'',0,'','Внутриведомственные расчеты по поступлению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404540',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)',0,'',0,'','Внутриведомственные расчеты по увеличению предоставлению кредитов, займов (ссуд)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404550',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлению иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404560',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей дебиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404600',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404610',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств',0,'',0,'','Внутриведомственные расчеты по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404620',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций',0,'',0,'','Внутриведомственные расчеты по выбытию ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404630',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал',0,'',0,'','Внутриведомственные расчеты по выбытию акций и иных форм участия в капитал', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404640',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов',0,'',0,'','Внутриведомственные расчеты по выбытию бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404650',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по выбытию иных финансовых активов',0,'',0,'','Внутриведомственные расчеты по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404660',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей дебиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404700',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению обязательств',0,'',0,'','Внутриведомственные расчеты по увеличению обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404710',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внутренних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внутренних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404720',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по поступлениям внешних заимствований',0,'',0,'','Внутриведомственные расчеты по поступлениям внешних заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404730',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по увеличению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по увеличению прочей кредиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404800',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению обязательств',0,'',0,'','Внутриведомственные расчеты по уменьшению обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404810',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внутреннему долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404820',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу',0,'',0,'','Внутриведомственные расчеты по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404830',0,'ПлСчет_Каз_2011',1,'Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности',0,'',0,'','Внутриведомственные расчеты по уменьшению прочей кредиторской задолженности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405000',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405210',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405211',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по заработной плате',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405212',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим выплатам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405213',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405220',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405221',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по услугам связи',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405222',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по транспортным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405223',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405224',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405225',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405226',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405230',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405231',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405232',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405240',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405241',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405242',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405250',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405251',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405252',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405253',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405260',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405261',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405262',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405263',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405270',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405273',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405290',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по прочим расходам',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405300',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405310',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению основных средств', '19000101','19000101',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 '730405320',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405330',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405340',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405500',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405510',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по размещению средств бюджета на депозиты', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405520',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405530',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405540',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405550',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405800',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405810',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405820',0,'ПлСчет_Каз_2011',1,'Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу',0,'',0,'','Расчеты по платежам из бюджета с финансовым органом по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730406000',0,'ПлСчет_Каз_2011',1,'Расчеты с прочими кредиторами',0,'',0,'','Расчеты с прочими кредиторами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730406730',0,'ПлСчет_Каз_2011',1,'Увеличение дебиторской задолженности прочих кредиторов',0,'',0,'','Увеличение дебиторской задолженности прочих кредиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730406830',0,'ПлСчет_Каз_2011',1,'Уменьшение дебиторской задолженности прочих кредиторов',0,'',0,'','Уменьшение дебиторской задолженности прочих кредиторов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730600000',0,'ПлСчет_Каз_2011',1,'Расчеты по выплате наличных денег',0,'',0,'','Расчеты по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730600730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по выплате наличных денег',0,'',0,'','Увеличение кредиторской задолженности по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730600830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по выплате наличных денег',0,'',0,'','Уменьшение кредиторской задолженности по выплате наличных денег', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730700000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730710000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712110',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712151',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712160',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по страховым взносам на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712251',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712261',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджета в органах Федерального казначейства по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по заимствованиям в виде внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730712820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу',0,'',0,'','Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по погашению задолженности по внешнему  государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений',0,'',0,'','Расчеты по операциям бюджетных учреждений', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям бюджетных учреждений по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим доходам', '19000101','19000101',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 '730713200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заработной плате',0,'',0,'','Расчеты по операциям бюджетных учреждений по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям бюджетных учреждений по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям бюджетных учреждений по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по услугам связи',0,'',0,'','Расчеты по операциям бюджетных учреждений по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям бюджетных учреждений по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям бюджетных учреждений по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям бюджетных учреждений по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям бюджетных учреждений по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям бюджетных учреждений по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям бюджетных учреждений по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям бюджетных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям бюджетных учреждений по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям бюджетных учреждений по предоставлению заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям бюджетных учреждений по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям бюджетных учреждений по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям бюджетных учреждений по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям бюджетных учреждений выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям по лицевым счетам бюджетных учреждений по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730713820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям бюджетных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений',0,'',0,'','Расчеты по операциям автономных учреждений', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам',0,'',0,'','Расчеты по операциям автономных учреждений по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от собственности',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям автономных учреждений по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям автономных учреждений по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от операций с активами',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по доходам от переоценки активов',0,'',0,'','Расчеты по операциям автономных учреждений по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим доходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по расходам',0,'',0,'','Расчеты по операциям автономных учреждений по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заработной плате',0,'',0,'','Расчеты по операциям автономных учреждений по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим выплатам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям автономных учреждений по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по оплате работ, услуг',0,'',0,'','Расчеты по операциям автономных учреждений по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по услугам связи',0,'',0,'','Расчеты по операциям автономных учреждений по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по транспортным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по коммунальным услугам',0,'',0,'','Расчеты по операциям автономных учреждений по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям автономных учреждений по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям автономных учреждений по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим работам, услугам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям автономных учреждений по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по перечислениям международным организациям',0,'',0,'','Расчеты по операциям автономных учреждений по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по социальному обеспечению',0,'',0,'','Расчеты по операциям автономных учреждений по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям автономных учреждений по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям автономных учреждений по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по прочим расходам',0,'',0,'','Расчеты по операциям автономных учреждений по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию основных средств',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию материальных запасов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению финансовых активов', '19000101','19000101',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 '730714510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по предоставлению заимствований',0,'',0,'','Расчеты по операциям автономных учреждений по предоставлению заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям автономных учреждений по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям автономных учреждений по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов',0,'',0,'','Расчеты по операциям автономных учреждений по возврату бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям автономных учреждений по выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по долговым заимствованиям',0,'',0,'','Расчеты по операциям автономных учреждений по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению долговых обязательств',0,'',0,'','Расчеты по операциям автономных учреждений по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730714820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям автономных учреждений по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715000',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций',0,'',0,'','Расчеты по операциям иных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715100',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам',0,'',0,'','Расчеты по операциям иных организаций по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715120',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от собственности',0,'',0,'','Расчеты по операциям иных организаций по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715130',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от оказания  платных услуг',0,'',0,'','Расчеты по операциям иных организаций по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715140',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по суммам принудительного изъятия',0,'',0,'','Расчеты по операциям иных организаций по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715150',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным поступлениям от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715152',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по поступлениям от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715153',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций',0,'',0,'','Расчеты по операциям по лицевым счетам иных организаций по поступлениям от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715170',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от операций с активами',0,'',0,'','Расчеты по операциям иных организаций по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715171',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по доходам от переоценки активов',0,'',0,'','Расчеты по операциям иных организаций по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715180',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим доходам',0,'',0,'','Расчеты по операциям иных организаций по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715200',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по расходам',0,'',0,'','Расчеты по операциям иных организаций по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715210',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715211',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заработной плате',0,'',0,'','Расчеты по операциям иных организаций по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715212',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим выплатам',0,'',0,'','Расчеты по операциям иных организаций по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715213',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда',0,'',0,'','Расчеты по операциям иных организаций по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715220',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по оплате работ, услуг',0,'',0,'','Расчеты по операциям иных организаций по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715221',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по услугам связи',0,'',0,'','Расчеты по операциям иных организаций по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715222',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по транспортным услугам',0,'',0,'','Расчеты по операциям иных организаций по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715223',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по коммунальным услугам',0,'',0,'','Расчеты по операциям иных организаций по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715224',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по арендной плате за пользование имуществом',0,'',0,'','Расчеты по операциям иных организаций по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715225',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по работам, услугам по содержанию имущества',0,'',0,'','Расчеты по операциям иных организаций по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715226',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим работам, услугам',0,'',0,'','Расчеты по операциям иных организаций по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715230',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715231',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в рублях',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715232',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по обслуживанию заимствований в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715240',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715241',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715242',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715250',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам',0,'',0,'','Расчеты по операциям иных организаций по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715252',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расчеты по операциям иных организаций по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715253',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по перечислениям международным организациям',0,'',0,'','Расчеты по операциям иных организаций по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715260',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по социальному обеспечению',0,'',0,'','Расчеты по операциям иных организаций по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715262',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пособиям по социальной помощи населению',0,'',0,'','Расчеты по операциям иных организаций по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715263',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Расчеты по операциям иных организаций по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715290',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по прочим расходам',0,'',0,'','Расчеты по операциям иных организаций по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715300',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715310',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению основных средств',0,'',0,'','Расчеты по операциям иных организаций по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715320',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715330',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715340',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715400',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нефинансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715410',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию основных средств',0,'',0,'','Расчеты по операциям иных организаций по выбытию основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715420',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию нематериальных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715430',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию непроизведенных активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715440',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию материальных запасов',0,'',0,'','Расчеты по операциям иных организаций по выбытию материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715500',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715510',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (увеличению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715520',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715530',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715540',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по предоставлению заимствований',0,'',0,'','Расчеты по операциям иных организаций по предоставлению заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715550',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по поступлению иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715600',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по выбытию финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по выбытию финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715610',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств',0,'',0,'','Расчеты по операциям иных организаций по изменению (уменьшению) остатков денежных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715620',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций',0,'',0,'','Расчеты по операциям иных организаций по реализации ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715630',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале',0,'',0,'','Расчеты по операциям иных организаций по реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715640',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по возврату заимствований',0,'',0,'','Расчеты по операциям иных организаций по возврату заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715650',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по  выбытию иных финансовых активов',0,'',0,'','Расчеты по операциям иных организаций по  выбытию иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715700',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по долговым заимствованиям',0,'',0,'','Расчеты по операциям иных организаций по долговым заимствованиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715710',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в рублях',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715720',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по заимствованиям в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по заимствованиям в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715800',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению долговых обязательств',0,'',0,'','Расчеты по операциям иных организаций по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715810',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в рублях', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730715820',0,'ПлСчет_Каз_2011',1,'Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте',0,'',0,'','Расчеты по операциям иных организаций по погашению задолженности по долговым обязательствам в иностранной валюте', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730800000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по поступлениям',0,'',0,'','Внутренние расчеты по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730800730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730800830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730900000',0,'ПлСчет_Каз_2011',1,'Внутренние расчеты по выбытиям',0,'',0,'','Внутренние расчеты по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730900730',0,'ПлСчет_Каз_2011',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Увеличение кредиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730900830',0,'ПлСчет_Каз_2011',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740000000',0,'ПлСчет_Каз_2011',1,'ФИНАНСОВЫЙ РЕЗУЛЬТАТ',0,'',0,'','ФИНАНСОВЫЙ РЕЗУЛЬТАТ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740100000',0,'ПлСчет_Каз_2011',1,'Финансовый результат хозяйствующего субъекта',0,'',0,'','Финансовый результат хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110000',0,'ПлСчет_Каз_2011',1,'Доходы текущего финансового года',0,'',0,'','Доходы текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110100',0,'ПлСчет_Каз_2011',1,'Доходы хозяйствующего субъекта',0,'',0,'','Доходы хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110110',0,'ПлСчет_Каз_2011',1,'Налоговые доходы',0,'',0,'','Налоговые доходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110120',0,'ПлСчет_Каз_2011',1,'Доходы от собственности',0,'',0,'','Доходы от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110130',0,'ПлСчет_Каз_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','Доходы от  оказания платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110140',0,'ПлСчет_Каз_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','Доходы от сумм принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110150',0,'ПлСчет_Каз_2011',1,'Доходы от безвозмездных поступлений от бюджетов',0,'',0,'','Доходы от безвозмездных поступлений от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110151',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110152',0,'ПлСчет_Каз_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','Доходы от поступлений от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110153',0,'ПлСчет_Каз_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','Доходы от поступления от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110160',0,'ПлСчет_Каз_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','Доходы от страховых взносов на обязательное социальное страхование', '19000101','19000101',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 '740110170',0,'ПлСчет_Каз_2011',1,'Доходы по операциям с активами',0,'',0,'','Доходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110171',0,'ПлСчет_Каз_2011',1,'Доходы от переоценки активов',0,'',0,'','Доходы от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110172',0,'ПлСчет_Каз_2011',1,'Доходы от операций с активами',0,'',0,'','Доходы от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110173',0,'ПлСчет_Каз_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','Чрезвычайные доходы от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110180',0,'ПлСчет_Каз_2011',1,'Прочие доходы',0,'',0,'','Прочие доходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120000',0,'ПлСчет_Каз_2011',1,'Расходы текущего финансового года',0,'',0,'','Расходы текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120200',0,'ПлСчет_Каз_2011',1,'Расходы хозяйствующего субъекта',0,'',0,'','Расходы хозяйствующего субъекта', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120210',0,'ПлСчет_Каз_2011',1,'Расходы по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Расходы по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120211',0,'ПлСчет_Каз_2011',1,'Расходы по заработной плате',0,'',0,'','Расходы по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120212',0,'ПлСчет_Каз_2011',1,'Расходы по прочим выплатам',0,'',0,'','Расходы по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120213',0,'ПлСчет_Каз_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','Расходы на начисления на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120220',0,'ПлСчет_Каз_2011',1,'Расходы на оплату работ, услуг',0,'',0,'','Расходы на оплату работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120221',0,'ПлСчет_Каз_2011',1,'Расходы на услуги связи',0,'',0,'','Расходы на услуги связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120222',0,'ПлСчет_Каз_2011',1,'Расходы на транспортные услуги',0,'',0,'','Расходы на транспортные услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120223',0,'ПлСчет_Каз_2011',1,'Расходы на коммунальные услуги',0,'',0,'','Расходы на коммунальные услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120224',0,'ПлСчет_Каз_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','Расходы на арендную плату за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120225',0,'ПлСчет_Каз_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','Расходы на работы, услуги по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120226',0,'ПлСчет_Каз_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','Расходы на прочие работы, услуги', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120230',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание государственного (муниципального)  долга',0,'',0,'','Расходы на обслуживание государственного (муниципального)  долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120231',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','Расходы на обслуживание внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120232',0,'ПлСчет_Каз_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','Расходы на обслуживание внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120240',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям',0,'',0,'','Расходы на безвозмездные перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120241',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','Расходы на безвозмездные перечисления государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120242',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120250',0,'ПлСчет_Каз_2011',1,'Расходы на безвозмездные перечисления бюджетам',0,'',0,'','Расходы на безвозмездные перечисления бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120251',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120252',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','Расходы на перечисления наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120253',0,'ПлСчет_Каз_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','Расходы на перечисления международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120260',0,'ПлСчет_Каз_2011',1,'Расходы на социальное обеспечение',0,'',0,'','Расходы на социальное обеспечение', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120261',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120262',0,'ПлСчет_Каз_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','Расходы на пособия по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120263',0,'ПлСчет_Каз_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120270',0,'ПлСчет_Каз_2011',1,'Расходы по операциям с активами',0,'',0,'','Расходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120271',0,'ПлСчет_Каз_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','Расходы на амортизацию основных средств и нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120272',0,'ПлСчет_Каз_2011',1,'Расходование материальных запасов',0,'',0,'','Расходование материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120273',0,'ПлСчет_Каз_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','Чрезвычайные расходы по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120290',0,'ПлСчет_Каз_2011',1,'Прочие расходы',0,'',0,'','Прочие расходы', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740130000',0,'ПлСчет_Каз_2011',1,'Финансовый результат прошлых отчетных периодов',0,'',0,'','Финансовый результат прошлых отчетных периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740140000',0,'ПлСчет_Каз_2011',1,'Доходы будущих периодов',0,'',0,'','Доходы будущих периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740150000',0,'ПлСчет_Каз_2011',1,'Расходы будущих периодов',0,'',0,'','Расходы будущих периодов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740200000',0,'ПлСчет_Каз_2011',1,'Результат по кассовым операциям бюджета',0,'',0,'','Результат по кассовым операциям бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по поступлениям в бюджет',0,'',0,'','Результат по кассовому исполнению бюджета по поступлениям в бюджет', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210100',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам',0,'',0,'','Поступления в бюджет по доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210110',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по налоговым доходам',0,'',0,'','Поступления в бюджет по налоговым доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210120',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от собственности',0,'',0,'','Поступления в бюджет по доходам от собственности', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210130',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от оказания  платных услуг',0,'',0,'','Поступления в бюджет по доходам от оказания  платных услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210140',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по суммам принудительного изъятия',0,'',0,'','Поступления в бюджет по суммам принудительного изъятия', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210150',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет безвозмездных поступлений от бюджетов',0,'',0,'','Поступления в бюджет безвозмездных поступлений от бюджетов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210151',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210152',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств',0,'',0,'','Поступления в бюджет от наднациональных организаций и правительств иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210153',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от международных финансовых организаций',0,'',0,'','Поступления в бюджет от международных финансовых организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210160',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет страховых взносов на обязательное социальное страхование',0,'',0,'','Поступления в бюджет страховых взносов на обязательное социальное страхование', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210170',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от операций с активами',0,'',0,'','Поступления в бюджет по доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210171',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по доходам от переоценки активов',0,'',0,'','Поступления в бюджет по доходам от переоценки активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210173',0,'ПлСчет_Каз_2011',1,'Поступление в бюджет по чрезвычайным доходам от операций с активами',0,'',0,'','Поступление в бюджет по чрезвычайным доходам от операций с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210180',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет по прочим доходам',0,'',0,'','Поступления в бюджет по прочим доходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210400',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нефинансовых активов',0,'',0,'','Поступления в бюджет от реализации нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210410',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации основных средств',0,'',0,'','Поступления в бюджет от реализации основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210420',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации нематериальных активов',0,'',0,'','Поступления в бюджет от реализации нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210430',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации непроизведенных активов',0,'',0,'','Поступления в бюджет от реализации непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210440',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации материальных запасов',0,'',0,'','Поступления в бюджет от реализации материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210600',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия финансовых активов',0,'',0,'','Поступления в бюджет от выбытия финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210620',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210630',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от реализации акций и иных форм участия в капитале',0,'',0,'','Поступления в бюджет от реализации акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210640',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от возврата бюджетных ссуд и кредитов',0,'',0,'','Поступления в бюджет от возврата бюджетных ссуд и кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210650',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от выбытия иных финансовых активов',0,'',0,'','Поступления в бюджет от выбытия иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210700',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований',0,'',0,'','Поступления в бюджет от заимствований', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210710',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внутреннего долга',0,'',0,'','Поступления в бюджет от заимствований в виде внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740210720',0,'ПлСчет_Каз_2011',1,'Поступления в бюджет от заимствований в виде внешнего государственного долга',0,'',0,'','Поступления в бюджет от заимствований в виде внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220000',0,'ПлСчет_Каз_2011',1,'Результат по кассовому исполнению бюджета по выбытиям из бюджета',0,'',0,'','Результат по кассовому исполнению бюджета по выбытиям из бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220200',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам',0,'',0,'','Выбытия средств бюджета по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220210',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220211',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по заработной плате',0,'',0,'','Выбытия средств бюджета по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220212',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим выплатам',0,'',0,'','Выбытия средств бюджета по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220213',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по начислениям на выплаты по оплате труда',0,'',0,'','Выбытия средств бюджета по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220220',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по оплате работ, услуг',0,'',0,'','Выбытия средств бюджета по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220221',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по услугам связи',0,'',0,'','Выбытия средств бюджета по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220222',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по транспортным услугам',0,'',0,'','Выбытия средств бюджета по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220223',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по коммунальным услугам',0,'',0,'','Выбытия средств бюджета по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220224',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по арендной плате за пользование имуществом',0,'',0,'','Выбытия средств бюджета по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220225',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по работам, услугам по содержанию имущества',0,'',0,'','Выбытия средств бюджета по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220226',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим работам, услугам',0,'',0,'','Выбытия средств бюджета по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220230',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию государственного (муниципального) долга',0,'',0,'','Выбытия средств бюджета по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220231',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внутреннего долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220232',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по обслуживанию внешнего государственного долга',0,'',0,'','Выбытия средств бюджета по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220240',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220241',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220242',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220250',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по безвозмездным перечислениям бюджетам',0,'',0,'','Выбытия средств бюджета по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220251',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220252',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220253',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по перечислениям международным организациям',0,'',0,'','Выбытия средств бюджета по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220260',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по социальному обеспечению',0,'',0,'','Выбытия средств бюджета по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220261',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220262',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пособиям по социальной помощи населению',0,'',0,'','Выбытия средств бюджета по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220263',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220270',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220273',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами',0,'',0,'','Выбытия средств бюджета по чрезвычайным расходам по операциям с активами', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220290',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по прочим расходам',0,'',0,'','Выбытия средств бюджета по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220300',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению нефинансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению нефинансовых активов', '19000101','19000101',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 '740220310',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению основных средств',0,'',0,'','Выбытия средств бюджета по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220320',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению нематериальных активов',0,'',0,'','Выбытия средств бюджета по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220330',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению непроизведенных активов',0,'',0,'','Выбытия средств бюджета по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220340',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению материальных запасов',0,'',0,'','Выбытия средств бюджета по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220500',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению финансовых активов',0,'',0,'','Выбытия средств бюджета по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220520',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций',0,'',0,'','Выбытия средств бюджета по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220530',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале',0,'',0,'','Выбытия средств бюджета по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220540',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по предоставлению бюджетных кредитов',0,'',0,'','Выбытия средств бюджета по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220550',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по поступлению иных финансовых активов',0,'',0,'','Выбытия средств бюджета по поступлению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220800',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению долговых обязательств',0,'',0,'','Выбытия средств бюджета по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220810',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740220820',0,'ПлСчет_Каз_2011',1,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу',0,'',0,'','Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740230000',0,'ПлСчет_Каз_2011',1,'Результат прошлых отчетных периодов по кассовому исполнению бюджета',0,'',0,'','Результат прошлых отчетных периодов по кассовому исполнению бюджета', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750000000',0,'ПлСчет_Каз_2011',1,'САНКЦИОНИРОВАНИЕ РАСХОДОВ',0,'',0,'','САНКЦИОНИРОВАНИЕ РАСХОДОВ', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750100000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств',0,'',0,'','Лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101000',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств',0,'',0,'','Доведенные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101200',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101210',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101211',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Доведенные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101212',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101213',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101220',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Доведенные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101221',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Доведенные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101222',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101223',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101224',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Доведенные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101225',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Доведенные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101226',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101230',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101231',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101232',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101240',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101241',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101242',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101250',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101251',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101252',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101253',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Доведенные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101260',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Доведенные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101261',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101262',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Доведенные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101263',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления',0,'',0,'','Доведенные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациям сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101290',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Доведенные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101300',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101310',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101320',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101330',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101340',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101500',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101530',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750101550',0,'ПлСчет_Каз_2011',1,'Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов',0,'',0,'','Доведенные лимиты бюджетных обязательств по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств к распределению',0,'',0,'','Лимиты бюджетных обязательств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате труда и начислениям на  выплаты по  оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по заработной плате к распределению',0,'',0,'','Лимиты бюджетных обязательств по заработной плате к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим выплатам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим выплатам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Лимиты бюджетных обязательств по начислениям на выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по оплате работ, услуг к распределению',0,'',0,'','Лимиты бюджетных обязательств по оплате работ, услуг к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по услугам связи к распределению',0,'',0,'','Лимиты бюджетных обязательств по услугам связи к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по транспортным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по транспортным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по коммунальным услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по коммунальным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению',0,'',0,'','Лимиты бюджетных обязательств по арендной плате за пользование имуществом к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению',0,'',0,'','Лимиты бюджетных обязательств по работам,  услугам по содержанию имущества к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим работам, услугам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим работам, услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внутреннего долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Лимиты бюджетных обязательств по обслуживанию внешнего государственного долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по перечислениям международным организациям к распределению',0,'',0,'','Лимиты бюджетных обязательств по перечислениям международным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по социальному обеспечению к распределению',0,'',0,'','Лимиты бюджетных обязательств по социальному обеспечению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению',0,'',0,'','Лимиты бюджетных обязательств по пособиям по социальной помощи населению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по прочим расходам к распределению',0,'',0,'','Лимиты бюджетных обязательств по прочим расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нефинансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению основных средств к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению основных средств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению нематериальных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению непроизведенных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению материальных запасов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению материальных запасов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению финансовых активов к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750102530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию государственного  (муниципального) долга', '19000101','19000101',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 '750103231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по обслуживанию внешнего  государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750103530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств получателей бюджетных средств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104000',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств',0,'',0,'','Переданные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104200',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104210',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104211',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Переданные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104212',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104213',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда',0,'',0,'','Переданные лимиты бюджетных обязательств по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104220',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Переданные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104221',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Переданные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104222',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104223',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104224',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Переданные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104225',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Переданные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104226',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104230',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104231',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104232',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга',0,'',0,'','Переданные лимиты бюджетных обязательств по обслуживанию внешнего государственного  долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104240',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104241',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104242',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104250',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104251',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104252',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104253',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Переданные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104260',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Переданные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104261',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104262',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Переданные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104263',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104290',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Переданные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104300',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104310',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104320',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104330',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104340',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104500',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750104530',0,'ПлСчет_Каз_2011',1,'Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105000',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств',0,'',0,'','Полученные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105200',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105210',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105211',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Полученные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105212',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105213',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Полученные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105220',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Полученные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105221',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Полученные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105222',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105223',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по коммунальным услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105224',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Полученные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105225',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Полученные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105226',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105230',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105231',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105232',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Полученные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105240',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105241',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105242',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105250',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105251',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105252',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105253',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Полученные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105260',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Полученные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105261',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105262',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Полученные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105263',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105290',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Полученные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105300',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105310',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105320',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105330',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105340',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105500',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750105530',0,'ПлСчет_Каз_2011',1,'Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути',0,'',0,'','Лимиты бюджетных обязательств в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106200',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106210',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106211',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по заработной плате',0,'',0,'','Лимиты бюджетных обязательств в пути по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106212',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим выплатам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106213',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда',0,'',0,'','Лимиты бюджетных обязательств в пути по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106220',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по оплате работ,  услуг',0,'',0,'','Лимиты бюджетных обязательств в пути по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106221',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по услугам связи',0,'',0,'','Лимиты бюджетных обязательств в пути по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106222',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по транспортным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по транспортным услугам', '19000101','19000101',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 '750106223',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по коммунальным услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106224',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом',0,'',0,'','Лимиты бюджетных обязательств в пути по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106225',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества',0,'',0,'','Лимиты бюджетных обязательств в пути по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106226',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим работам,  услугам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим работам,  услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106230',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106231',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106232',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга',0,'',0,'','Лимиты бюджетных обязательств в пути по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106240',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106241',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106242',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106250',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Лимиты бюджетных обязательств в пути по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106251',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106252',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106253',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по перечислениям международным организациям',0,'',0,'','Лимиты бюджетных обязательств в пути по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106260',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по социальному обеспечению',0,'',0,'','Лимиты бюджетных обязательств в пути по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106261',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106262',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению',0,'',0,'','Лимиты бюджетных обязательств в пути по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106263',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Лимиты бюджетных обязательств в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106290',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по прочим расходам',0,'',0,'','Лимиты бюджетных обязательств в пути по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106300',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106310',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению основных средств',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106320',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению нематериальных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106330',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106340',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению материальных запасов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106500',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению финансовых активов',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750106530',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Лимиты бюджетных обязательств в пути по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109000',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств',0,'',0,'','Утвержденные лимиты бюджетных обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109200',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109210',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109211',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по заработной плате',0,'',0,'','Утвержденные лимиты бюджетных обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109212',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим выплатам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109213',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные лимиты бюджетных обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109220',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по оплате работ, услуг',0,'',0,'','Утвержденные лимиты бюджетных обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109221',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по услугам связи',0,'',0,'','Утвержденные лимиты бюджетных обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109222',0,'ПлСчет_Каз_2011',1,'Утверждены лимиты бюджетных обязательств по транспортным услугам',0,'',0,'','Утверждены лимиты бюджетных обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109223',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств  по коммунальным услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств  по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109224',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом',0,'',0,'','Утвержденные лимиты бюджетных обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109225',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные лимиты бюджетных обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109226',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим работам, услугам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109230',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109231',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109232',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга',0,'',0,'','Утвержденные лимиты бюджетных обязательств по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109240',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109241',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109242',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109250',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109251',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109252',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109253',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям',0,'',0,'','Утвержденные лимиты бюджетных обязательств по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109260',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по социальному обеспечению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109261',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109262',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109263',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные лимиты бюджетных обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109290',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по прочим расходам',0,'',0,'','Утвержденные лимиты бюджетных обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109300',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109310',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению основных средств',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109320',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109330',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109340',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109500',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750109530',0,'ПлСчет_Каз_2011',1,'Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные лимиты бюджетных обязательств по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750110000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств текущего финансового года',0,'',0,'','Лимиты бюджетных обязательств текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750120000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Лимиты бюджетных обязательств первого года, следующего за текущим (очередного финансового года)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750130000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за текущим (первого года, следующего за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750140000',0,'ПлСчет_Каз_2011',1,'Лимиты бюджетных обязательств  второго года, следующего за очередным',0,'',0,'','Лимиты бюджетных обязательств второго года, следующего за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750200000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства',0,'',0,'','Принятые обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201200',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по расходам',0,'',0,'','Принятые обязательства по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201210',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201211',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по заработной плате',0,'',0,'','Принятые обязательства по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201212',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим выплатам',0,'',0,'','Принятые обязательства по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201213',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','Принятые обязательства по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201220',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','Принятые обязательства по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201221',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  по услугам связи',0,'',0,'','Принятые обязательства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201222',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по транспортным услугам',0,'',0,'','Принятые обязательства по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201223',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','Принятые обязательства по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201224',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые обязательства по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201225',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые обязательства по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201226',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','Принятые обязательства по прочим  работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201230',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','Принятые обязательства по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201231',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','Принятые обязательства по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201232',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','Принятые обязательства по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201240',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201241',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201242',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201250',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','Принятые обязательства по безвозмездным перечисления бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201251',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201252',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201253',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','Принятые обязательства по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201260',0,'ПлСчет_Каз_2011',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','Принятые бюджетные обязательства по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201261',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201262',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые обязательства по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201263',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201290',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по прочим расходам',0,'',0,'','Принятые обязательства по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201300',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые обязательства по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201310',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','Принятые обязательства по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201320',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','Принятые обязательства по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201330',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые обязательства по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201340',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','Принятые обязательства по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201500',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','Принятые обязательства по приобретению финансовых активов', '19000101','19000101',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 '750201520',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201530',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','Принятые обязательства по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201540',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','Принятые обязательства по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201550',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','Принятые обязательства по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201800',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','Принятые обязательства по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201810',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750201820',0,'ПлСчет_Каз_2011',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Принятые обязательства по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202000',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства',0,'',0,'','Принятые денежные обязательства', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202200',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по расходам',0,'',0,'','Принятые денежные обязательства по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202210',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202211',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','Принятые денежные обязательства по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202212',0,'ПлСчет_Каз_2011',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','Принятые денежные бюджетные обязательства по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202213',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','Принятые денежные обязательства по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202220',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','Принятые денежные обязательства по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202221',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','Принятые денежные обязательства по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202222',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','Принятые денежные обязательства по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202223',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','Принятые денежные обязательства по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202224',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','Принятые денежные обязательства по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202225',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','Принятые денежные обязательства по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202226',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','Принятые денежные обязательства по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202240',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202241',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202242',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202250',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','Принятые денежные обязательства по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202253',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','Принятые денежные обязательства по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202260',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','Принятые денежные обязательства по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202262',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','Принятые денежные обязательства по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202263',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202290',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','Принятые денежные обязательства по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202300',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','Принятые денежные обязательства по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202310',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','Принятые денежные обязательства по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202320',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','Принятые денежные обязательства по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202330',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','Принятые денежные обязательства по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750202340',0,'ПлСчет_Каз_2011',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','Принятые денежные обязательства по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750210000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на текущий финансовый год',0,'',0,'','Принятые обязательства  на текущий финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750220000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на первый год, следующий за текущим  (на очередной финансовый год)',0,'',0,'','Принятые обязательства на первый год, следующий за текущим (на очередной финансовый год)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750230000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства  на второй год, следующий за текущим  (на первый год, следующий за очередным)',0,'',0,'','Принятые обязательства на второй год, следующий за текущим (на первый год, следующий за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750240000',0,'ПлСчет_Каз_2011',1,'Принятые обязательства на второй год, следующий за очередным',0,'',0,'','Принятые обязательства на второй год, следующий за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750300000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования',0,'',0,'','Бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301000',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования',0,'',0,'','Доведенные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301200',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по расходам',0,'',0,'','Доведенные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301210',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301211',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по заработной плате',0,'',0,'','Доведенные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301212',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим выплатам',0,'',0,'','Доведенные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301213',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Доведенные бюджетные ассигнования по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301220',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Доведенные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301221',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по услугам связи',0,'',0,'','Доведенные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301222',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по транспортным услугам',0,'',0,'','Доведенные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301223',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Доведенные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301224',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Доведенные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301225',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Доведенные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301226',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Доведенные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301230',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301231',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301232',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Доведенные бюджетные ассигнования по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301240',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301241',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301242',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301250',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Доведенные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301251',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301252',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301253',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Доведенные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301260',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Доведенные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301261',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301262',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Доведенные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301263',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Доведенные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301290',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по прочим расходам',0,'',0,'','Доведенные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301300',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301310',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Доведенные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301320',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301330',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301340',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования на по приобретению материальных запасов',0,'',0,'','Доведенные бюджетные ассигнования на по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301500',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301520',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301530',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Доведенные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301540',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Доведенные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301550',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Доведенные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301800',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Доведенные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301810',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750301820',0,'ПлСчет_Каз_2011',1,'Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Доведенные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования к распределению',0,'',0,'','Бюджетные ассигнования к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по  расходам к распределению',0,'',0,'','Бюджетные ассигнования по  расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по оплате труда и начисления на  выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по заработной плате к распределению',0,'',0,'','Бюджетные ассигнования по заработной плате к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим выплатам к распределению',0,'',0,'','Бюджетные ассигнования по прочим выплатам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению',0,'',0,'','Бюджетные ассигнования по начислениям на выплаты по оплате труда к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по оплате работ,  услуг к распределению',0,'',0,'','Бюджетные ассигнования по оплате работ,  услуг к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по услугам связи к распределению',0,'',0,'','Бюджетные ассигнования по услугам связи к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по транспортным услугам к распределению',0,'',0,'','Бюджетные ассигнования по транспортным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по коммунальным услугам к распределению',0,'',0,'','Бюджетные ассигнования по коммунальным услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по арендной плате за пользование имуществом к распределению',0,'',0,'','Бюджетные ассигнования по арендной плате за пользование имуществом к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению',0,'',0,'','Бюджетные ассигнования по работам, услугам по содержанию имущества к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим работам, услугам к распределению',0,'',0,'','Бюджетные ассигнования по прочим работам, услугам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию государственного (муниципального) долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внутреннего долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внутреннего долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению',0,'',0,'','Бюджетные ассигнования по обслуживанию внешнего государственного долга к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению',0,'',0,'','Бюджетные ассигнования по безвозмездным перечислениям бюджетам к распределению', '19000101','19000101',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 '750302251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по перечислениям международным организациям к распределению',0,'',0,'','Бюджетные ассигнования по перечислениям международным организациям к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по социальному обеспечению к распределению',0,'',0,'','Бюджетные ассигнования по социальному обеспечению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пособиям по социальной помощи населению к распределению',0,'',0,'','Бюджетные ассигнования по пособиям по социальной помощи населению к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению',0,'',0,'','Бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по прочим расходам к распределению',0,'',0,'','Бюджетные ассигнования по прочим расходам к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нефинансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нефинансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению основных средств к распределению',0,'',0,'','Бюджетные ассигнования по приобретению основных средств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению нематериальных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению нематериальных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению непроизведенных активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению непроизведенных активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению материальных запасов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению материальных запасов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению ценных бумаг, кроме акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению',0,'',0,'','Бюджетные ассигнования по приобретению акций и иных форм участия в капитале к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению',0,'',0,'','Бюджетные ассигнования по предоставлению бюджетных кредитов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по приобретению иных финансовых активов к распределению',0,'',0,'','Бюджетные ассигнования по приобретению иных финансовых активов к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению долговых обязательств к распределению',0,'',0,'','Бюджетные ассигнования по погашению долговых обязательств к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности по внутреннему долгу к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750302820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению',0,'',0,'','Бюджетные ассигнования по погашению задолженности  по внешнему государственному  долгу к распределению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по расходам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по услугам связи',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования получателей бюджетных средств и администраторов выплат по источникам по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования выплат по источникам по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования  выплат по источникам по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750303820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования администраторов выплат по источникам по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304000',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования',0,'',0,'','Переданные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304200',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по расходам',0,'',0,'','Переданные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304210',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Переданные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304211',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования  по заработной плате',0,'',0,'','Переданные бюджетные ассигнования  по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304212',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим выплатам',0,'',0,'','Переданные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304213',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда',0,'',0,'','Переданные бюджетные ассигнования по начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304220',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по оплате работ, услуг',0,'',0,'','Переданные бюджетные ассигнования по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304221',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по услугам связи',0,'',0,'','Переданные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304222',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по транспортным услугам',0,'',0,'','Переданные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304223',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Переданные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304224',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Переданные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304225',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Переданные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304226',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Переданные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304230',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304231',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304232',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга',0,'',0,'','Переданные бюджетные ассигнования по обслуживанию  внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304240',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304241',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304242',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304250',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Переданные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304251',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Переданные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304252',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Переданные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304253',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Переданные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304260',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Переданные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304261',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Переданные бюджетные ассигнования на расходы по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304262',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Переданные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304263',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Переданные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304290',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по прочим расходам',0,'',0,'','Переданные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304300',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304310',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Переданные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304320',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304330',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304340',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Переданные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304500',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304520',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Переданные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304530',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Переданные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304540',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Переданные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304550',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Переданные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304800',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Переданные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304810',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750304820',0,'ПлСчет_Каз_2011',1,'Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Переданные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305000',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования',0,'',0,'','Полученные бюджетные ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305200',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по расходам',0,'',0,'','Полученные бюджетные ассигнования по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305210',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305211',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по заработной плате',0,'',0,'','Полученные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305212',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим выплатам',0,'',0,'','Полученные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305213',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда',0,'',0,'','Полученные бюджетные ассигнования по начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305220',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Полученные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305221',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по услугам связи',0,'',0,'','Полученные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305222',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по транспортным услугам',0,'',0,'','Полученные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305223',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Полученные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305224',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Полученные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305225',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества',0,'',0,'','Полученные бюджетные ассигнования по работам,  услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305226',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим работ, услуг',0,'',0,'','Полученные бюджетные ассигнования по прочим работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305230',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305231',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внутреннего долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305232',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга',0,'',0,'','Полученные бюджетные ассигнования по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305240',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305241',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305242',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305250',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Полученные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305251',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Полученные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',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 '750305252',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Полученные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305253',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Полученные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305260',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Полученные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305261',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305262',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Полученные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305263',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Полученные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305290',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по прочим расходам',0,'',0,'','Полученные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305300',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305310',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Полученные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305320',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305330',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305340',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Полученные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305500',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305520',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Полученные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305530',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Полученные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305540',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Полученные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305550',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Полученные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305800',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Полученные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305810',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внутреннему долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750305820',0,'ПлСчет_Каз_2011',1,'Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Полученные бюджетные ассигнования по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути',0,'',0,'','Бюджетные ассигнования в пути', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306200',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по расходам',0,'',0,'','Бюджетные ассигнования в пути по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306210',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда',0,'',0,'','Бюджетные ассигнования в пути по оплате труда и начисления на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306211',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по заработной плате',0,'',0,'','Бюджетные ассигнования в пути по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306212',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим выплатам',0,'',0,'','Бюджетные ассигнования в пути по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306213',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда',0,'',0,'','Бюджетные ассигнования в пути по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306220',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по оплате работ,  услуг',0,'',0,'','Бюджетные ассигнования в пути по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306221',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по услугам связи',0,'',0,'','Бюджетные ассигнования в пути по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306222',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по транспортным услугам',0,'',0,'','Бюджетные ассигнования в пути по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306223',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по коммунальным услугам',0,'',0,'','Бюджетные ассигнования в пути по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306224',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по арендной плате за пользование имуществом',0,'',0,'','Бюджетные ассигнования в пути по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306225',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по работам, услугам по содержанию имущества',0,'',0,'','Бюджетные ассигнования в пути по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306226',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим работам, услугам',0,'',0,'','Бюджетные ассигнования в пути по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306230',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306231',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внутреннего долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306232',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга',0,'',0,'','Бюджетные ассигнования в пути по обслуживанию внешнего государственного долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306240',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306241',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306242',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306250',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам',0,'',0,'','Бюджетные ассигнования в пути по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306251',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Бюджетные ассигнования в пути по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306252',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Бюджетные ассигнования в пути по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306253',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по перечислениям международным организациям',0,'',0,'','Бюджетные ассигнования в пути по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306260',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по социальному обеспечению',0,'',0,'','Бюджетные ассигнования в пути по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306261',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306262',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пособиям по социальной помощи населению',0,'',0,'','Бюджетные ассигнования в пути по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306263',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Бюджетные ассигнования в пути по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306290',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по прочим расходам',0,'',0,'','Бюджетные ассигнования в пути по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306300',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нефинансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306310',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению основных средств',0,'',0,'','Бюджетные ассигнования в пути по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306320',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению нематериальных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306330',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению непроизведенных активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306340',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению материальных запасов',0,'',0,'','Бюджетные ассигнования в пути по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306500',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306520',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению ценных бумаг, кроме акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306530',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале',0,'',0,'','Бюджетные ассигнования в пути по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306540',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по предоставлению бюджетных кредитов',0,'',0,'','Бюджетные ассигнования в пути по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306550',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по приобретению иных финансовых активов',0,'',0,'','Бюджетные ассигнования в пути по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306800',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению долговых обязательств',0,'',0,'','Бюджетные ассигнования в пути по погашению долговых обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306810',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внутреннему  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750306820',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу',0,'',0,'','Бюджетные ассигнования в пути по погашению задолженности по внешнему государственному  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309000',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные  ассигнования',0,'',0,'','Утвержденные бюджетные  ассигнования', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309200',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  расходам',0,'',0,'','Утвержденные бюджетные ассигнования по  расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309210',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по оплате труда и начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309211',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по заработной плате',0,'',0,'','Утвержденные бюджетные ассигнования по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309212',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим выплатам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309213',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные бюджетные ассигнования по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309220',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по оплате работ,  услуг',0,'',0,'','Утвержденные бюджетные ассигнования по оплате работ,  услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309221',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по услугам связи',0,'',0,'','Утвержденные бюджетные ассигнования по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309222',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по транспортным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309223',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по коммунальным услугам',0,'',0,'','Утвержденные бюджетные ассигнования по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309224',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом',0,'',0,'','Утвержденные бюджетные ассигнования по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309225',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные бюджетные ассигнования по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309226',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим работам, услугам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309230',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию государственного (муниципального) долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309231',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внутреннего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309232',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга',0,'',0,'','Утвержденные бюджетные ассигнования по  обслуживанию внешнего долга', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309240',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309241',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309242',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309250',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам',0,'',0,'','Утвержденные бюджетные ассигнования по безвозмездным перечислениям бюджетам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309251',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям другим бюджетам бюджетной системы Российской Федерации', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309252',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309253',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по перечислениям международным организациям',0,'',0,'','Утвержденные бюджетные ассигнования по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309260',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по социальному обеспечению',0,'',0,'','Утвержденные бюджетные ассигнования по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309261',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309262',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению',0,'',0,'','Утвержденные бюджетные ассигнования по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309263',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные бюджетные ассигнования по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309290',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по прочим расходам',0,'',0,'','Утвержденные бюджетные ассигнования по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309300',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нефинансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309310',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению основных средств',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309320',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению нематериальных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309330',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению непроизведенных активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309340',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению материальных запасов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309500',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309520',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению ценных бумаг, кроме акций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309530',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению акций и иных форм участия в капитале', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309540',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов',0,'',0,'','Утвержденные бюджетные ассигнования по предоставлению бюджетных кредитов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309550',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по приобретению иных финансовых активов',0,'',0,'','Утвержденные бюджетные ассигнования по приобретению иных финансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309800',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению долговых обязательств',0,'',0,'','Утвержденные бюджетные ассигнования по погашению долговых обязательств', '19000101','19000101',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 '750309810',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внутреннему  долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750309820',0,'ПлСчет_Каз_2011',1,'Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу',0,'',0,'','Утвержденные бюджетные ассигнования по погашению задолженности по внешнему государственному долгу', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750310000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования текущего финансового года',0,'',0,'','Бюджетные ассигнования текущего финансового года', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750320000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)',0,'',0,'','Бюджетные ассигнования первого года, следующего за текущим (очередного финансового года)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750330000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)',0,'',0,'','Бюджетные ассигнования второго года, следующего за текущим (первого года, следующего за очередным)', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750340000',0,'ПлСчет_Каз_2011',1,'Бюджетные ассигнования второго года, следующего за очередным',0,'',0,'','Бюджетные ассигнования второго года, следующего за очередным', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400000',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400200',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400210',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате труда и начислениям на  выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400211',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по заработной плате',0,'',0,'','Утвержденные сметные (плановые) назначения по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400212',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим выплатам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400213',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда',0,'',0,'','Утвержденные сметные (плановые) назначения по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400220',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по оплате работ, услуг',0,'',0,'','Утвержденные сметные (плановые) назначения по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400221',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по услугам связи',0,'',0,'','Утвержденные сметные (плановые) назначения по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400222',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по транспортным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400223',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по коммунальным услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400224',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом',0,'',0,'','Утвержденные сметные (плановые) назначения по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400225',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества',0,'',0,'','Утвержденные сметные (плановые) назначения по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400226',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим работам, услугам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400240',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400241',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400242',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400250',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по безвозмездным перечислениям',0,'',0,'','Утвержденные сметные (плановые) назначения по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400252',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400253',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по перечислениям международным организациям',0,'',0,'','Утвержденные сметные (плановые) назначения по перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400260',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по социальному обеспечению',0,'',0,'','Утвержденные сметные (плановые) назначения по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400262',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению',0,'',0,'','Утвержденные сметные (плановые) назначения по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400263',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Утвержденные сметные (плановые) назначения по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400290',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по прочим расходам',0,'',0,'','Утвержденные сметные (плановые) назначения по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400300',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400310',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению основных средств',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400320',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению нематериальных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400330',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750400340',0,'ПлСчет_Каз_2011',1,'Утвержденные сметные (плановые) назначения по приобретению материальных запасов',0,'',0,'','Утвержденные сметные (плановые) назначения по приобретению материальных запасов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750410000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения  на текущий финансовый год',0,'',0,'','Сметные (плановые) назначения  на текущий финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750420000',0,'ПлСчет_Каз_2011',1,'Сметные (плановые) назначения на очередной финансовый год',0,'',0,'','Сметные (плановые) назначения на очередной финансовый год', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600000',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств',0,'',0,'','Право на принятие обязательств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600200',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по расходам',0,'',0,'','Право на принятие обязательств по расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600210',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда',0,'',0,'','Право на принятие обязательств по оплате труда и начислениям на выплаты по  оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600211',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по заработной плате',0,'',0,'','Право на принятие обязательств по заработной плате', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600212',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим выплатам',0,'',0,'','Право на принятие обязательств по прочим выплатам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600213',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по начислениям на выплаты по оплате труда',0,'',0,'','Право на принятие обязательств по начислениям на выплаты по оплате труда', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600220',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по оплате работ, услуг',0,'',0,'','Право на принятие обязательств по оплате работ, услуг', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600221',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по услугам связи',0,'',0,'','Право на принятие обязательств по услугам связи', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600222',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по транспортным услугам',0,'',0,'','Право на принятие обязательств по транспортным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600223',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по коммунальным услугам',0,'',0,'','Право на принятие обязательств по коммунальным услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600224',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по арендной плате за пользование имуществом',0,'',0,'','Право на принятие обязательств по арендной плате за пользование имуществом', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600225',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по работам, услугам по содержанию имущества',0,'',0,'','Право на принятие обязательств по работам, услугам по содержанию имущества', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600226',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим работам, услугам',0,'',0,'','Право на принятие обязательств по прочим работам, услугам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600240',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600241',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям государственным и муниципальным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600242',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600250',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по безвозмездным перечислениям',0,'',0,'','Право на принятие обязательств по безвозмездным перечислениям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600252',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','Право на принятие обязательств по перечислениям наднациональным организациям и правительствам иностранных государств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600253',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по  перечислениям международным организациям',0,'',0,'','Право на принятие обязательств по  перечислениям международным организациям', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600260',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по социальному обеспечению',0,'',0,'','Право на принятие обязательств по социальному обеспечению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600262',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пособиям по социальной помощи населению',0,'',0,'','Право на принятие обязательств по пособиям по социальной помощи населению', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600263',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','Право на принятие обязательств по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600290',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по прочим расходам',0,'',0,'','Право на принятие обязательств по прочим расходам', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600300',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нефинансовых активов',0,'',0,'','Право на принятие обязательств по приобретению нефинансовых активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600310',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению основных средств',0,'',0,'','Право на принятие обязательств по приобретению основных средств', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600320',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению нематериальных активов',0,'',0,'','Право на принятие обязательств по приобретению нематериальных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600330',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению непроизведенных активов',0,'',0,'','Право на принятие обязательств по приобретению непроизведенных активов', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750600340',0,'ПлСчет_Каз_2011',1,'Право на принятие обязательств по приобретению материальных запасов',0,'',0,'','Право на принятие обязательств по приобретению материальных запасов', '19000101','19000101',0


GO


GO
if not exists(select * from KAU where CODE = 'Номинал')
	insert into KAU(CODE, NAME, THEMA)
	values('Номинал','Учет ценной бумаги по номинальной стоимости','Ценные бумаги')

if not exists(select * from KAU where CODE = 'Размещение')
	insert into KAU(CODE, NAME, THEMA)
	values('Размещение','Учет ценной бумаги по цене размещения','Ценные бумаги')
GO

GO
/****** Объект: Вид финансового обеспечения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_773')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_773'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_773')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_VID_773')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_VID_773', 'Вид финансового обеспечения', 41, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORTS_ATR_VID_773', NAME = 'Вид финансового обеспечения', ORDERS = '41', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORTS_ATR_VID_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'NAME', 'Вид финансового обеспечения'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("R_SPR_ATR_VID_773", oForm.ALIAS_ATR, "CODE,NAME", "REPORTS_ATR_VID_773,REPORTS_ATR_VID_NAME_773", "", "", "", .T., 1, oForm, oObj)
'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'SHORT_NAME', 'ВидФинОб'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'DEFAULT_VALUE', 'v'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'MAXWIDTH', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'DICTIONARY', 'R_SPR_ATR_VID_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_VID_773,REPORTS_ATR_VID_NAME_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_773', 'DICTIONARY_FIELDS_LIST', 'CODE,NAME'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/****** Объект: Наименование финансового обеспечения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_NAME_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_NAME_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_NAME_773')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_VID_NAME_773')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_NAME_773'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_VID_NAME_773')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_VID_NAME_773')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_VID_NAME_773', 'Наименование финансового обеспечения', 42, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORTS_ATR_VID_NAME_773', NAME = 'Наименование финансового обеспечения', ORDERS = '42', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORTS_ATR_VID_NAME_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'NAME', 'Наименоване финансового обеспечения'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("R_SPR_ATR_VID_773",oForm.ALIAS_ATR, "CODE,NAME", "REPORTS_ATR_VID_773,REPORTS_ATR_VID_NAME_773", "", "", "", .T., 1, oForm, oObj)
'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'SHORT_NAME', 'Наим'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'DEFAULT_VALUE', 'деятельность по оказанию услуг (работ) (приносящая доход деятельность)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'MAXWIDTH', '254'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'DICTIONARY', 'R_SPR_ATR_VID_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_VID_773,REPORTS_ATR_VID_NAME_773'
GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'DICTIONARY_FIELDS_LIST', 'CODE,NAME'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
EXEC X_SET_PROP 'REPORTS_ATR_PERCENT', 'DEFAULT_VALUE', '45'
GO


GO
EXEC X_SET_PROP 'REPORTS_ATR_VID_NAME_773', 'DEFAULT_VALUE', 'деятельность по оказанию услуг (работ)'
GO

GO
update B
set VALUE = replace(replace(replace(replace(B.VALUE,'<LF>', '<Перевод_строки>'),'<PERCENT>', '<Процент>'),'<SUMMA>', '<Руб>.<Коп>'),'<SUM_NDS>', '<НДС_Руб>.<НДС_Коп>')
FROM dbo.DICTION_APP B  
inner JOIN S_OBJECTS SO on SO.LINK = B.OBJECT and SO.CODE = 'DICTIONARY_PAY_NDS_SHABLON'
GO
EXEC X_SET_PROP 'DICTIONARY_PAY_NDS_SHABLON', 'EDIT_OBJECT_METHOD', 'BB_VIBOR_SHABLON (oForm.Alias, "SHABLON", "NDS")'
GO
EXEC X_SET_PROP 'DICTIONARY_PAY_NDS_SHABLON', 'CONTROL_NAME_EDIT', 'aSel_spr2'
GO

GO
EXECUTE dbo.X_FORM_VIEW_DICTIONARY 'DICTIONARY_PLACE_ND_IMU'
EXECUTE dbo.X_FORM_SAVE_DICTIONARY 'DICTIONARY_PLACE_ND_IMU', 'DICTIONARY_PLACE_ND_IMU', 1
GO



GO
EXECUTE dbo.X_FORM_VIEW_DICTIONARY 'DICTIONARY_REORG_DEP'
EXECUTE dbo.X_FORM_SAVE_DICTIONARY 'DICTIONARY_REORG_DEP', 'DICTIONARY_REORG_DEP', 1
GO


GO
EXECUTE X_FORM_VIEW_DICTIONARY 'DICTIONARY_TAX_PERIOD'
EXECUTE X_FORM_SAVE_DICTIONARY 'DICTIONARY_TAX_PERIOD', 'DICTIONARY_TAX_PERIOD', 1 
GO


GO
--- Загрузка (обновление) справочника: 'Коды представления НД по налогу на имущество' (DICTIONARY_PLACE_ND_IMU)
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '213')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту учета в качестве крупнейшего налогоплательщика',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '213'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '213', 'По месту учета в качестве крупнейшего налогоплательщика', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '214')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту нахождения российской организации, не являющейся крупнейшим налогоплательщиком',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '214'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '214', 'По месту нахождения российской организации, не являющейся крупнейшим налогоплательщиком', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '215')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту нахождения правопреемника, не являющегося крупнейшим налогоплательщиком',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '215'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '215', 'По месту нахождения правопреемника, не являющегося крупнейшим налогоплательщиком', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '216')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту учета правопреемника, являющегося крупнейшим налогоплательщиком',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '216'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '216', 'По месту учета правопреемника, являющегося крупнейшим налогоплательщиком', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '221')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту нахождения обособленного подразделения российской организации, имеющего отдельный баланс',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '221'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '221', 'По месту нахождения обособленного подразделения российской организации, имеющего отдельный баланс', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '245')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту постановки на учет в налоговом органе иностранной организации',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '245'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '245', 'По месту постановки на учет в налоговом органе иностранной организации', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_PLACE_ND_IMU')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '281')
	UPDATE dbo.DICTION
	SET [NAME] = 'По месту нахождения объекта недвижимого имущества (в отношении которого установлен отдельный порядок исчисления и уплаты налога)',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '281'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '281', 'По месту нахождения объекта недвижимого имущества (в отношении которого установлен отдельный порядок исчисления и уплаты налога)', @intOBJ_LINK, '17530101', '99991231'
GO







GO
--- Загрузка (обновление) справочника: 'Коды форм реорганизации (ликвидации)' (DICTIONARY_REORG_DEP)
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '1 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Преобразование',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '1 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '1', 'Преобразование', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '2 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Слияние',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '2 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '2', 'Слияние', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '3 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Разделение',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '3 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '3', 'Разделение', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '5 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Присоединение',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '5 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '5', 'Присоединение', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '6 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Разделение с одновременным присоединением',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '6 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '6', 'Разделение с одновременным присоединением', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_REORG_DEP')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '0 ')
	UPDATE dbo.DICTION
	SET [NAME] = 'Ликвидация',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '0 '
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '0', 'Ликвидация', @intOBJ_LINK, '17530101', '99991231'
GO


GO
--- Загрузка (обновление) справочника: 'Налоговый период' (DICTIONARY_TAX_PERIOD)
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '34')
	UPDATE dbo.DICTION
	SET [NAME] = 'Календарный год',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '34'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '34', 'Календарный год', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '50')
	UPDATE dbo.DICTION
	SET [NAME] = 'Последний налоговый период при реорганизации (ликвидации) организации',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '50'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '50', 'Последний налоговый период при реорганизации (ликвидации) организации', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '21')
	UPDATE dbo.DICTION
	SET [NAME] = 'I квартал',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '21'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '21', 'I квартал', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '31')
	UPDATE dbo.DICTION
	SET [NAME] = 'полугодие',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '31'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '31', 'полугодие', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '33')
	UPDATE dbo.DICTION
	SET [NAME] = '9 месяцев',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '33'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '33', '9 месяцев', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '51')
	UPDATE dbo.DICTION
	SET [NAME] = 'I квартал при реорганизации организации',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '51'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '51', 'I квартал при реорганизации организации', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '52')
	UPDATE dbo.DICTION
	SET [NAME] = 'полугодие при реорганизации организации',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '52'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '52', 'полугодие при реорганизации организации', @intOBJ_LINK, '17530101', '99991231'
GO
DECLARE @intOBJ_LINK INT
SELECT @intOBJ_LINK = dbo.GetObjLink ('DICTIONARY_TAX_PERIOD')
IF EXISTS (SELECT 1 FROM dbo.DICTION WHERE OBJECT = @intOBJ_LINK AND CODE = '53')
	UPDATE dbo.DICTION
	SET [NAME] = '9 месяцев при реорганизации организации',
		BEGINDATE = '17530101',
		ENDDATE = '99991231'
	WHERE OBJECT = @intOBJ_LINK AND CODE = '53'
ELSE
	INSERT INTO dbo.DICTION (CODE, [NAME], OBJECT, BEGINDATE, ENDDATE)
	SELECT '53', '9 месяцев при реорганизации организации', @intOBJ_LINK, '17530101', '99991231'
GO




GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '01')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Отгрузка (передача) или приобретение товаров, работ, услуг (включая посреднические услуги), имущественных прав, за исключением операций, перечисленных по кодам 03, 04, 06, 10, 11, 13',
		FULL_NAME = 'Отгрузка (передача) или приобретение товаров, работ, услуг (включая посреднические услуги), имущественных прав, за исключением операций, перечисленных по кодам 03, 04, 06, 10, 11, 13'
	WHERE CODE = '01'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '01', 'Отгрузка (передача) или приобретение товаров, работ, услуг (включая посреднические услуги), имущественных прав, за исключением операций, перечисленных по кодам 03, 04, 06, 10, 11, 13', 'Отгрузка (передача) или приобретение товаров, работ, услуг (включая посреднические услуги), имущественных прав, за исключением операций, перечисленных по кодам 03, 04, 06, 10, 11, 13', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '02')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (включая посреднические услуги)), передачи имущественных прав, за исключением операций, перечисленных по кодам 05, 06, 12',
		FULL_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (включая посреднические услуги)), передачи имущественных прав, за исключением операций, перечисленных по кодам 05, 06, 12'
	WHERE CODE = '02'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '02', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (включая посреднические услуги)), передачи имущественных прав, за исключением операций, перечисленных по кодам 05, 06, 12', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (включая посреднические услуги)), передачи имущественных прав, за исключением операций, перечисленных по кодам 05, 06, 12', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '03')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Возврат покупателем товаров продавцу или получение продавцом возвращенных покупателем товаров',
		FULL_NAME = 'Возврат покупателем товаров продавцу или получение продавцом возвращенных покупателем товаров'
	WHERE CODE = '03'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '03', 'Возврат покупателем товаров продавцу или получение продавцом возвращенных покупателем товаров', 'Возврат покупателем товаров продавцу или получение продавцом возвращенных покупателем товаров', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '04')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Отгрузка (передача) или приобретение товаров, работ, услуг (за исключением посреднических услуг), имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, пере',
		FULL_NAME = 'Отгрузка (передача) или приобретение товаров, работ, услуг (за исключением посреднических услуг), имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, перечисленных по коду 06'
	WHERE CODE = '04'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '04', 'Отгрузка (передача) или приобретение товаров, работ, услуг (за исключением посреднических услуг), имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, пере', 'Отгрузка (передача) или приобретение товаров, работ, услуг (за исключением посреднических услуг), имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, перечисленных по коду 06', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '05')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (за исключением посреднических услуг)), передачи имущественных прав на основе договора комиссии (агентского договора, в случае, есл',
		FULL_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (за исключением посреднических услуг)), передачи имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, перечисленных по коду 06'
	WHERE CODE = '05'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '05', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (за исключением посреднических услуг)), передачи имущественных прав на основе договора комиссии (агентского договора, в случае, есл', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров (выполнения работ, оказания услуг (за исключением посреднических услуг)), передачи имущественных прав на основе договора комиссии (агентского договора, в случае, если агент совершает действия от своего имени), за исключением операций, перечисленных по коду 06', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '06')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Операции, совершаемые налоговыми агентами, перечисленными в статье 161 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Операции, совершаемые налоговыми агентами, перечисленными в статье 161 Налогового кодекса Российской Федерации'
	WHERE CODE = '06'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '06', 'Операции, совершаемые налоговыми агентами, перечисленными в статье 161 Налогового кодекса Российской Федерации', 'Операции, совершаемые налоговыми агентами, перечисленными в статье 161 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '07')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Операции, перечисленные в подпункте 2 пункта 1 статьи 146 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Операции, перечисленные в подпункте 2 пункта 1 статьи 146 Налогового кодекса Российской Федерации'
	WHERE CODE = '07'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '07', 'Операции, перечисленные в подпункте 2 пункта 1 статьи 146 Налогового кодекса Российской Федерации', 'Операции, перечисленные в подпункте 2 пункта 1 статьи 146 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '08')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Операции, перечисленные в подпункте 3 пункта 1 статьи 146 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Операции, перечисленные в подпункте 3 пункта 1 статьи 146 Налогового кодекса Российской Федерации'
	WHERE CODE = '08'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '08', 'Операции, перечисленные в подпункте 3 пункта 1 статьи 146 Налогового кодекса Российской Федерации', 'Операции, перечисленные в подпункте 3 пункта 1 статьи 146 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '09')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Получение сумм, указанных в статье 162 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Получение сумм, указанных в статье 162 Налогового кодекса Российской Федерации'
	WHERE CODE = '09'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '09', 'Получение сумм, указанных в статье 162 Налогового кодекса Российской Федерации', 'Получение сумм, указанных в статье 162 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '10')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Отгрузка (передача) или получение товаров, работ, услуг, имущественных прав на безвозмездной основе',
		FULL_NAME = 'Отгрузка (передача) или получение товаров, работ, услуг, имущественных прав на безвозмездной основе'
	WHERE CODE = '10'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '10', 'Отгрузка (передача) или получение товаров, работ, услуг, имущественных прав на безвозмездной основе', 'Отгрузка (передача) или получение товаров, работ, услуг, имущественных прав на безвозмездной основе', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '11')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Отгрузка (передача) или приобретение товаров, имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Отгрузка (передача) или приобретение товаров, имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации'
	WHERE CODE = '11'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '11', 'Отгрузка (передача) или приобретение товаров, имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации', 'Отгрузка (передача) или приобретение товаров, имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '12')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров, передачи имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации',
		FULL_NAME = 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров, передачи имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации'
	WHERE CODE = '12'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '12', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров, передачи имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации', 'Оплата, частичная оплата (полученная или переданная) в счет предстоящих поставок товаров, передачи имущественных прав, перечисленных в пунктах 3, 4, 5.1 статьи 154, в подпунктах 1 - 4 статьи 155 Налогового кодекса Российской Федерации', 1
GO
IF EXISTS (SELECT 1 FROM dbo.TYPE_OPER_NDS WHERE CODE = '13')
	UPDATE dbo.TYPE_OPER_NDS
	SET SHORT_NAME = 'Проведение подрядными организациями (заказчиками-застройщиками) капитального строительства, модернизации (реконструкции) объектов недвижимости',
		FULL_NAME = 'Проведение подрядными организациями (заказчиками-застройщиками) капитального строительства, модернизации (реконструкции) объектов недвижимости'
	WHERE CODE = '13'
ELSE
	INSERT INTO dbo.TYPE_OPER_NDS (CODE, SHORT_NAME, FULL_NAME, ISUSED)
	SELECT '13', 'Проведение подрядными организациями (заказчиками-застройщиками) капитального строительства, модернизации (реконструкции) объектов недвижимости', 'Проведение подрядными организациями (заказчиками-застройщиками) капитального строительства, модернизации (реконструкции) объектов недвижимости', 1
GO




GO
--- Перенос реквизитов счет-фактура полученный со старой структуры ---
INSERT INTO dbo.G_PROV_INVOICE
		(DOC_LINK,
		SELLER,
		BUYER,
		SHIPPER,
		RECEIVER,
		PRODUCER,
		PAY_NUM,
		PAY_DATE,
		OSNOV,
		TAX_RATE,
		INBOOK,
		SEL_SHIP,
		BUY_RECIVE,
		TAX_SUM)

SELECT T0.LINK,
	T0.SEL_LINK,
	T0.BUY_LINK,
	T0.CONS1_LINK,
	T0.CONS2_LINK,
	T0.PROD_LINK,

	ISNULL (T0.NUM_BASE, ''),
	T0.DATE_BASE,
		
	T0.OSNOV,
	ISNULL (T0.TAX_RATE, 0),

	ISNULL (T0.BOOK_PUR, 0),
	ISNULL (T0.CONS1_SELF, 0),
	ISNULL (T0.CONS2_SELF, 0),
	
	ISNULL (T0.NALOG_DOC, 0)

FROM dbo.DOCUMENTS_INVOICE_RECEIVED_OLD T0
WHERE NOT EXISTS (SELECT 1
		FROM dbo.G_PROV_INVOICE GPI
		WHERE GPI.DOC_LINK = T0.LINK)

GO



GO
--- Перенос реквизитов счет-фактура выданный со старой структуры ---
INSERT INTO dbo.G_PROV_INVOICE
		(DOC_LINK,
		SELLER,
		BUYER,
		SHIPPER,
		RECEIVER,
		PRODUCER,
		PAY_NUM,
		PAY_DATE,
		OSNOV,
		TAX_RATE,
		INBOOK,
		SEL_SHIP,
		BUY_RECIVE,
		TAX_SUM)

SELECT T0.LINK,
	T0.SEL_LINK,
	T0.BUY_LINK,
	T0.CONS1_LINK,
	T0.CONS2_LINK,
	T0.PROD_LINK,

	ISNULL (T0.NUM_BASE, ''),
	T0.DATE_BASE,
		
	T0.OSNOV,
	ISNULL (T0.TAX_RATE, 0),

	ISNULL (T0.BOOK_SALES, 0),
	ISNULL (T0.CONS1_SELF, 0),
	ISNULL (T0.CONS2_SELF, 0),
	
	ISNULL (T0.NALOG_DOC, 0)

FROM dbo.DOCUMENTS_INVOICE_ISSUED_OLD T0
WHERE NOT EXISTS (SELECT 1
		FROM dbo.G_PROV_INVOICE GPI
		WHERE GPI.DOC_LINK = T0.LINK)

GO





GO
-- !!!Обновление эталонных настроек ПС!!! --
UPDATE T1
SET AP_EKR = 1
FROM dbo.S_ACCOUNTS_NASTR T1
WHERE SINTH = '201' AND ANALITH = '34' 
	OR SINTH = '303'
	OR SINTH = '304' AND ANALITH = '03' 
	
UPDATE T1 
SET S_ACTIVE = 1
FROM dbo.S_ACCOUNTS_NASTR T1
WHERE SINTH = '501' AND ANALITH LIKE '_[5,9]'
	OR SINTH = '503' AND ANALITH LIKE '_[5,9]'
GO


GO
update  OVV
set VALUE = 'Полученны лимиты (501.05),Переданны  лимиты(501.04),Полученны ассигнования (503.05),Переданны ассигнования(503.04)'
from OBJECT_VAR_VALUES OVV
inner join object_var OV on OV.LINK = OVV.LINK_UP and OV.code = 'CARD_LBO_NASTR3'
inner join s_property SP on SP.LINK = OVV.PROPERTY and SP.code = 'QUERY_NASTR_SOURCE'
GO

GO
EXEC X_SET_PROP 'DOC_CLOSE_YEAR_TABLE_ACCT_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01("PLAN_ACCOUNTS_LIST", oForm.Pages.Page1.Bchspisok.Bgrid1.RecordSource, "LINK,CODE,NAME", "ACCT_LINK,ACCT_CODE,ACCT_NAME", "LINK", "","ZABALANS = 0 AND (OCODE  LIKE ''21002%'' OR OCODE LIKE ''3040[4- 6]%'' OR OCODE LIKE ''401[1-2]0%'')",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO


GO
EXECUTE dbo.BX_CREATE_G_PROV_AP_EDIT_TABLE
GO


GO
if not exists(select * from CREDIT_PARAM_DICTION where code = 'SERIYA')
	insert into CREDIT_PARAM_DICTION(CODE, NAME, [TYPE], [ORDER],SPR)
	values('SERIYA','Серия ценной бумаги', 1, 1, 0)
GO

GO
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_DATA_DAY')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_DATA_DAY')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_DATA_DAY')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORTS_ATR_DATA_DAY')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_DATA_DAY'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_DATA_DAY')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_DATA_DAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_DATA_DAY', 'Дата(ежедневная)', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORTS_ATR_DATA_DAY', NAME = 'Дата(ежедневная)', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_ATR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ATRIBUT'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORTS_ATR_DATA_DAY'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'NAME', 'Дата(ежедневная)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'SHORT_NAME', 'ДАТА'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_DATA_DAY', 'MAXWIDTH', '10'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_DATA_DAY', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_DATA_DAY', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_DATA_DAY', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_DATA_DAY', 'Главный бухгалтер', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_DATA_DAY', 'Начальник отдела кадров', 63,0
GO


GO
DELETE FROM [dbo].[REPORT_GROUP_KS] WHERE code = '1097'
GO

GO

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Исполнительный лист******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_KADR_WRIT')
	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_KADR_WRIT')
	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_KADR_WRIT')
	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_KADR_WRIT')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_KADR_WRIT'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_KADR_WRIT')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_KADR_WRIT', 'Исполнительный лист', 19, (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_KADR_WRIT', NAME = 'Исполнительный лист', ORDERS = '19', 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_KADR_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_K_WRIT', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_K_WRIT', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FLAG_J_C_DED_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FLAG_J_C_DED_WRIT', 'Признак проведения в журнале расчетов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_FLAG_J_C_DED_WRIT', NAME = 'Признак проведения в журнале расчетов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_FLAG_J_C_DED_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_K_WRIT', 'Номер документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_K_WRIT', NAME = 'Номер документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE_K_WRIT', 'Дата документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE_K_WRIT', NAME = 'Дата документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EMPL_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EMPL_K_WRIT', 'Табельный номер', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EMPL_K_WRIT', NAME = 'Табельный номер', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EMPL_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_EMPL_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_EMPL_K_WRIT', 'Сотрудник', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_EMPL_K_WRIT', NAME = 'Сотрудник', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_EMPL_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_EMPL_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_EMPL_K_WRIT', 'Ссылка на работника', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_EMPL_K_WRIT', NAME = 'Ссылка на работника', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_EMPL_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_TAX_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_TAX_K_WRIT', 'Код удержания', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_TAX_K_WRIT', NAME = 'Код удержания', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_TAX_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_TAX_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_TAX_K_WRIT', 'Наименование удержания', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_TAX_K_WRIT', NAME = 'Наименование удержания', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_TAX_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_TAX_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_TAX_K_WRIT', 'Ссылка на удержание', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_TAX_K_WRIT', NAME = 'Ссылка на удержание', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_TAX_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE1_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE1_K_WRIT', 'Дата начала', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE1_K_WRIT', NAME = 'Дата начала', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE1_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE2_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE2_K_WRIT', 'Дата окончания', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE2_K_WRIT', NAME = 'Дата окончания', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE2_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_PHYS_PERS_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_PHYS_PERS_K_WRIT', 'Ссылка на физическое лицо', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_PHYS_PERS_K_WRIT', NAME = 'Ссылка на физическое лицо', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_PHYS_PERS_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_RECIP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_RECIP_K_WRIT', 'Код получателя', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_RECIP_K_WRIT', NAME = 'Код получателя', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_RECIP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_RECIP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_RECIP_K_WRIT', 'Наименование получателя', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_RECIP_K_WRIT', NAME = 'Наименование получателя', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_RECIP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_RECIP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_RECIP_K_WRIT', 'Ссылка на получателя', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_RECIP_K_WRIT', NAME = 'Ссылка на получателя', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_RECIP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_WAY_ENUMER_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_WAY_ENUMER_K_WRIT', 'Способ перечисления', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_WAY_ENUMER_K_WRIT', NAME = 'Способ перечисления', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_WAY_ENUMER_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PAYMENT_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PAYMENT_K_WRIT', 'Способ расчета', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PAYMENT_K_WRIT', NAME = 'Способ расчета', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PAYMENT_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUM_ENUMER_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUM_ENUMER_K_WRIT', 'Сумма за перечисление', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUM_ENUMER_K_WRIT', NAME = 'Сумма за перечисление', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUM_ENUMER_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PERCENT_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PERCENT_K_WRIT', 'Процент', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PERCENT_K_WRIT', NAME = 'Процент', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PERCENT_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_NEED_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_NEED_K_WRIT', 'Сумма необходимая', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_NEED_K_WRIT', NAME = 'Сумма необходимая', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_NEED_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_K_WRIT', 'Сумма', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_K_WRIT', NAME = 'Сумма', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_COMMENTARY_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_COMMENTARY_K_WRIT', 'Комментарий', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_COMMENTARY_K_WRIT', NAME = 'Комментарий', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_COMMENTARY_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_ORGP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_ORGP_K_WRIT', 'Организация', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_ORGP_K_WRIT', NAME = 'Организация', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_ORGP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_ORGP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_ORGP_K_WRIT', 'Организация', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_ORGP_K_WRIT', NAME = 'Организация', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_ORGP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_ORGP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_ORGP_K_WRIT', 'Ссылка на организацию', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_ORGP_K_WRIT', NAME = 'Ссылка на организацию', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_ORGP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_TAXP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_TAXP_K_WRIT', 'Код удержания за перечисление', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_TAXP_K_WRIT', NAME = 'Код удержания за перечисление', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_TAXP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_TAXP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_TAXP_K_WRIT', 'Наименование удержания за перечисление', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_TAXP_K_WRIT', NAME = 'Наименование удержания за перечисление', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_TAXP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_TAXP_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_TAXP_K_WRIT', 'Ссылка на удержание за перечисление', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_TAXP_K_WRIT', NAME = 'Ссылка на удержание за перечисление', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_TAXP_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_VKR_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_VKR_K_WRIT', 'Ссылка на Источник', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_VKR_K_WRIT', NAME = 'Ссылка на Источник', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_VKR_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR_K_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR_K_WRIT', 'Источник', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR_K_WRIT', NAME = 'Источник', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR_K_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_INO_WRIT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_INO_WRIT', 'Флаг международного перевода', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_INO_WRIT', NAME = 'Флаг международного перевода', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_INO_WRIT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WRIT_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WRIT_NAME_DEP', 'Организация', 33, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WRIT_NAME_DEP', NAME = 'Организация', ORDERS = '33', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WRIT_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WRIT_PERC_SFIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WRIT_PERC_SFIN', 'почт. сбор по источникам', 34, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WRIT_PERC_SFIN', NAME = 'почт. сбор по источникам', ORDERS = '34', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WRIT_PERC_SFIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WRIT_PERC_NO_NDFL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WRIT_PERC_NO_NDFL', 'без учёта НДФЛ', 35, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WRIT_PERC_NO_NDFL', NAME = 'без учёта НДФЛ', ORDERS = '35', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WRIT_PERC_NO_NDFL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='WRIT_UCHET_BY_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'WRIT_UCHET_BY_EKR', 'учет в разрезе ЭКР', 36, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'WRIT_UCHET_BY_EKR', NAME = 'учет в разрезе ЭКР', ORDERS = '36', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_KADR_WRIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='WRIT_UCHET_BY_EKR'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'TITLE', 'Исполнительные листы'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'INIT_OBJECT_METHOD', 'S_SPISOK("DOCUMENTS_KADR_WRIT")'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOCUMENTS_KADR_WRIT", "SALARY_DELETE_SDOC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'SAVE_OBJECT_METHOD', 'sd_isp_save(oForm)'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SD_ISP'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'SELECT_RECORDS_METHOD', 'kir_select_document_sdoc_writ(''DOCUMENTS_KADR_WRIT'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'SELECT_RECORDS_METHOD_EDIT', 'select_document_list(''DOCUMENTS_KADR_WRIT'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'SERVER_TABLE_NAME', 'SDOC'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'HELP_TOPIC', '32'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'COMMENTARY', 'Исполнительный лист вводится по сотруднику для регистрации исполнительного листа. Вводятся все необходимые данные для дальнейшего расчета через режим "Массовый расчет".'
GO
EXEC X_SET_PROP 'DOCUMENTS_KADR_WRIT', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_K_WRIT', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_WRIT', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'CONTROL_NAME_EDIT', 'ATxtNomDok'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_K_WRIT', 'COMMENTARY', 'Номер документа по порядку'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_K_WRIT', 'CONTROL_NAME_EDIT', 'Aseldate02'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'TITLE', 'Таб. номер'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''LINK, TAB, NAME_EMPL'', ''REF_EMPL, TAB_NUMER,NAME_EMPL'', '''','''', "DEP_LINK = " + STR(EVAL(oForm.Alias + ".LINK_DEP")), .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".TAB_NUMER"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAB_NUMER"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr03'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'TITLE', 'Сотрудник'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".NAME_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox03'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".REF_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'TITLE', 'Удержание'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_TAX_SALARY'', oForm.ALIAS, ''LINK, CODE, NAME'', ''REF_PAY, CODE_PAY, NAME_PAY'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr05'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAX_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_TAX_SALARY'',EVALUATE(m.cAliasOperate+''.REF_PAY''))'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'TITLE', 'Удержание'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox05'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAX_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_TAX_SALARY'',EVALUATE(m.cAliasOperate+''.REF_PAY''))'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAX_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".REF_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAX_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAX_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'TITLE', 'Дата начала'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'ORDER_NUMBER', '11'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".DATE1"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE1"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_K_WRIT', 'CONTROL_NAME_EDIT', 'Aseldate12'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'TITLE', 'Дата окончания'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'ORDER_NUMBER', '12'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".DATE2"'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE2"'
GO
EXEC X_SET_PROP 'COLUMN_DATE2_K_WRIT', 'CONTROL_NAME_EDIT', 'Aseldate13'
GO
EXEC X_SET_PROP 'COLUMN_REF_PHYS_PERS_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".REF_PHYS_PERS"'
GO
EXEC X_SET_PROP 'COLUMN_REF_PHYS_PERS_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_PHYS_PERS_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_PHYS_PERS"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'TITLE', 'Получатель'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "REF_ORGANIZATION, COD_ORGANIZATION, NAM_ORGANIZATION", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".COD_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(8)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COD_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr04'
GO
EXEC X_SET_PROP 'COLUMN_CODE_RECIP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_DEPARTMENT'',EVALUATE(m.cAliasOperate+''.REF_ORGANIZATION''))'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'TITLE', 'Получатель'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".NAM_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAM_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox04'
GO
EXEC X_SET_PROP 'COLUMN_NAME_RECIP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_DEPARTMENT'',EVALUATE(m.cAliasOperate+''.REF_ORGANIZATION''))'
GO
EXEC X_SET_PROP 'COLUMN_REF_RECIP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".REF_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_REF_RECIP_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_RECIP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REF_ORGANIZATION"'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'TITLE', 'Способ перечисления'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".WAY"'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'ROWSOURCE', '''по почте,через кассу,через банк'''
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(3,0)'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".WAY"'
GO
EXEC X_SET_PROP 'COLUMN_WAY_ENUMER_K_WRIT', 'CONTROL_NAME_EDIT', 'Acombobox10'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'TITLE', 'Способ расчета'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".PAYMENT"'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'ROWSOURCE', '''%,сумма'''
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(3,0)'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PAYMENT"'
GO
EXEC X_SET_PROP 'COLUMN_PAYMENT_K_WRIT', 'CONTROL_NAME_EDIT', 'Acombobox07'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'TITLE', 'Сумма за перечисление'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".SUM_ENUM"'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUM_ENUM"'
GO
EXEC X_SET_PROP 'COLUMN_SUM_ENUMER_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox11'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox09'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'TITLE', 'Сумма необх.'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_NEED"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_NEED"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox18'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_NEED_K_WRIT', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'TYPE_FIELD_DICT', 'NUMERIC(15,4)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox06'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_K_WRIT', 'INPUT_MASK', '999 999 999.9999'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox14'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_DEPARTMENT'', oForm.ALIAS, ''LINK, CODE, NAME'', ''REF_ORGP, COD_ORGP, NAM_ORGP'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".COD_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(8)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COD_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'COMMENTARY', 'Организация перечисления'
GO
EXEC X_SET_PROP 'COLUMN_CODE_ORGP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_DEPARTMENT'',EVALUATE(m.cAliasOperate+''.REF_ORGP''))'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".NAM_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAM_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'COMMENTARY', 'Организация перечисления'
GO
EXEC X_SET_PROP 'COLUMN_NAME_ORGP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_DEPARTMENT'',EVALUATE(m.cAliasOperate+''.REF_ORGP''))'
GO
EXEC X_SET_PROP 'COLUMN_REF_ORGP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias+".REF_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_REF_ORGP_K_WRIT', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_REF_ORGP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REF_ORGP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'TITLE', 'Код удержания за перечисление'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_TAX_SALARY'', oForm.ALIAS, ''LINK, CODE, NAME'', ''REF_PAYP, CODE_PAYP, NAME_PAYP'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'COMMENTARY', 'Наименование удержания за перечисление'
GO
EXEC X_SET_PROP 'COLUMN_CODE_TAXP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_TAX_SALARY'',EVALUATE(m.cAliasOperate+''.REF_PAYP''))'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'TITLE', 'Код удержания за перечисление'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'CONTROL_NAME_EDIT', 'Atextbox1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'COMMENTARY', 'Наименование удержания за перечисление'
GO
EXEC X_SET_PROP 'COLUMN_NAME_TAXP_K_WRIT', 'OPERATE_METHOD', 'x_edit_rec(''DICTIONARY_TAX_SALARY'',EVALUATE(m.cAliasOperate+''.REF_PAYP''))'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAXP_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".REF_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAXP_K_WRIT', 'TYPE_FIELD_DICT', 'iNT'
GO
EXEC X_SET_PROP 'COLUMN_REF_TAXP_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_PAYP"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_K_WRIT', 'TYPE_FIELD_DICT', 'iNT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.ALIAS, ''LINK,CODE'', ''LINK_VKR,NAME_VKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'CONTROL_NAME_EDIT', 'Asel_spr6'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_K_WRIT', 'COMMENTARY', 'Источник финансирования. Оставьте поле пустым, чтобы рассчитать пропорционально источникам финансирования.'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'TITLE', 'международый перевод'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'CONTROLSOURCE', 'm.cAlias + ".INO"'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".INO"'
GO
EXEC X_SET_PROP 'COLUMN_INO_WRIT', 'CONTROL_NAME_EDIT', 'Acheckbox15'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'WRIT_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 'WRIT_NAME_DEP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'CONTROL_NAME_EDIT', 'cnt_dep.asel_spr01'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'COMMENTARY', 'Наименование организации'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 240px; POSITION: absolute; TOP: 48px""
Width="392px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'WRIT_NAME_DEP', 'FIELD_DATA', 'name_empl'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'TITLE', 'почт. сбор по источникам'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'CONTROLSOURCE', 'm.cAlias + ".PERC_SFIN"'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERC_SFIN"'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'CONTROL_NAME_EDIT', 'Acheckbox11'
GO
EXEC X_SET_PROP 'WRIT_PERC_SFIN', 'COMMENTARY', 'Почтовый сбор будет взиматься отдельно по каждому источку по шкале ставок'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'TITLE', 'без учёта НДФЛ'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'CONTROLSOURCE', 'm.cAlias + ".NO_NDFL"'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NO_NDFL"'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'CONTROL_NAME_EDIT', 'Acheckbox12'
GO
EXEC X_SET_PROP 'WRIT_PERC_NO_NDFL', 'COMMENTARY', 'Сумма по исполнительному листу будет взиматься от дохода без учёта НДФЛ'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'TITLE', 'учет в разрезе ЭКР'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'CONTROLSOURCE', 'm.cAlias + ".BY_EKR"'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BY_EKR"'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'CONTROL_NAME_EDIT', 'Acheckbox13'
GO
EXEC X_SET_PROP 'WRIT_UCHET_BY_EKR', 'COMMENTARY', 'Сумма по исполнительному листу будет расчитываться в разрезе ЭКР (211,213)'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_KADR_WRIT', 'Зарплата-КС', 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 = '4227')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_KADR_WRIT')

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'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4599'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '4599', 'Исполнительные листы', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Вкладка "Общие"******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'S_REP_OPTIONS_ECP_COMMON')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'S_REP_OPTIONS_ECP_COMMON')
	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 = 'S_REP_OPTIONS_ECP_COMMON')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'S_REP_OPTIONS_ECP_COMMON')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'S_REP_OPTIONS_ECP_COMMON'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'S_REP_OPTIONS_ECP_COMMON')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_REP_OPTIONS_ECP_COMMON', 'Вкладка "Общие"', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_ECP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_REP_OPTIONS_ECP_COMMON', NAME = 'Вкладка "Общие"', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_ECP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_REP_OPTIONS_ECP_COMMON'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON_USE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_REP_OPTIONS_ECP_COMMON_USE', 'Использовать ЭЦП', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_REP_OPTIONS_ECP_COMMON_USE', NAME = 'Использовать ЭЦП', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_REP_OPTIONS_ECP_COMMON_USE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'Тип ЭЦП', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_REP_OPTIONS_ECP_COMMON_TYPE', NAME = 'Тип ЭЦП', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_REP_OPTIONS_ECP_COMMON_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_ROUTE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_REP_OPTIONS_ECP_ROUTE', 'Использовать ЭЦП для маршрута согласования', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_REP_OPTIONS_ECP_ROUTE', NAME = 'Использовать ЭЦП для маршрута согласования', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_REP_OPTIONS_ECP_ROUTE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RS_REP_OPTIONS_ECP_IP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RS_REP_OPTIONS_ECP_IP', 'Адрес сервера сертификатов', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RS_REP_OPTIONS_ECP_IP', NAME = 'Адрес сервера сертификатов', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RS_REP_OPTIONS_ECP_IP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_ROUTE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_REP_OPTIONS_ECP_ROUTE_1', 'Не выводить отчет в режиме "Документы для проверки" если он не подписан организацией', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_REP_OPTIONS_ECP_ROUTE_1', NAME = 'Не выводить отчет в режиме "Документы для проверки" если он не подписан организацией', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_REP_OPTIONS_ECP_ROUTE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RS_REP_OPTIONS_ECP_OID')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RS_REP_OPTIONS_ECP_OID', 'Назначение сертификата (OID)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RS_REP_OPTIONS_ECP_OID', NAME = 'Назначение сертификата (OID)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RS_REP_OPTIONS_ECP_OID'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RS_REP_OPTIONS_MINECP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RS_REP_OPTIONS_MINECP', 'Минимальное количество ЭЦП для установки Готов к проверке', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RS_REP_OPTIONS_MINECP', NAME = 'Минимальное количество ЭЦП для установки Готов к проверке', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RS_REP_OPTIONS_MINECP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RS_REP_OPTIONS_REPORTREADONLY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RS_REP_OPTIONS_REPORTREADONLY', 'Запрещать редактировать отчет подписанный ЭЦП', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RS_REP_OPTIONS_REPORTREADONLY', NAME = 'Запрещать редактировать отчет подписанный ЭЦП', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RS_REP_OPTIONS_REPORTREADONLY'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON', 'SELECT_RECORDS_METHOD', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_ECP'', m.cAlias)'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_ECP'', m.cAlias)'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'TITLE', 'Использовать ЭЦП'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'CONTROLSOURCE', 'm.cAlias + ''.UseECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'SHORT_CODE_OBJ', 'UseECP'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.UseECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_USE', 'CONTROL_NAME_EDIT', 'chkUseECP'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'TITLE', 'Тип ЭЦП'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'CONTROLSOURCE', 'm.cAlias + ''.TypeECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'SHORT_CODE_OBJ', 'TypeECP'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.TypeECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_COMMON_TYPE', 'CONTROL_NAME_EDIT', 'aoptType'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'TITLE', 'Использовать ЭЦП для маршрута согласования'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'CONTROLSOURCE', 'm.cAlias + ''.UseECPRoute'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'SHORT_CODE_OBJ', 'UseECPRoute'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.UseECPRoute'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE', 'CONTROL_NAME_EDIT', 'chkUseECPRoute'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'TITLE', 'Адрес сервера сертификатов'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'CONTROLSOURCE', 'm.cAlias + ''.serverIP'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'SHORT_CODE_OBJ', 'serverIP'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.serverIP'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_IP', 'CONTROL_NAME_EDIT', 'txtServerIP'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'TITLE', 'Не выводить отчет в режиме "Документы для проверки" если он не подписан организацией'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'CONTROLSOURCE', 'm.cAlias + ''.ToRouteWithECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'SHORT_CODE_OBJ', 'ToRouteWithECP'
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ToRouteWithECP'''
GO
EXEC X_SET_PROP 'S_REP_OPTIONS_ECP_ROUTE_1', 'CONTROL_NAME_EDIT', 'chkToRouteWithECP'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'TITLE', 'Назначение сертификата (OID)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'CONTROLSOURCE', 'm.cAlias + ''.OID'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'SHORT_CODE_OBJ', 'OID'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.OID'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_ECP_OID', 'CONTROL_NAME_EDIT', 'txtOID'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'TITLE', 'Минимальное количество ЭЦП для установки Готов к проверке'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'CONTROLSOURCE', 'm.cAlias + ''.MinECP'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'SHORT_CODE_OBJ', 'OID'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.MinECP'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_MINECP', 'CONTROL_NAME_EDIT', 'atxtMinECP'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'TITLE', 'Запрещать редактировать отчет подписанный ЭЦП'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'CONTROLSOURCE', 'm.cAlias + ''.ReportReadOnly'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'SHORT_CODE_OBJ', 'ReportReadOnly'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ReportReadOnly'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_REPORTREADONLY', 'CONTROL_NAME_EDIT', 'achkReportReadOnly'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'S_REP_OPTIONS_ECP_COMMON', 'Главный бухгалтер', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'S_REP_OPTIONS_ECP_COMMON', 'Свод-КС', 5,0
GO


GO
if not exists(SELECT * FROM dbo.report_options WHERE [Razdel] = 'ECP' AND Code = 'ReportReadOnly')
BEGIN
   INSERT dbo.[REPORT_OPTIONS] ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Int], [SID])
   VALUES ('ECP', 'ReportReadOnly', 6, 'Запрещать редактировать отчет подписанный ЭЦП', 1, 0, 0x01)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] 'ECP'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'ECP'   
END
GO

GO
IF not exists(select * from dbo.formula_bridge where name = '4ФСС_09022012_УСТАНОВКА' and PROC_NAME = 'SA_4FSS_09022012_PREPARE')
begin
  	
  IF not exists(select * from dbo.DICTION where name = '4ФСС_09022012_УСТАНОВКА')
  begin
		-- insert формулы установки в таблицу dbo.DICTION  
		declare @linkObjF int,
				@LinkOBJ int
							
		set @linkObjF  = (select link from dbo.s_objects where code = 'FORMULA_BRIDGE')
  
		insert into  dbo.DICTION (NAME,[OBJECT], CODE, begindate, enddate)
			values ('4ФСС_09022012_УСТАНОВКА', @linkObjF, NULL, '17530101','99991231')
		
		set @LinkOBJ = (select link from dbo.DICTION where name = '4ФСС_09022012_УСТАНОВКА')
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = '4ФСС_09022012_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_ORDERS'))
		begin	
			declare @linkObjF_ORD int 
					
			set @linkObjF_ORD = (select link from dbo.s_objects where code = 'FORMULA_ORDERS') 
			
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_ORD, '9')		
				
		end
		-- insert процедуры обработки для формулы в таблицу dbo.DICTION_APP 		
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = '4ФСС_09022012_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_PROCEDURE'))
		begin	
			
			declare @linkObjF_PROC int 
					
			set @linkObjF_PROC = (select link from dbo.s_objects where code = 'FORMULA_PROCEDURE') 
		
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_PROC, 'SA_4FSS_09022012_PREPARE')		
 
		end
			
  end	
 
end   
GO

GO
IF not exists(select * from dbo.formula_bridge where name = 'РСВ1_12_УСТАНОВКА' and PROC_NAME = 'SA_RSV_1_12_PFR_PREPARE')
begin
  	
  IF not exists(select * from dbo.DICTION where name = 'РСВ1_12_УСТАНОВКА')
  begin
		-- insert формулы установки в таблицу dbo.DICTION  
		declare @linkObjF int,
				@LinkOBJ int
							
		set @linkObjF  = (select link from dbo.s_objects where code = 'FORMULA_BRIDGE')
  
		insert into  dbo.DICTION (NAME,[OBJECT], CODE, begindate, enddate)
			values ('РСВ1_12_УСТАНОВКА', @linkObjF, NULL, '17530101','99991231')
		
		set @LinkOBJ = (select link from dbo.DICTION where name = 'РСВ1_12_УСТАНОВКА')
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_12_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_ORDERS'))
		begin	
			declare @linkObjF_ORD int 
					
			set @linkObjF_ORD = (select link from dbo.s_objects where code = 'FORMULA_ORDERS') 
			
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_ORD, '9')		
				
		end
		-- insert процедуры обработки для формулы в таблицу dbo.DICTION_APP 		
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_12_УСТАНОВКА') and [object] = (select link from s_objects where  code = 'FORMULA_PROCEDURE'))
		begin	
			
			declare @linkObjF_PROC int 
					
			set @linkObjF_PROC = (select link from dbo.s_objects where code = 'FORMULA_PROCEDURE') 
		
			insert into  dbo.DICTION_APP (LINK_UP,[OBJECT], VALUE)
				values (@LinkOBJ, @linkObjF_PROC, 'SA_RSV_1_12_PFR_PREPARE')		
 
		end
			
  end	
 
end   
GO

GO

DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_MANAGER_COMMENT' -- 'KOD_MY_EXZAM' - код запроса
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Отзыв руководителя',401,								-- 'Тестовый отчет' - название отчета
	(Select link from object_var where code = 'KADRY_CHIN_REPORTS'),	-- 'KADRY_FREE_RESERVE' - код папки,в которой расположен отчет
	'KOD_MANAGER_COMMENT',NULL, NULL, 1		


GO
-- Отчет "Присвоение классного чина"
-- Сгенерировано скриптом scriptObjectVar 'KOD_ASSIGNMENT_CLASS_CHIN'

/*** Сам отчет ***/

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= 'KOD_ASSIGNMENT_CLASS_CHIN'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_ASSIGNMENT_CLASS_CHIN'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Присвоение классного чина',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_ASSIGNMENT_CLASS_CHIN',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_ASSIGNMENT_CLASS_CHIN') 
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_ASSIGNMENT_CLASS_CHIN @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_ASSIGNMENT_CLASS_CHIN'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"ASSIGNMENT_CLASS_CHIN.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_ASSIGNMENT_CLASS_CHIN
	@nSel_Spr1 int	/* Сотрудник */
AS
BEGIN

exec dbo.KO_REP_ASSIGNMENT_CLASS_CHIN @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	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 = 'KOD_ASSIGNMENT_CLASS_CHIN') 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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_ASSIGNMENT_CLASS_CHIN_G1' 
		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 = 'KOD_ASSIGNMENT_CLASS_CHIN'),
		'KOD_ASSIGNMENT_CLASS_CHIN_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_G1'),
					'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'20'
						
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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_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 = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_ASSIGNMENT_CLASS_CHIN_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
/****** Объект: График аттестации******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ATT_GRAPHIC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ATT_GRAPHIC')
	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 = 'ATT_GRAPHIC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ATT_GRAPHIC')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ATT_GRAPHIC'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ATT_GRAPHIC')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC', 'График аттестации', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATTESTATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC', NAME = 'График аттестации', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATTESTATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='ATT_GRAPHIC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_NUMBER', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_NUMBER', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_DATE', 'Дата', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_DATE', NAME = 'Дата', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_COMMENT', 'Комментарий', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_COMMENT', NAME = 'Комментарий', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_PERIOD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_PERIOD', 'Период', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_PERIOD', NAME = 'Период', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_PERIOD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_CODE', 'Код', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_CODE', NAME = 'Код', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE', 'График аттестаций (таблица)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE', NAME = 'График аттестаций (таблица)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='VAC_GRAPHIC_STATUS_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'VAC_GRAPHIC_STATUS_1', 'Статус', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'VAC_GRAPHIC_STATUS_1', NAME = 'Статус', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='VAC_GRAPHIC_STATUS_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_EMPL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_EMPL_LINK', 'Ссылка на сотрудника', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_EMPL_LINK', NAME = 'Ссылка на сотрудника', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_EMPL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_TAB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_TAB', 'Табельный номер', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_TAB', NAME = 'Табельный номер', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_TAB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_FIO', 'ФИО сотрудника (редактирование)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_FIO', NAME = 'ФИО сотрудника (редактирование)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_FIO2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_FIO2', 'ФИО сотрудника (просмотр)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_FIO2', NAME = 'ФИО сотрудника (просмотр)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_FIO2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_POST', 'Должность', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_POST', NAME = 'Должность', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_SUBDIV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_SUBDIV', 'Подразделение', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_SUBDIV', NAME = 'Подразделение', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_SUBDIV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_TIME_HOURS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'Время проведения ЧАСЫ', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_TIME_HOURS', NAME = 'Время проведения ЧАСЫ', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_TIME_HOURS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_DATE', 'Дата проведения', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_DATE', NAME = 'Дата проведения', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_TIME_MINUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'Время проведения МИНУТЫ', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_TIME_MINUT', NAME = 'Время проведения МИНУТЫ', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_TIME_MINUT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE_PLACE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ATT_GRAPHIC_TABLE_PLACE', 'Место проведения', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ATT_GRAPHIC_TABLE_PLACE', NAME = 'Место проведения', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ATT_GRAPHIC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ATT_GRAPHIC_TABLE_PLACE'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'TITLE', 'График аттестации'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'INIT_OBJECT_METHOD', 'x_spisok(m.Obj_Code)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "VAC_GRAPHIC", "KJ_ATT_GRAPHICS_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'SAVE_OBJECT_METHOD', 'kj_att_graphics_save(oForm)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'EDIT_OBJECT_METHOD', 'kj_brow(''kj_att_graphic'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'SELECT_RECORDS_METHOD', 'sd_select_document_list_zb1(''ATT_GRAPHIC'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''ATT_GRAPHIC'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'HELP_TOPIC', '50'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC', 'OPERATION_MASK', ''
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".Checked"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'CONTROLSOURCE', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'CONTROL_NAME_EDIT', 'numdate1.number'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'COMMENTARY', 'Номер'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_NUMBER', 'ASPTYPE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'CONTROLSOURCE', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'CONTROL_NAME_EDIT', 'numdate1.date'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_DATE', 'COMMENTARY', 'Дата'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'CONTROLSOURCE', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'CONTROL_NAME_EDIT', 'Atextbox04'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_COMMENT', 'COMMENTARY', 'Комментарий'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'TITLE', 'Период'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'CONTROLSOURCE', 'm.cAlias+".PERIOD"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PERIOD"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'CONTROL_NAME_EDIT', 'AYear1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_PERIOD', 'COMMENTARY', 'Начало периода отпусков'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'STORAGE', 'ATTESTAT_GRAPHICS'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'CONTROL_NAME_EDIT', 'Atextbox05'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'COMMENTARY', 'Код'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'FIELD_ALIAS', 'ATT_GRAPHIC'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'TITLE', 'График аттестаций'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'EDIT_OBJECT_METHOD', 'kj_brow_rec(''kj_att_graphic_edit'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'CLOSE_CODE', 'NUM_STR'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'SELECT_RECORDS_METHOD', 'kj_select_table(m.nLinkTable, m.cAlias,''ATT_GRAPHIC_TABLE'',''LINK,NUM_STR,DOC_LINK,EMPL_LINK,FIO,FIO as FIO2,TAB,POST,TTOD(DATE_TIME) as DATE,HOUR(DATE_TIME) as HOUR,MINUTE(DATE_TIME) as MINUTE,PLACE,SUBDIV_NAME,ATTEST_LINK,ATTEST_LINK_NUM'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'SELECT_RECORDS_METHOD_EDIT', 'kj_select_table(m.nLinkTable, m.cAlias,''ATT_GRAPHIC_TABLE'',''LINK,NUM_STR,DOC_LINK,EMPL_LINK,FIO,FIO as FIO2,TAB,POST,TTOD(DATE_TIME) as DATE,HOUR(DATE_TIME) as HOUR,MINUTE(DATE_TIME) as MINUTE,PLACE,SUBDIV_NAME,ATTEST_LINK,ATTEST_LINK_NUM'')'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'OPEN_CODE', 'NUM_STR'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE', 'OPERATION_MASK', ''
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".Checked"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'VAC_GRAPHIC_STATUS_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'VAC_GRAPHIC_STATUS_1', 'CONTROLSOURCE', 'm.cAlias + ".ATTEST_LINK"'
GO
EXEC X_SET_PROP 'VAC_GRAPHIC_STATUS_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'VAC_GRAPHIC_STATUS_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ATTEST_LINK"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_EMPL_LINK', 'CONTROLSOURCE', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_EMPL_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_EMPL_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_EMPL_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'TITLE', 'Таб №'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'CONTROLSOURCE', 'm.cAlias+".TAB"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TAB"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TAB', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'TITLE', 'Сотрудник'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'EDIT_OBJECT_METHOD', 'kj_att_kom_vibor_empl(4,oForm.alias)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'CONTROLSOURCE', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO', 'COMMENTARY', 'Сотрудник'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'TITLE', 'Сотрудник'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'CONTROLSOURCE', 'm.cAlias+".FIO2"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FIO2"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_FIO2', 'COMMENTARY', 'Сотрудник'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'TITLE', 'Должность'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'CONTROLSOURCE', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_POST', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'CONTROLSOURCE', 'm.cAlias+".SUBDIV_NAME"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SUBDIV_NAME"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_SUBDIV', 'CONTROL_NAME_EDIT', 'Atxt6'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'TITLE', 'Часы'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'CONTROLSOURCE', 'm.cAlias+".HOUR"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'TYPE_FIELD_DICT', 'varchar(2)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".HOUR"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_HOURS', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'CONTROLSOURCE', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_DATE', 'CONTROL_NAME_EDIT', 'Asel_date1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'TITLE', 'Минуты'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'CONTROLSOURCE', 'm.cAlias+".MINUTE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'TYPE_FIELD_DICT', 'varchar(2)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".MINUTE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'CONTROL_NAME_EDIT', 'Atxt4'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_TIME_MINUT', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'TITLE', 'Место проведения'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'CONTROLSOURCE', 'm.cAlias+".PLACE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PLACE"'
GO
EXEC X_SET_PROP 'ATT_GRAPHIC_TABLE_PLACE', 'CONTROL_NAME_EDIT', 'Atxt5'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

EXEC DBO.W_SPERM_WRITE 'ATT_GRAPHIC', 'Кадры-КС', 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 = 'KADR_ATTESTAT_FOLDER')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ATT_GRAPHIC')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_ATTESTAT_FOLDER'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_ATTESTAT_GRAPHICS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADR_ATTESTAT_GRAPHICS', 'Графики аттестаций', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Классные чины******/
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_CHIN', 'Классные чины', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_CHIN', NAME = 'Классные чины', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_CHIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_CODE', 'Класс', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_CODE', NAME = 'Класс', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_MONTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_MONTH', 'Количество месяцев', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_MONTH', NAME = 'Количество месяцев', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_MONTH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CHIN_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CHIN_ORDERS', 'Порядок', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CHIN_ORDERS', NAME = 'Порядок', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CHIN_ORDERS'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'TITLE', 'Классные чины'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'INIT_OBJECT_METHOD', 'X_SPISOK("DICTIONARY_CHIN")'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_CHIN", "X_DELETE_DICTIONARY_CHIN", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DICTIONARY_CHIN'', m.cAlias," CODE, NAME,MONTH, ORDERS","DICTIONARY_CHIN")'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'PRINT_OBJECT_METHOD', 'KIR_PRINT_DICTIONARY(oForm.Alias, "DICTIONARY_CHIN")'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'INIT_OBJECT_PROG', 'A_SPISOK_MENU (oForm)
A_SPISOK_UPD(oForm, 0, .T.)'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'INIT_EDIT_OBJECT_PROG', 'A_EDIT_REC_INIT(oForm, "DICTIONARY_CHIN")'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DICTIONARY_CHIN'')'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'DELETE_RECORD_METHOD', 'L_SQLEXEC(m.Handle,"DELETE DICTION WHERE LINK=" + STR(m.nLink))'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''DICTIONARY_CHIN'')'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'CMD_SEARCH', 'A_SRCH(oForm.aGrid1, ''KADR_CHN.SRC'')'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'PREPARE_NEW_RECORD', 'xu_new_table_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''DICTIONARY_CHIN'''
GO
EXEC X_SET_PROP 'DICTIONARY_CHIN', 'SELECT_RECORDS_METHOD_SQL', 'select [checked] =0, code, name, link from dictionary_chin'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'CHIN_CHECKED', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'TITLE', 'Класс'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'ROWSOURCE', '''1,2,3'''
GO
EXEC X_SET_PROP 'CHIN_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'TYPE_FIELD_DICT', 'CHAR(2)'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'CONTROL_NAME_EDIT', 'Acmb1'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'ATTRIBUTES', ' style="Z-INDEX: 103; LEFT: 144px; POSITION: absolute; TOP: 16px"
Width="120px"'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'FIELD_ALIAS', 'DICTIONARY_CHIN'
GO
EXEC X_SET_PROP 'CHIN_CODE', 'FIELD_DATA', 'code'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'CONTROL_NAME_EDIT', 'Atxt2'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 144px; POSITION: absolute; TOP: 56px"
Width="248px"'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px"'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'FIELD_ALIAS', 'DICTIONARY_CHIN'
GO
EXEC X_SET_PROP 'CHIN_NAME', 'FIELD_DATA', 'name'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'TITLE', 'Количество месяцев'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'CONTROLSOURCE', 'm.cAlias+".MONTH"'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'SHORT_CODE_OBJ', 'MONTH'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'CONTROLSOURCE_EDIT', 'm.cAlias+".MONTH"'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'INPUT_MASK', '999'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'COMMENTARY', 'Количество месяцев, по истечение которых можно претендовать на другой классный чин'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 144px; POSITION: absolute; TOP: 56px"
Width="248px"'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px"'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'FIELD_ALIAS', 'DICTIONARY_CHIN'
GO
EXEC X_SET_PROP 'CHIN_MONTH', 'FIELD_DATA', 'MONTH'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'TITLE', 'Порядок'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'CONTROLSOURCE', 'm.cAlias+".ORDERS"'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'SHORT_CODE_OBJ', 'ORDERS'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ORDERS"'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'CONTROL_NAME_EDIT', 'Atxt4'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'INPUT_MASK', '999'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'COMMENTARY', 'Номер п/п в порядке назначения классного чина'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'ATTRIBUTES', ' style="Z-INDEX: 104; LEFT: 144px; POSITION: absolute; TOP: 56px"
Width="248px"'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px"'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'FIELD_ALIAS', 'DICTIONARY_CHIN'
GO
EXEC X_SET_PROP 'CHIN_ORDERS', 'FIELD_DATA', 'ORDERS'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_CHIN', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_CHIN', 'Зарплата-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'DICTIONARY_CHIN', 'Смета-КС', 5,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Классные чины"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICTIONARY_CHIN')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_CHIN'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADR_DICTIONARY_CHIN', 'Классные чины', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


EXECUTE X_FORM_VIEW_DICTIONARY 'DICTIONARY_CHIN'
GO

EXECUTE X_FORM_SAVE_DICTIONARY 'DICTIONARY_CHIN', 'DICTIONARY_CHIN', 1
GO

GO
/****** Объект: Каталог документов по представлению к чину******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_KCHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_KCHIN')
	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 = 'GROUP_DOCUMENTS_KCHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_KCHIN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_KCHIN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_KCHIN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='GROUP_DOCUMENTS_KCHIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'GROUP_DOCUMENTS_KCHIN', 'Каталог документов по представлению к чину', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'GROUP_DOCUMENTS_KCHIN', NAME = 'Каталог документов по представлению к чину', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='GROUP_DOCUMENTS_KCHIN'
GO
EXEC X_SET_PROP 'GROUP_DOCUMENTS_KCHIN', 'SELECT_RECORDS_METHOD', 'KIR_GET_DOCS_BY_CODE(''KADRY_CHIN_REPORTS'')'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Каталог документов по изменении должности******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_REP_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_REP_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_REP_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_REP_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_REP_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_REP_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='GROUP_DOCUMENTS_REP_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'GROUP_DOCUMENTS_REP_POST', 'Каталог документов по изменении должности', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'GROUP_DOCUMENTS_REP_POST', NAME = 'Каталог документов по изменении должности', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='GROUP_DOCUMENTS_REP_POST'
GO
EXEC X_SET_PROP 'GROUP_DOCUMENTS_REP_POST', 'SELECT_RECORDS_METHOD', 'KIR_GET_DOCS_BY_CODE(''KADRY_REPLACE_POST'')'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'GROUP_DOCUMENTS_REP_POST', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'GROUP_DOCUMENTS_REP_POST', 'public', 5,0
GO

GO
-- Отчет "График отпусков (Форма № Т-7)"
-- Сгенерировано скриптом scriptObjectVar 'KJ_VACATION_GRAPHICS'

/*** Сам отчет ***/

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= 'KJ_VACATION_GRAPHICS'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KJ_VACATION_GRAPHICS'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'График отпусков (Форма № Т-7)',NULL, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KJ_VACATION_GRAPHICS',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS') 
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= 'declare @temp varchar(12) 	'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KJ_VACATION_GRAPHICS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"KJ_VACATION_GRAPHICS.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KJ_VACATION_GRAPHICS
	@nSel_Spr1 int	/* Ссылка на график отпусков */,
	@nCheck1 int	/* Январь */,
	@nCheck2 int	/* Февраль */,
	@nCheck3 int	/* Март */,
	@nCheck4 int	/* Апрель */,
	@nCheck5 int	/* Май */,
	@nCheck6 int	/* Июнь */,
	@nCheck7 int	/* Июль */,
	@nCheck8 int	/* Август */,
	@nCheck9 int	/* Сентябрь */,
	@nCheck10 int	/* Октябрь */,
	@nCheck11 int	/* Ноябрь */,
	@nCheck12 int	/* Декабрь */,
	@nCheck13 int	/* Отображать пустые графики */,
	@nCheck14 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_SUBDIV''))
	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 @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1

declare @temp varchar(12) 	
END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	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 = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_VACATION_GRAPHICS') 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 = 'KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_FILTER' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'KJ_VACATION_GRAPHICS'),
		'KJ_VACATION_GRAPHICS_FILTER',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_OTBOR' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_SUBDIV'),
					'Отбор подразделений',1, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_FILTER'),
					'KJ_VACATION_GRAPHICS_OTBOR',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 = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_SUBDIVISION01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_GROUP' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',2, 
		(Select link from object_var where code = 'KJ_VACATION_GRAPHICS'),
		'KJ_VACATION_GRAPHICS_GROUP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_ALL' 
					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'),
					'Печать по всем графикам организации с фильтром по подразделениям',17, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_ALL',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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'14'
						
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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck14'
						
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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_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 = 'KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Январь',4, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(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 = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Будут отображаться графики за этот месяц'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param10' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Октябрь',13, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param10',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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'10'
						
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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck10'
						
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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param11' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Ноябрь',14, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param11',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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'11'
						
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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck11'
						
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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param12' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Декабрь',15, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param12',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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'12'
						
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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck12'
						
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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param13' 
					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'),
					'Отображать пустые графики',16, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param13',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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'13'
						
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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck13'
						
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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param2' 
					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'),
					'Февраль',5, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param2',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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param3' 
					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'),
					'Март',6, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param3',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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param4' 
					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'),
					'Апрель',7, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param4',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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param5' 
					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 = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param5',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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param6' 
					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'),
					'Июнь',9, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param6',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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param7' 
					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'),
					'Июль',10, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param7',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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param8' 
					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'),
					'Август',11, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param8',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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'8'
						
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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck8'
						
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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_VACATION_GRAPHICS_param9' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Сентябрь',12, 
					(Select link from object_var where code = 'KJ_VACATION_GRAPHICS_GROUP'),
					'KJ_VACATION_GRAPHICS_param9',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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'9'
						
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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck9'
						
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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "График отпусков с датой окончания отпуска"
-- Сгенерировано скриптом scriptObjectVar 'KOD_KJ_VACATION_GRAPHICS'

/*** Сам отчет ***/

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= 'KOD_KJ_VACATION_GRAPHICS'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'График отпусков с датой окончания отпуска',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_KJ_VACATION_GRAPHICS',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS') 
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= 'declare @temp varchar(12) 	'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_KJ_VACATION_GRAPHICS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"KJ_VACATION_GRAPHICS_2.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_KJ_VACATION_GRAPHICS
	@nSel_Spr1 int	/* Ссылка на график отпусков */,
	@nCheck1 int	/* Январь */,
	@nCheck2 int	/* Февраль */,
	@nCheck3 int	/* Март */,
	@nCheck4 int	/* Апрель */,
	@nCheck5 int	/* Май */,
	@nCheck6 int	/* Июнь */,
	@nCheck7 int	/* Июль */,
	@nCheck8 int	/* Август */,
	@nCheck9 int	/* Сентябрь */,
	@nCheck10 int	/* Октябрь */,
	@nCheck11 int	/* Ноябрь */,
	@nCheck12 int	/* Декабрь */,
	@nCheck13 int	/* Отображать пустые графики */,
	@nCheck14 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_SUBDIV''))
	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 @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1

declare @temp varchar(12) 	
END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	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 = 'KOD_KJ_VACATION_GRAPHICS') 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 = 'KOD_KJ_VACATION_GRAPHICS'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_FILTER' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS'),
		'KOD_KJ_VACATION_GRAPHICS_FILTER',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_OTBOR' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_SUBDIV'),
					'Отбор подразделений',1, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_FILTER'),
					'KOD_KJ_VACATION_GRAPHICS_OTBOR',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 = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_SUBDIVISION01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_GROUP' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',2, 
		(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS'),
		'KOD_KJ_VACATION_GRAPHICS_GROUP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_ALL' 
					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'),
					'Печать по всем графикам организации с фильтром по подразделениям',17, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_ALL',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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'14'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck14'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_ALL'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'4'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_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 = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Январь',4, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Будут отображаться графики за этот месяц'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param10' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Октябрь',13, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param10',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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'10'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck10'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param10'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param11' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Ноябрь',14, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param11',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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'11'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck11'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param11'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param12' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Декабрь',15, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param12',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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'12'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck12'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param12'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param13' 
					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'),
					'Отображать пустые графики',16, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param13',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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'13'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck13'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param13'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param2' 
					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'),
					'Февраль',5, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param2',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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param3' 
					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'),
					'Март',6, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param3',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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param4' 
					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'),
					'Апрель',7, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param4',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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param5' 
					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 = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param5',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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param6' 
					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'),
					'Июнь',9, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param6',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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param7' 
					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'),
					'Июль',10, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param7',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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param8' 
					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'),
					'Август',11, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param8',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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'8'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck8'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_param9' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Сентябрь',12, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_param9',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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'9'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck9'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_param9'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "График отпусков с датой окончания отпуска"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KJ_VACATION_GRAPHICS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KJ_VACATION_GRAPHICS', 'График отпусков с датой окончания отпуска', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO


GO
-- Отчет "График отпусков(форма № Т-7)"
-- Сгенерировано скриптом scriptObjectVar 'KOD_KJ_VACATION_GRAPHICS_T7'

/*** Сам отчет ***/

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= 'KOD_KJ_VACATION_GRAPHICS_T7'  

 
GO
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'График отпусков(форма № Т-7)',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_KJ_VACATION_GRAPHICS_T7',NULL, NULL, 1

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7') 
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= 'declare @temp varchar(12) 	'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'declare @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_KJ_VACATION_GRAPHICS_T7'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"KJ_VACATION_GRAPHICS.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_KJ_VACATION_GRAPHICS_T7
	@nSel_Spr1 int	/* Ссылка на график отпусков */,
	@nCheck1 int	/* Январь */,
	@nCheck2 int	/* Февраль */,
	@nCheck3 int	/* Март */,
	@nCheck4 int	/* Апрель */,
	@nCheck5 int	/* Май */,
	@nCheck6 int	/* Июнь */,
	@nCheck7 int	/* Июль */,
	@nCheck8 int	/* Август */,
	@nCheck9 int	/* Сентябрь */,
	@nCheck10 int	/* Октябрь */,
	@nCheck11 int	/* Ноябрь */,
	@nCheck12 int	/* Декабрь */,
	@nCheck13 int	/* Отображать пустые графики */,
	@nCheck14 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_SUBDIV''))
	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 @month_mask varchar(13) 	
set @month_mask = convert(varchar(1),@nCheck1) + convert(varchar(1),@nCheck2) + convert(varchar(1),@nCheck3) + convert(varchar(1),@nCheck4) + convert(varchar(1),@nCheck5) + convert(varchar(1),@nCheck6) + convert(varchar(1),@nCheck7) + convert(varchar(1),@nCheck8) + convert(varchar(1),@nCheck9) + convert(varchar(1),@nCheck10) + convert(varchar(1),@nCheck11) + convert(varchar(1),@nCheck12) + convert(varchar(1),@nCheck13)

exec KJ_VACATION_GRAPHICS @nSel_Spr1, @month_mask, @nCheck14, @nOtborLink1

declare @temp varchar(12) 	
END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	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 = 'KOD_KJ_VACATION_GRAPHICS_T7') 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 = 'KOD_KJ_VACATION_GRAPHICS_T7'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_FILTER' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7'),
		'KOD_KJ_VACATION_GRAPHICS_T7_FILTER',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_SUBDIV'),
					'Отбор подразделений',1, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_FILTER'),
					'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_SUBDIVISION01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_OTBOR'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',2, 
		(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7'),
		'KOD_KJ_VACATION_GRAPHICS_T7_GROUP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL' 
					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'),
					'Печать по всем графикам организации с фильтром по подразделениям',17, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_ALL',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'14'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck14'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_ALL'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'4'
						
						
						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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'6'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_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 = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Январь',4, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Будут отображаться графики за этот месяц'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param10' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Октябрь',13, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param10',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'10'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck10'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param10') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param10'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param11' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Ноябрь',14, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param11',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'11'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck11'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param11') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param11'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param12' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Декабрь',15, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param12',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'12'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck12'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param12') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param12'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param13' 
					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'),
					'Отображать пустые графики',16, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param13',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'13'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck13'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param13') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param13'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param2' 
					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'),
					'Февраль',5, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param2',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param3' 
					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'),
					'Март',6, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param3',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck3'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param4' 
					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'),
					'Апрель',7, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param4',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck4'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param5' 
					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 = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param5',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck5'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param6' 
					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'),
					'Июнь',9, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param6',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param7' 
					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'),
					'Июль',10, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param7',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck7'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param8' 
					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'),
					'Август',11, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param8',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'8'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck8'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7_param9' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Сентябрь',12, 
					(Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_GROUP'),
					'KOD_KJ_VACATION_GRAPHICS_T7_param9',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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'9'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck9'
						
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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(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 = 'KOD_KJ_VACATION_GRAPHICS_T7_param9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_KJ_VACATION_GRAPHICS_T7_param9'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "Отзыв руководителя"
-- Сгенерировано скриптом scriptObjectVar 'KOD_MANAGER_COMMENT'

/*** Сам отчет ***/

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= 'KOD_MANAGER_COMMENT'  

 
GO

	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_MANAGER_COMMENT'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Отзыв руководителя',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_MANAGER_COMMENT',NULL, NULL, 1
	
	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_MANAGER_COMMENT') 
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_MANAGER_COMMENT @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_MANAGER_COMMENT'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"MANAGER_COMMENT.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_MANAGER_COMMENT
	@nSel_Spr1 int	/* Сотрудник */
AS
BEGIN

exec dbo.KO_REP_MANAGER_COMMENT @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	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 = 'KOD_MANAGER_COMMENT') 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 = 'KOD_MANAGER_COMMENT'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_MANAGER_COMMENT_G1' 
		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 = 'KOD_MANAGER_COMMENT'),
		'KOD_MANAGER_COMMENT_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_MANAGER_COMMENT_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_MANAGER_COMMENT_G1'),
					'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'20'
						
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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_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 = 'KOD_MANAGER_COMMENT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_MANAGER_COMMENT_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "Постановление о приеме на работу"
-- Сгенерировано скриптом scriptObjectVar 'KOD_POSTANOVLENIE_NEW_POST'

/*** Сам отчет ***/

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= 'KOD_POSTANOVLENIE_NEW_POST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_POSTANOVLENIE_NEW_POST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Постановление о приеме на работу',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_POSTANOVLENIE_NEW_POST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_POST') 
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_POSTANOVLENIE_NEW_POST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"POSTANOVLENIE.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_POSTANOVLENIE_NEW_POST
	@nSel_Spr1 int	/* Сотрудник */,
	@nSel_Spr2 int	/* Пункт №1 */,
	@nSel_Spr3 int	/* Пункт №2 */,
	@nSel_Spr4 int	/* Пункт №3 */,
	@nSel_Spr5 int	/* Пункт №4 */,
	@nSel_Spr6 int	/* Пункт №5 */
AS
BEGIN

exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	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 = 'KOD_POSTANOVLENIE_NEW_POST') 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 = 'KOD_POSTANOVLENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_CODE'),
	VALUE= ''
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_G1' 
		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 = 'KOD_POSTANOVLENIE_NEW_POST'),
		'KOD_POSTANOVLENIE_NEW_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'302096'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'    302096'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'    302146'
						
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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_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 = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_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_LSEL_SPR'),
					'Пункт №1',3, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr2'
						
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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_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_LSEL_SPR'),
					'Пункт №2',4, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №2'
						
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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr3'
						
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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_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_LSEL_SPR'),
					'Пункт №3',5, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №3'
						
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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr4'
						
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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_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_LSEL_SPR'),
					'Пункт №4',6, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №4'
						
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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr5'
						
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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_NEW_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_LSEL_SPR'),
					'Пункт №5',7, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_G1'),
					'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №5'
						
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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr6'
						
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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
						
						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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_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 = 'KOD_POSTANOVLENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_NEW_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO


GO
-- Отчет "Постановление о переводе на другую должность"
-- Сгенерировано скриптом scriptObjectVar 'KOD_POSTANOVLENIE_REPLACE_POST'

/*** Сам отчет ***/

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= 'KOD_POSTANOVLENIE_REPLACE_POST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_POSTANOVLENIE_REPLACE_POST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Постановление о переводе на другую должность',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_POSTANOVLENIE_REPLACE_POST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_REPLACE_POST') 
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,2'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_POSTANOVLENIE_REPLACE_POST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"POSTANOVLENIE.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_POSTANOVLENIE_REPLACE_POST
	@nSel_Spr1 int	/* Сотрудник */,
	@nSel_Spr2 int	/* Пункт №1 */,
	@nSel_Spr3 int	/* Пункт №2 */,
	@nSel_Spr4 int	/* Пункт №3 */,
	@nSel_Spr5 int	/* Пункт №4 */,
	@nSel_Spr6 int	/* Пункт №5 */
AS
BEGIN

exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,2

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	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 = 'KOD_POSTANOVLENIE_REPLACE_POST') 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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_CODE'),
	VALUE= ''
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_G1' 
		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 = 'KOD_POSTANOVLENIE_REPLACE_POST'),
		'KOD_POSTANOVLENIE_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_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 = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_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_LSEL_SPR'),
					'Пункт №1',3, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №1'
						
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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr2'
						
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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_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_LSEL_SPR'),
					'Пункт №2',4, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №2'
						
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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr3'
						
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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_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_LSEL_SPR'),
					'Пункт №3',5, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №3'
						
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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr4'
						
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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_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_LSEL_SPR'),
					'Пункт №4',6, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №4'
						
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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr5'
						
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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_POSTANOVLENIE_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_LSEL_SPR'),
					'Пункт №5',7, 
					(Select link from object_var where code = 'KOD_POSTANOVLENIE_G1'),
					'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №5'
						
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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr6'
						
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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_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 = 'KOD_POSTANOVLENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_POSTANOVLENIE_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO


GO
-- Отчет "Распоряжение о приеме на работу"
-- Сгенерировано скриптом scriptObjectVar 'KOD_RASPORIAZENIE_NEW_POST'

/*** Сам отчет ***/

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= 'KOD_RASPORIAZENIE_NEW_POST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_RASPORIAZENIE_NEW_POST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Распоряжение о приеме на работу',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_RASPORIAZENIE_NEW_POST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_POST') 
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_RASPORIAZENIE_NEW_POST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"RASPORIAZENIE.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_RASPORIAZENIE_NEW_POST
	@nSel_Spr1 int	/* Сотрудник */,
	@nSel_Spr2 int	/* Пункт №1 */,
	@nSel_Spr3 int	/* Пункт №2 */,
	@nSel_Spr4 int	/* Пункт №3 */,
	@nSel_Spr5 int	/* Пункт №4 */,
	@nSel_Spr6 int	/* Пункт №5 */
AS
BEGIN

exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	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 = 'KOD_RASPORIAZENIE_NEW_POST') 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 = 'KOD_RASPORIAZENIE_NEW_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_CODE'),
	VALUE= ''
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_G1' 
		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 = 'KOD_RASPORIAZENIE_NEW_POST'),
		'KOD_RASPORIAZENIE_NEW_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'    302146'
						
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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_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 = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_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_LSEL_SPR'),
					'Пункт №1',3, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr2'
						
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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_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_LSEL_SPR'),
					'Пункт №2',4, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №2'
						
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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_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_LSEL_SPR'),
					'Пункт №3',5, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr4'
						
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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_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_LSEL_SPR'),
					'Пункт №4',6, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №4'
						
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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr5'
						
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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_NEW_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_LSEL_SPR'),
					'Пункт №5',7, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_G1'),
					'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №5'
						
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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV1'
						
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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr6'
						
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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'3'
						
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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_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 = 'KOD_RASPORIAZENIE_NEW_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_NEW_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO


GO
-- Отчет "Распоряжение о переводе на другую должность"
-- Сгенерировано скриптом scriptObjectVar 'KOD_RASPORIAZENIE_REPLACE_POST'

/*** Сам отчет ***/

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= 'KOD_RASPORIAZENIE_REPLACE_POST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KOD_RASPORIAZENIE_REPLACE_POST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Распоряжение о переводе на другую должность',401, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KOD_RASPORIAZENIE_REPLACE_POST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_REPLACE_POST') 
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,2'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KOD_RASPORIAZENIE_REPLACE_POST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"RASPORIAZENIE.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KOD_RASPORIAZENIE_REPLACE_POST
	@nSel_Spr1 int	/* Сотрудник */,
	@nSel_Spr2 int	/* Пункт №1 */,
	@nSel_Spr3 int	/* Пункт №2 */,
	@nSel_Spr4 int	/* Пункт №3 */,
	@nSel_Spr5 int	/* Пункт №4 */,
	@nSel_Spr6 int	/* Пункт №5 */
AS
BEGIN

exec dbo.KO_REP_RASPORIAZENIE @nSel_Spr1, @nSel_Spr2, @nSel_Spr3 , @nSel_Spr4,@nSel_Spr5, @nSel_Spr6,2

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	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 = 'KOD_RASPORIAZENIE_REPLACE_POST') 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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_CODE'),
	VALUE= ''
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_G1' 
		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 = 'KOD_RASPORIAZENIE_REPLACE_POST'),
		'KOD_RASPORIAZENIE_G1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Сотрудник',2, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'    302096'
						
						
						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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'302096'
						
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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_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 = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_REPLACE_POST_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_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_LSEL_SPR'),
					'Пункт №1',3, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №1'
						
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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr2'
						
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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_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_LSEL_SPR'),
					'Пункт №2',4, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №2'
						
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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr3'
						
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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_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_LSEL_SPR'),
					'Пункт №3',5, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №3'
						
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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr4'
						
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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_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_LSEL_SPR'),
					'Пункт №4',6, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №4'
						
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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr5'
						
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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KOD_RASPORIAZENIE_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_LSEL_SPR'),
					'Пункт №5',7, 
					(Select link from object_var where code = 'KOD_RASPORIAZENIE_G1'),
					'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пункт №5'
						
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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'6'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'KO_PUNKT_POSTANOV2'
						
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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr6'
						
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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_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 = 'KOD_RASPORIAZENIE_N6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KOD_RASPORIAZENIE_N6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO

GO
/****** Объект: Пункты постановления/распоряжения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV')
	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 = 'KO_PUNKT_POSTANOV')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KO_PUNKT_POSTANOV', 'Пункты постановления/распоряжения', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KO_PUNKT_POSTANOV', NAME = 'Пункты постановления/распоряжения', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KO_PUNKT_POSTANOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_TYP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_TYP', 'Тип приказа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_TYP', NAME = 'Тип приказа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_TYP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_NAME', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_NAME', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_COD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_COD', 'Код приказа', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_COD', NAME = 'Код приказа', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_COD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_SH_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_SH_NAME', 'Наименование (короткое)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_SH_NAME', NAME = 'Наименование (короткое)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_SH_NAME'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'TITLE', 'Пункты постановления / распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'INIT_OBJECT_METHOD', 'XA_SPISOK_WITH_PRINT(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KO_PUNKT_POSTANOV", "KO_PUNKT_POSTANOV_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KO_PUNKT_POSTANOV_SAVE'', m.cAlias," CODE, NAME,PRIK_TYP_N, PRIK_TYP","ko_punkt_postanov")'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'EDIT_OBJECT_METHOD', 'K_BROW(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE),'''', CODE) + [-] + IIF(ISNULL(NAME), '''', NAME) + [-] + IIF(ISNULL(PRIK_TYP_N), '''', PRIK_TYP_N)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SERVER_TABLE_NAME', 'ko_punkt_postanov'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'HELP_TOPIC', 'Пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROL_NAME', 'ATxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'TITLE', 'Тип приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("ORDER_TYPES", oForm.alias, "CODE, NAME", "PRIK_TYP, PRIK_TYP_N", "", "", "CODE IN (1,2,101,102)", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP_N"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP_N"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROL_NAME', 'Asel_spr2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'DICTIONARY', 'ORDER_TYPES'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(2000)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROL_NAME', 'ATxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'TITLE', 'Код приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'DICTIONARY', 'ORDER_TYPES'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'CONTROLSOURCE', 'm.cAlias+".SH_NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SH_NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_SH_NAME', 'QUICKSEARCH', '1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KO_PUNKT_POSTANOV', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'KO_PUNKT_POSTANOV', 'Зарплата-КС', 4,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Пункты постановления/распоряжения"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'PUNKT_POSTANOVLENIA'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'PUNKT_POSTANOVLENIA', 'Пункты постановления/распоряжения', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Приказ о приёме: пункты постановления/распоряжения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV1')
	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 = 'KO_PUNKT_POSTANOV1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KO_PUNKT_POSTANOV1', 'Приказ о приёме: пункты постановления/распоряжения', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KO_PUNKT_POSTANOV1', NAME = 'Приказ о приёме: пункты постановления/распоряжения', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KO_PUNKT_POSTANOV1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CHECKED_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CHECKED_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CHECKED_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CHECKED_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CODE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CODE_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CODE_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CODE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_NAME_1', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_NAME_1', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_COD_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_COD_1', 'Код приказа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_COD_1', NAME = 'Код приказа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_COD_1'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'TITLE', 'Приказ о приёме: пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'INIT_OBJECT_METHOD', 'XA_SPISOK_WITH_PRINT(''ko_punkt_postanov1'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KO_PUNKT_POSTANOV", "KO_PUNKT_POSTANOV_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'SELECT_RECORDS_METHOD', 'SQL.EXEC( "EXEC  dbo.KO_PUNKT_POSTANOV_VIBOR ''1,101''", m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'SELECT_RECORDS_METHOD_EDIT', ''
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE),'''', CODE) + [-] + IIF(ISNULL(NAME), '''', NAME) + [-] + IIF(ISNULL(PRIK_TYP_N), '''', PRIK_TYP_N)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'SERVER_TABLE_NAME', 'ko_punkt_postanov'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'HELP_TOPIC', 'Приказ о приёме: пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV1', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'CONTROL_NAME', 'ATxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'TYPE_FIELD_DICT', 'VARCHAR(2000)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'CONTROL_NAME', 'ATxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'TITLE', 'Код приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1', 'DICTIONARY', 'ORDER_TYPES'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Приказ о переводе: пункты постановления/распоряжения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV2')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV2')
	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 = 'KO_PUNKT_POSTANOV2')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KO_PUNKT_POSTANOV2')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV2'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV2')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KO_PUNKT_POSTANOV2', 'Приказ о переводе: пункты постановления/распоряжения', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KO_PUNKT_POSTANOV2', NAME = 'Приказ о переводе: пункты постановления/распоряжения', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KO_PUNKT_POSTANOV2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CHECKED_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CHECKED_1_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CHECKED_1_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CHECKED_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CODE_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CODE_1_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CODE_1_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CODE_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_NAME_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_NAME_1_1', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_NAME_1_1', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_NAME_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_COD_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_COD_1_1', 'Код приказа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_COD_1_1', NAME = 'Код приказа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_COD_1_1'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'TITLE', 'Приказ о переводе: пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'INIT_OBJECT_METHOD', 'XA_SPISOK_WITH_PRINT(''ko_punkt_postanov2'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KO_PUNKT_POSTANOV", "KO_PUNKT_POSTANOV_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'SELECT_RECORDS_METHOD', 'SQL.EXEC( "EXEC  dbo.KO_PUNKT_POSTANOV_VIBOR ''2,102''", m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'SELECT_RECORDS_METHOD_EDIT', ''
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE),'''', CODE) + [-] + IIF(ISNULL(NAME), '''', NAME) + [-] + IIF(ISNULL(PRIK_TYP_N), '''', PRIK_TYP_N)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'SERVER_TABLE_NAME', 'ko_punkt_postanov'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'HELP_TOPIC', 'Приказ о переводе: пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV2', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED_1_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'CONTROL_NAME', 'ATxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE_1_1', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'TYPE_FIELD_DICT', 'VARCHAR(2000)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'CONTROL_NAME', 'ATxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME_1_1', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'TITLE', 'Код приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD_1_1', 'DICTIONARY', 'ORDER_TYPES'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/****** Объект: Присвоения классных чинов******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_CHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KU_EMPL_CHIN')
	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 = 'KU_EMPL_CHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KU_EMPL_CHIN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_CHIN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_CHIN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KU_EMPL_CHIN', 'Присвоения классных чинов', 40, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KU_EMPL_CHIN', NAME = 'Присвоения классных чинов', ORDERS = '40', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KU_EMPL_CHIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_FACE_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_FACE_LINK', 'Ссылка на сотрудника', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_FACE_LINK', NAME = 'Ссылка на сотрудника', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_FACE_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_DATE', 'Дата', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_DATE', NAME = 'Дата', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='EMPL_CHIN_KOMISS_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'EMPL_CHIN_KOMISS_LINK', 'Ссылка на комиссию', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'EMPL_CHIN_KOMISS_LINK', NAME = 'Ссылка на комиссию', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='EMPL_CHIN_KOMISS_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='EMPL_CHIN_KOMISS_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'EMPL_CHIN_KOMISS_NAME', 'Комиссия', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'EMPL_CHIN_KOMISS_NAME', NAME = 'Комиссия', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='EMPL_CHIN_KOMISS_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_LINK', 'Ссылка на классный чин', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_LINK', NAME = 'Ссылка на классный чин', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_NAME', 'Классный чин', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_NAME', NAME = 'Классный чин', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_PAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_PAY', 'Надбавка', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_PAY', NAME = 'Надбавка', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_PAY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PCHIN_REASON')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PCHIN_REASON', 'Основание', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PCHIN_REASON', NAME = 'Основание', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_CHIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PCHIN_REASON'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'SERVER_TABLE_NAME', 'EMPL_CHIN'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''KU_EMPL_CHIN'')'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''KU_EMPL_CHIN'')'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'EDIT_OBJECT_METHOD', 'kj_brow(''kj_brow_empl_chin'')'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KU_EMPL_CHIN_SAVE'', m.cAlias," SQLNULL(EMPL_LINK), SQLNULL(DATE), SQLNULL(CHIN_LINK), SQLNULL(INCREASE), REASON,ATT_KOM_LINK","KU_EMPL_CHIN")'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KU_EMPL_CHIN", "KU_EMPL_CHIN_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'INIT_OBJECT_METHOD', 'ku_empl_spisok(''KU_EMPL_CHIN'')'
GO
EXEC X_SET_PROP 'KU_EMPL_CHIN', 'TITLE', 'Присвоения классных чинов'
GO
EXEC X_SET_PROP 'PCHIN_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'PCHIN_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PCHIN_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'PCHIN_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'SHORT_CODE_OBJ', 'EMPL_LINK'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'PCHIN_FACE_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'CONTROLSOURCE', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'PCHIN_DATE', 'CONTROL_NAME_EDIT', 'adate1'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'CONTROLSOURCE', 'm.cAlias+".ATT_KOM_LINK"'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'SHORT_CODE_OBJ', 'ATT_KOM_LINK'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ATT_KOM_LINK"'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'TITLE', 'Комиссия'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("ATT_KOMISSION",oForm.ALIAS,"LINK, NAME", "ATT_KOM_LINK, ATT_KOM_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'CONTROLSOURCE', 'm.cAlias+".ATT_KOM_NAME"'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'SHORT_CODE_OBJ', 'ATT_KOM_NAME'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ATT_KOM_NAME"'
GO
EXEC X_SET_PROP 'EMPL_CHIN_KOMISS_NAME', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_ATT_RESH_RUK'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'SHORT_CODE_OBJ', 'CHIN_LINK'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHIN_LINK"'
GO
EXEC X_SET_PROP 'PCHIN_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'TITLE', 'Классный чин'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_CHIN",oForm.ALIAS,"LINK, NAME", "CHIN_LINK, CHIN_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'CONTROLSOURCE', 'm.cAlias+".CHIN_NAME"'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'SHORT_CODE_OBJ', 'CHIN_NAME'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHIN_NAME"'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'PCHIN_NAME', 'REFERENCE_TO_FIELD', 'SOLVE_ATTEST_LINK'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'TITLE', 'Надбавка'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'CONTROLSOURCE', 'm.cAlias+".INCREASE"'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'SHORT_CODE_OBJ', 'INCREASE'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'CONTROLSOURCE_EDIT', 'm.cAlias+".INCREASE"'
GO
EXEC X_SET_PROP 'PCHIN_PAY', 'CONTROL_NAME_EDIT', 'atxt4'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'CONTROLSOURCE', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'SHORT_CODE_OBJ', 'REASON'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'PCHIN_REASON', 'CONTROL_NAME_EDIT', 'atxt5'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Главный бухгалтер', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Смета-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Дело-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Начальник отдела кадров', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_CHIN', 'Свод-КС', 5,0
GO


GO
/****** Объект: Рабочие телефоны******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_PHONE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KU_EMPL_PHONE')
	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 = 'KU_EMPL_PHONE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KU_EMPL_PHONE')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_PHONE'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KU_EMPL_PHONE')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KU_EMPL_PHONE', 'Рабочие телефоны', 34, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KU_EMPL_PHONE', NAME = 'Рабочие телефоны', ORDERS = '34', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KU_EMPL_PHONE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONES_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONES_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONES_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONES_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONES_FACE_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONES_FACE_LINK', 'Ссылка на сотрудника', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONES_FACE_LINK', NAME = 'Ссылка на сотрудника', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONES_FACE_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONE_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONE_CODE', 'Код', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONE_CODE', NAME = 'Код', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONE_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONE_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONE_NUMBER', 'Номер телефона', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONE_NUMBER', NAME = 'Номер телефона', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONE_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONE_ADD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONE_ADD', 'Добавочный', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONE_ADD', NAME = 'Добавочный', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONE_ADD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PHONE_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PHONE_TYPE', 'Вид телефона', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PHONE_TYPE', NAME = 'Вид телефона', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PHONE_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='EMAIL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'EMAIL', 'Электронный адрес', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'EMAIL', NAME = 'Электронный адрес', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PHONE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='EMAIL'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'TITLE', 'Служебные телефоны'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'INIT_OBJECT_METHOD', 'ku_empl_spisok(''KU_EMPL_PHONE'')'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KU_EMPL_PHONE", "KU_EMPL_PHONE_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KU_EMPL_PHONE_SAVE'', m.cAlias," SQLNULL(EMPL_LINK), CODE, NUMBER, ADD, TYPE,EMAIL","KU_EMPL_PHONE")'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'EDIT_OBJECT_METHOD', 'k_brow(''u_brow_rec'')'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''KU_EMPL_PHONE'')'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''KU_EMPL_PHONE'')'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'SERVER_TABLE_NAME', 'EMPL_PHONE'
GO
EXEC X_SET_PROP 'KU_EMPL_PHONE', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'PHONES_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'PHONES_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PHONES_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONES_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'PHONES_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_FACES'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'SHORT_CODE_OBJ', 'EMPL_LINK'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'PHONES_FACE_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PHONE_CODE', 'CONTROL_NAME_EDIT', 'atxt1'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'TITLE', 'Номер телефона'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'CONTROLSOURCE', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'TYPE_FIELD_DICT', 'VARCHAR(15)'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'SHORT_CODE_OBJ', 'NUMBER'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'PHONE_NUMBER', 'CONTROL_NAME_EDIT', 'atxt2'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'TITLE', 'Добавочный'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'CONTROLSOURCE', 'm.cAlias+".ADD"'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'TYPE_FIELD_DICT', 'VARCHAR(5)'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'SHORT_CODE_OBJ', 'ADD'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ADD"'
GO
EXEC X_SET_PROP 'PHONE_ADD', 'CONTROL_NAME_EDIT', 'atxt3'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'TITLE', 'Вид телефона'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'CONTROLSOURCE', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'ROWSOURCE', '''мобильный,внутренний,городской'''
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'SHORT_CODE_OBJ', 'TYPE'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'PHONE_TYPE', 'CONTROL_NAME_EDIT', 'acmb4'
GO
EXEC X_SET_PROP 'EMAIL', 'TITLE', 'Электронный адрес'
GO
EXEC X_SET_PROP 'EMAIL', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'EMAIL', 'CONTROLSOURCE', 'm.cAlias+".EMAIL"'
GO
EXEC X_SET_PROP 'EMAIL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'EMAIL', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'EMAIL', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'EMAIL', 'SHORT_CODE_OBJ', 'EMAIL'
GO
EXEC X_SET_PROP 'EMAIL', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMAIL"'
GO
EXEC X_SET_PROP 'EMAIL', 'CONTROL_NAME_EDIT', 'atxt5'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Главный бухгалтер', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Смета-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Дело-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Начальник отдела кадров', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'KU_EMPL_PHONE', 'Свод-КС', 5,0
GO


GO
-- Отчет "Экзаменационный лист государственного гражданского служащего"
-- Сгенерировано скриптом scriptObjectVar 'KJ_EKZ_LIST'

/*** Сам отчет ***/

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= 'KJ_EKZ_LIST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'KJ_EKZ_LIST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_CLASS'),
	'Экзаменационный лист государственного гражданского служащего',NULL, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'KJ_EKZ_LIST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'KJ_EKZ_LIST') 
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'VISIBLE'),
	VALUE= '1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec KJ_EKZ_LIST @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#KJ_EKZ_LIST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"KJ_EKZ_LIST.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #KJ_EKZ_LIST
	@nSel_Spr1 int	/* Ссылка */
AS
BEGIN

exec KJ_EKZ_LIST @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SYSTEM'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	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 = 'KJ_EKZ_LIST') 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 = 'KJ_EKZ_LIST'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'KJ_EKZ_LIST_GROUP' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',1, 
		(Select link from object_var where code = 'KJ_EKZ_LIST'),
		'KJ_EKZ_LIST_GROUP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'KJ_EKZ_LIST_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Ссылка',2, 
					(Select link from object_var where code = 'KJ_EKZ_LIST_GROUP'),
					'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'14'
						
						
						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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'18'
						
						
						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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_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 = 'KJ_EKZ_LIST_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'KJ_EKZ_LIST_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO



GO
/****** Объект: Перевод работников на другую работу******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'MOVES')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'MOVES')
	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 = 'MOVES')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'MOVES')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'MOVES'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'MOVES')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVES')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVES', 'Перевод работников на другую работу', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='ORDERS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVES', NAME = 'Перевод работников на другую работу', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ORDERS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='MOVES'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NUMBER', 'Номер приказа', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NUMBER', NAME = 'Номер приказа', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_DATE', 'Дата приказа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_DATE', NAME = 'Дата приказа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_TAB_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_TAB_NUM', 'Табельный номер', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_TAB_NUM', NAME = 'Табельный номер', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_TAB_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_FM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_FM', 'Фамилия И.О.', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_FM', NAME = 'Фамилия И.О.', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_FM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_SUBDIV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_SUBDIV', 'Подразделение', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_SUBDIV', NAME = 'Подразделение', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_SUBDIV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_POST', 'Должность', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_POST', NAME = 'Должность', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NEW_SUBDIV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NEW_SUBDIV_LINK', 'Ссылка на новое подразделение', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NEW_SUBDIV_LINK', NAME = 'Ссылка на новое подразделение', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NEW_SUBDIV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NEW_SUBDIV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NEW_SUBDIV', 'Новое подразделение', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NEW_SUBDIV', NAME = 'Новое подразделение', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NEW_SUBDIV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NEW_POST_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NEW_POST_LINK', 'Ссылка на новую должность', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NEW_POST_LINK', NAME = 'Ссылка на новую должность', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NEW_POST_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NEW_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NEW_POST', 'Новая должность', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NEW_POST', NAME = 'Новая должность', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NEW_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_NUM_STAKE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_NUM_STAKE', 'Число ставок', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_NUM_STAKE', NAME = 'Число ставок', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_NUM_STAKE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_STATUS_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_STATUS_1', 'Статус', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_STATUS_1', NAME = 'Статус', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_STATUS_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_DATE_BEGIN', 'Дата начала', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_DATE_BEGIN', NAME = 'Дата начала', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_DATE_END', 'Дата окончания', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_DATE_END', NAME = 'Дата окончания', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_DATE_END'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_REASON')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_REASON', 'Причина перевода', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_REASON', NAME = 'Причина перевода', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_REASON'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_TYPE', 'Вид перевода', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_TYPE', NAME = 'Вид перевода', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_OKLAD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_OKLAD', 'Оклад', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_OKLAD', NAME = 'Оклад', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_OKLAD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_ETS_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_ETS_LINK', 'Ссылка на тарифную сетку', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_ETS_LINK', NAME = 'Ссылка на тарифную сетку', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_ETS_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_ETS_RAZR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_ETS_RAZR', 'Разряд тарифной сетки', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_ETS_RAZR', NAME = 'Разряд тарифной сетки', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_ETS_RAZR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_KONTR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_KONTR_DATE', 'Дата трудового договора', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_KONTR_DATE', NAME = 'Дата трудового договора', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_KONTR_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_KONTR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_KONTR_NUM', 'Номер трудового договора', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_KONTR_NUM', NAME = 'Номер трудового договора', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_KONTR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='MOVE_IO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'MOVE_IO', 'Исполняющий обязанности', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'MOVE_IO', NAME = 'Исполняющий обязанности', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='MOVES'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='MOVE_IO'
GO
EXEC X_SET_PROP 'MOVES', 'TITLE', 'Приказы о переводе работников на другую работу'
GO
EXEC X_SET_PROP 'MOVES', 'INIT_OBJECT_METHOD', 'x_spisok(m.Obj_Code)'
GO
EXEC X_SET_PROP 'MOVES', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "MOVES", "U_DELETE_MOVES", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'MOVES', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_MOVES_SAVE'', m.cAlias, "NUMBER, SQLNULL(DATE), SQLNULL(STAFF_LINK), SQLNULL(NUM_STAKE), SQLNULL(STATUS), SQLNULL(DATE_BEGIN), SQLNULL(DATE_END2), TYPE, REASON, ETS_RAZR, SQLNULL(K_DATE), K_NUM, EMPL_LINK, ORDER_LINK,NULL,NULL,IO","MOVES", .t.)'
GO
EXEC X_SET_PROP 'MOVES', 'PRINT_OBJECT_METHOD', 'KIR_SHOW_DOCUM3("ORDER_MOVE", oForm)'
GO
EXEC X_SET_PROP 'MOVES', 'EDIT_OBJECT_METHOD', 'k_brow(''u_move'')'
GO
EXEC X_SET_PROP 'MOVES', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(m.Obj_Code)'
GO
EXEC X_SET_PROP 'MOVES', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(m.Obj_Code)'
GO
EXEC X_SET_PROP 'MOVES', 'SERVER_TABLE_NAME', 'ITEM_MOVE'
GO
EXEC X_SET_PROP 'MOVES', 'HELP_TOPIC', '25'
GO
EXEC X_SET_PROP 'MOVES', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'MOVES', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''MOVES'''
GO
EXEC X_SET_PROP 'MOVES', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_ITEMS @cDicCode=''MOVES'''
GO
EXEC X_SET_PROP 'MOVE_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'MOVE_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".Checked"'
GO
EXEC X_SET_PROP 'MOVE_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'MOVE_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'MOVE_CHECKED', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'TITLE', 'Номер приказа'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'CONTROLSOURCE', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'TYPE_FIELD_DICT', 'VARCHAR(15)'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'SHORT_CODE_OBJ', 'NUMBER'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'CONTROL_NAME_EDIT', 'atxt1'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'ATTRIBUTES', 'style="Z-INDEX: 135; LEFT: 352px; POSITION: absolute; TOP: 16px""
Width="184px"'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 131; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'MOVE_NUMBER', 'FIELD_DATA', 'number'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'TITLE', 'Дата приказа'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'CONTROLSOURCE', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'CONTROL_NAME_EDIT', 'adate2'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'REFERENCE_TO_FIELD', 'DATE'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 352px; POSITION: absolute; TOP: 48px""
Width="176px"'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 110; LEFT: 16px; POSITION: absolute; TOP: 48px"'
GO
EXEC X_SET_PROP 'MOVE_DATE', 'FIELD_DATA', 'date'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'TITLE', 'Таб.№'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'CONTROLSOURCE', 'm.cAlias+".TAB_NUM"'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'SHORT_CODE_OBJ', 'TAB_NUM'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TAB_NUM"'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'CONTROL_NAME_EDIT', 'atxt3'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'REFERENCE_TO_FIELD', 'TAB_NUM'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'ATTRIBUTES', 'style="Z-INDEX: 108; LEFT: 352px; POSITION: absolute; TOP: 80px""
Width="120px"'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 115; LEFT: 16px; POSITION: absolute; TOP: 80px"'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'DICTIONARY', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'DICTIONARY_COLUMNS_LIST', 'MOVE_TAB_NUM,MOVE_FM,MOVE_SUBDIV,MOVE_POST'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'DICTIONARY_FIELDS_LIST', 'TAB,FIO,SUBDIV_NAME,POST_NAME'
GO
EXEC X_SET_PROP 'MOVE_TAB_NUM', 'FIELD_DATA', 'tab_num'
GO
EXEC X_SET_PROP 'MOVE_FM', 'TITLE', 'Фамилия И.О.'
GO
EXEC X_SET_PROP 'MOVE_FM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_FM', 'CONTROLSOURCE', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'MOVE_FM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_FM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_FM', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'MOVE_FM', 'SHORT_CODE_OBJ', 'FIO'
GO
EXEC X_SET_PROP 'MOVE_FM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'MOVE_FM', 'CONTROL_NAME_EDIT', 'atxt4'
GO
EXEC X_SET_PROP 'MOVE_FM', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_FM', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 352px; POSITION: absolute; TOP: 112px""
Width="424px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'MOVE_FM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 132; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'MOVE_FM', 'FIELD_DATA', 'fio'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'CONTROLSOURCE', 'm.cAlias+".SUBDIV"'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'SHORT_CODE_OBJ', 'SUBDIV'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SUBDIV"'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'CONTROL_NAME_EDIT', 'atxt5'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'REFERENCE_TO_FIELD', 'SUBDIV'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'ATTRIBUTES', 'style="Z-INDEX: 105; LEFT: 352px; POSITION: absolute; TOP: 144px""
Width="424px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 133; LEFT: 16px; POSITION: absolute; TOP: 144px"'
GO
EXEC X_SET_PROP 'MOVE_SUBDIV', 'FIELD_DATA', 'subdiv'
GO
EXEC X_SET_PROP 'MOVE_POST', 'TITLE', 'Должность'
GO
EXEC X_SET_PROP 'MOVE_POST', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_POST', 'CONTROLSOURCE', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'MOVE_POST', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_POST', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_POST', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'MOVE_POST', 'SHORT_CODE_OBJ', 'POST'
GO
EXEC X_SET_PROP 'MOVE_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'MOVE_POST', 'CONTROL_NAME_EDIT', 'atxt6'
GO
EXEC X_SET_PROP 'MOVE_POST', 'REFERENCE_TO_FIELD', 'POST'
GO
EXEC X_SET_PROP 'MOVE_POST', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_POST', 'ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 352px; POSITION: absolute; TOP: 176px""
Width="424px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'MOVE_POST', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 134; LEFT: 16px; POSITION: absolute; TOP: 176px"'
GO
EXEC X_SET_PROP 'MOVE_POST', 'FIELD_DATA', 'post'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'CONTROLSOURCE', 'm.cAlias+".NEW_SUBDIV_LINK"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_SUBDIVISION'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'SHORT_CODE_OBJ', 'NEW_SUBDIV_LINK'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NEW_SUBDIV_LINK"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV_LINK', 'FIELD_DATA', 'new_subdiv_link'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'TITLE', 'Новое подразделение'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'CONTROLSOURCE', 'm.cAlias+".NEW_SUBDIV"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'SHORT_CODE_OBJ', 'NEW_SUBDIV'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NEW_SUBDIV"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'CONTROL_NAME_EDIT', 'apageframe.page1.asel9'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'REFERENCE_TO_FIELD', 'NEW_SUBDIV'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 352px; POSITION: absolute; TOP: 208px""
Width="424px"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 118; LEFT: 16px; POSITION: absolute; TOP: 208px"'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'DICTIONARY', 'DICTIONARY_SUBDIVISION_ALL'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'DICTIONARY_COLUMNS_LIST', 'MOVE_NEW_SUBDIV_LINK,OVE_NEW_SUBDIV'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'DICTIONARY_FIELDS_LIST', 'link_up,name'
GO
EXEC X_SET_PROP 'MOVE_NEW_SUBDIV', 'FIELD_DATA', 'new_subdiv'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'CONTROLSOURCE', 'm.cAlias+".STAFF_LINK"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'SHORT_CODE_OBJ', 'STAFF_LINK'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".STAFF_LINK"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST_LINK', 'FIELD_DATA', 'staff_link'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'TITLE', 'Новая должность'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("DICTIONARY_STAFF_ALL",oForm.icnt.ALIAS,"LINK_UP, POST_NAME, OKLAD", "STAFF_LINK, NEW_POST, OKLAD", "", "", "subdiv_link=?"+oForm.icnt.alias+".new_subdiv_link and link_up in (select link from dbo.sa_FreeStaffHead(?"+oForm.icnt.alias+".date_begin)) and ?"+oForm.icnt.alias+".date_begin between date_begin and date_end", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'CONTROLSOURCE', 'm.cAlias+".NEW_POST"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'SHORT_CODE_OBJ', 'NEW_POST'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NEW_POST"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'CONTROL_NAME_EDIT', 'apageframe.page1.asel10'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'REFERENCE_TO_FIELD', 'NEW_POST'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 352px; POSITION: absolute; TOP: 240px""
Width="424px"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 119; LEFT: 16px; POSITION: absolute; TOP: 240px"'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'DICTIONARY', 'DICTIONARY_STAFF_ALL'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'DICTIONARY_COLUMNS_LIST', 'MOVE_NEW_POST_LINK,MOVE_NEW_POST,MOVE_OKLAD'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'DICTIONARY_FIELDS_LIST', 'link_up,post_name,oklad'
GO
EXEC X_SET_PROP 'MOVE_NEW_POST', 'FIELD_DATA', 'new_post'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'TITLE', 'Число ставок'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'CONTROLSOURCE', 'm.cAlias+".NUM_STAKE"'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'TYPE_FIELD_DICT', 'NUMERIC(3,2)'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'SHORT_CODE_OBJ', 'NUM_STAKE'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUM_STAKE"'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt11'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'REFERENCE_TO_FIELD', 'NUM_STAKE'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'ATTRIBUTES', 'style="Z-INDEX: 109; LEFT: 352px; POSITION: absolute; TOP: 272px""
Width="88px"'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 16px; POSITION: absolute; TOP: 272px"'
GO
EXEC X_SET_PROP 'MOVE_NUM_STAKE', 'FIELD_DATA', 'num_stake'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'TITLE', 'Статус'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'CONTROLSOURCE', 'm.cAlias+".STATUS"'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'ROWSOURCE', '''Основной,Совместитель,Внешний совместитель'''
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'SHORT_CODE_OBJ', 'STATUS'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".STATUS"'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'CONTROL_NAME_EDIT', 'apageframe.page1.acmb12'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'REFERENCE_TO_FIELD', 'VALUE'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'ATTRIBUTES', 'style="Z-INDEX: 123; LEFT: 352px; POSITION: absolute; TOP: 304px""
Width="160px"'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 122; LEFT: 16px; POSITION: absolute; TOP: 304px"'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'DICTIONARY', 'Основной#1@Совместитель#2@Внешний совместитель#3'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'FIELD_DATA', 'status'
GO
EXEC X_SET_PROP 'FACE_STATUS_1', 'FIELD_KEY', 'status'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'TITLE', 'Перевести с'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'SHORT_CODE_OBJ', 'DATE_BEGIN'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate13'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'REFERENCE_TO_FIELD', 'DATE_BEGIN'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'ATTRIBUTES', 'style="Z-INDEX: 114; LEFT: 352px; POSITION: absolute; TOP: 336px""
Width="176px"'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 124; LEFT: 16px; POSITION: absolute; TOP: 336px"'
GO
EXEC X_SET_PROP 'MOVE_DATE_BEGIN', 'FIELD_DATA', 'date_begin'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'TITLE', 'по'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'CONTROLSOURCE', 'm.cAlias+".DATE_END2"'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'SHORT_CODE_OBJ', 'DATE_END2'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_END2"'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate14'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'REFERENCE_TO_FIELD', 'DATE_END2'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'ATTRIBUTES', 'style="Z-INDEX: 112; LEFT: 352px; POSITION: absolute; TOP: 368px""
Width="176px"'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 125; LEFT: 16px; POSITION: absolute; TOP: 368px"'
GO
EXEC X_SET_PROP 'MOVE_DATE_END', 'FIELD_DATA', 'date_end2'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'TITLE', 'Причина перевода'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'CONTROLSOURCE', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'SHORT_CODE_OBJ', 'REASON'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt15'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'REFERENCE_TO_FIELD', 'REASON'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 352px; POSITION: absolute; TOP: 400px""
Width="424px"'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 126; LEFT: 16px; POSITION: absolute; TOP: 400px"'
GO
EXEC X_SET_PROP 'MOVE_REASON', 'FIELD_DATA', 'reason'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'TITLE', 'Вид перевода'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'CONTROLSOURCE', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'SHORT_CODE_OBJ', 'TYPE'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'CONTROL_NAME_EDIT', 'apageframe.page1.aoption16'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'REFERENCE_TO_FIELD', 'TYPE'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'ATTRIBUTES', 'style="Z-INDEX: 137; LEFT: 352px; POSITION: absolute; TOP: 432px""
Width="160px"'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 136; LEFT: 16px; POSITION: absolute; TOP: 432px"'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'DICTIONARY', 'временно#1@постоянно#2'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'FIELD_DATA', 'type'
GO
EXEC X_SET_PROP 'MOVE_TYPE', 'FIELD_KEY', 'type'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'TITLE', 'Оклад'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'CONTROLSOURCE', 'm.cAlias+".OKLAD"'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'SHORT_CODE_OBJ', 'OKLAD'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".OKLAD"'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt17'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'REFERENCE_TO_FIELD', 'OKLAD'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'ATTRIBUTES', 'style="Z-INDEX: 103; LEFT: 352px; POSITION: absolute; TOP: 464px""
Width="144px"'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 127; LEFT: 16px; POSITION: absolute; TOP: 464px"'
GO
EXEC X_SET_PROP 'MOVE_OKLAD', 'FIELD_DATA', 'oklad'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'SHORT_CODE_OBJ', 'ETS_LINK'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ETS_LINK "'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'MOVE_ETS_LINK', 'FIELD_DATA', 'ets_link'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'TITLE', 'Разряд'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'CONTROLSOURCE', 'm.cAlias+".ETS_RAZR"'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'SHORT_CODE_OBJ', 'ETS_RAZR'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ETS_RAZR"'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt18'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'ATTRIBUTES', 'style="Z-INDEX: 128; LEFT: 352px; POSITION: absolute; TOP: 496px""
Width="104px"'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 120; LEFT: 16px; POSITION: absolute; TOP: 496px"'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'DICTIONARY', 'SU_ETS'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'DICTIONARY_COLUMNS_LIST', 'MOVE_ETS_LINK,OVE_ETS_RAZR'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'DICTIONARY_FIELDS_LIST', 'link,razr'
GO
EXEC X_SET_PROP 'MOVE_ETS_RAZR', 'FIELD_DATA', 'ets_razr'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'TITLE', 'Изменение к трудовому договору (контракту) от'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'CONTROLSOURCE', 'm.cAlias+".K_DATE"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'SHORT_CODE_OBJ', 'KONTR_DATE'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".K_DATE"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate19'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'REFERENCE_TO_FIELD', 'KONTR_DATE'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'ATTRIBUTES', 'style="Z-INDEX: 113; LEFT: 352px; POSITION: absolute; TOP: 528px""
Width="176px"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 129; LEFT: 16px; POSITION: absolute; TOP: 528px""
Height="11px"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_DATE', 'FIELD_DATA', 'k_date'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'TITLE', 'Номер трудового договора (контракта)'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'CONTROLSOURCE', 'm.cAlias+".K_NUM"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(15)'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'SHORT_CODE_OBJ', 'KONTR_NUM'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".K_NUM"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt20'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'REFERENCE_TO_FIELD', 'KONTR_NUM'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 352px; POSITION: absolute; TOP: 560px""
Width="144px"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 130; LEFT: 16px; POSITION: absolute; TOP: 560px"'
GO
EXEC X_SET_PROP 'MOVE_KONTR_NUM', 'FIELD_DATA', 'k_num'
GO
EXEC X_SET_PROP 'MOVE_IO', 'TITLE', 'Исполняющий обязанности'
GO
EXEC X_SET_PROP 'MOVE_IO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'MOVE_IO', 'CONTROLSOURCE', 'm.cAlias+".IO"'
GO
EXEC X_SET_PROP 'MOVE_IO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'MOVE_IO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'MOVE_IO', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'MOVE_IO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IO"'
GO
EXEC X_SET_PROP 'MOVE_IO', 'CONTROL_NAME_EDIT', 'apageframe.page1.acheckboxIO'
GO
EXEC X_SET_PROP 'MOVE_IO', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'MOVE_IO', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'MOVE_IO', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'MOVES', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'MOVES', 'Зарплата-КС', 5,0
GO


GO
/****** Объект: Прием работников на работу******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'NEW_FACE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'NEW_FACE')
	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 = 'NEW_FACE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'NEW_FACE')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'NEW_FACE'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'NEW_FACE')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NEW_FACE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NEW_FACE', 'Прием работников на работу', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ORDERS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NEW_FACE', NAME = 'Прием работников на работу', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ORDERS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='NEW_FACE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_NUMBER', 'Номер приказа', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_NUMBER', NAME = 'Номер приказа', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_DATE', 'Дата приказа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_DATE', NAME = 'Дата приказа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_TAB_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_TAB_NUM', 'Табельный номер', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_TAB_NUM', NAME = 'Табельный номер', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_TAB_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_FM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_FM', 'Фамилия И.О.', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_FM', NAME = 'Фамилия И.О.', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_FM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_SUBDIV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_SUBDIV_LINK', 'Ссылка на подразделение', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_SUBDIV_LINK', NAME = 'Ссылка на подразделение', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_SUBDIV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_SUBDIV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_SUBDIV', 'Подразделение', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_SUBDIV', NAME = 'Подразделение', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_SUBDIV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_POST_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_POST_LINK', 'Ссылка на должность', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_POST_LINK', NAME = 'Ссылка на должность', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_POST_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_POST', 'Должность', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_POST', NAME = 'Должность', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_DATE_BEGIN', 'Дата начала', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_DATE_BEGIN', NAME = 'Дата начала', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_DATE_END', 'Дата окончания', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_DATE_END', NAME = 'Дата окончания', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_DATE_END'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_USL_PR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_USL_PR', 'Условия приема', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_USL_PR', NAME = 'Условия приема', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_USL_PR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_OKLAD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_OKLAD', 'Оклад', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_OKLAD', NAME = 'Оклад', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_OKLAD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_ETS_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_ETS_LINK', 'Ссылка на тарифную сетку', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_ETS_LINK', NAME = 'Ссылка на тарифную сетку', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_ETS_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_ETS_RAZR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_ETS_RAZR', 'Разряд тарифной сетки', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_ETS_RAZR', NAME = 'Разряд тарифной сетки', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_ETS_RAZR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_ISP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_ISP', 'Испытательный срок', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_ISP', NAME = 'Испытательный срок', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_ISP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_KONTR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_KONTR_DATE', 'Дата трудового договора', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_KONTR_DATE', NAME = 'Дата трудового договора', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_KONTR_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_KONTR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_KONTR_NUM', 'Номер трудового договора', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_KONTR_NUM', NAME = 'Номер трудового договора', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_KONTR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_FACE_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_FACE_LINK', 'Ссылка на сотрудника', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_FACE_LINK', NAME = 'Ссылка на сотрудника', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_FACE_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_ORDER_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_ORDER_TYPE', 'Тип приказа', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_ORDER_TYPE', NAME = 'Тип приказа', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_ORDER_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_NUM_STAKE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_NUM_STAKE', 'Число ставок', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_NUM_STAKE', NAME = 'Число ставок', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_NUM_STAKE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_STATUS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_STATUS', 'Статус', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_STATUS', NAME = 'Статус', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_STATUS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_TEMP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_TEMP', 'ВРЕМЕННО', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_TEMP', NAME = 'ВРЕМЕННО', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_TEMP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_TEMP_EMPL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_TEMP_EMPL_LINK', 'ССЫЛКА НА ВМЕСТО КОГО', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_TEMP_EMPL_LINK', NAME = 'ССЫЛКА НА ВМЕСТО КОГО', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_TEMP_EMPL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_TEMP_EMPL_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_TEMP_EMPL_FIO', 'ВМЕСТО КОГО', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_TEMP_EMPL_FIO', NAME = 'ВМЕСТО КОГО', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_TEMP_EMPL_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NF_IO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NF_IO', 'Исполняющий обязанности', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NF_IO', NAME = 'Исполняющий обязанности', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NEW_FACE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NF_IO'
GO
EXEC X_SET_PROP 'NEW_FACE', 'TITLE', 'Приказы о приеме работников на работу'
GO
EXEC X_SET_PROP 'NEW_FACE', 'INIT_OBJECT_METHOD', 'x_spisok(m.Obj_Code)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "NEW_FACE", "U_DELETE_NEW_FACE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_NEW_FACE_SAVE'', m.cAlias,"NUMBER, DATE,SQLNULL(STAFF_LINK), SQLNULL(DATE_BEGIN), SQLNULL(DATE_END2), USL_PR, ETS_RAZR, ISP, SQLNULL(KONTR_DATE), SQLNULL(KONTR_NUM), SQLNULL(NUM_STAKE), SQLNULL(STATUS), SQLNULL(EMPL_LINK), ORDER_LINK,NULL,NULL,SQLNULL(TEMP_LINK),IO", "NEW_FACE", .t.)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'PRINT_OBJECT_METHOD', 'KIR_SHOW_DOCUM3("NEW_FACE", oForm)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'EDIT_OBJECT_METHOD', 'k_brow(''u_new_face'')'
GO
EXEC X_SET_PROP 'NEW_FACE', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(m.Obj_Code)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(m.Obj_Code)'
GO
EXEC X_SET_PROP 'NEW_FACE', 'SERVER_TABLE_NAME', 'ITEM_MOVE'
GO
EXEC X_SET_PROP 'NEW_FACE', 'HELP_TOPIC', '15'
GO
EXEC X_SET_PROP 'NEW_FACE', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'NEW_FACE', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''NEW_FACE'''
GO
EXEC X_SET_PROP 'NEW_FACE', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_ITEMS @cDicCode=''NEW_FACE'''
GO
EXEC X_SET_PROP 'NF_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'NF_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".Checked"'
GO
EXEC X_SET_PROP 'NF_CHECKED', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'NF_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'NF_CHECKED', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'TITLE', 'Номер приказа'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'CONTROLSOURCE', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'TYPE_FIELD_DICT', 'VARCHAR(15)'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'SHORT_CODE_OBJ', 'NUMBER'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'CONTROL_NAME_EDIT', 'atxt1'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 16px""
Width="232px"'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'NF_NUMBER', 'FIELD_DATA', 'number'
GO
EXEC X_SET_PROP 'NF_DATE', 'TITLE', 'Дата приказа'
GO
EXEC X_SET_PROP 'NF_DATE', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'NF_DATE', 'CONTROLSOURCE', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'NF_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_DATE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'NF_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'NF_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'NF_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE"'
GO
EXEC X_SET_PROP 'NF_DATE', 'CONTROL_NAME_EDIT', 'adate2'
GO
EXEC X_SET_PROP 'NF_DATE', 'REFERENCE_TO_FIELD', 'DATE'
GO
EXEC X_SET_PROP 'NF_DATE', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'NF_DATE', 'ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 288px; POSITION: absolute; TOP: 48px""
Width="176px"'
GO
EXEC X_SET_PROP 'NF_DATE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 110; LEFT: 16px; POSITION: absolute; TOP: 48px"'
GO
EXEC X_SET_PROP 'NF_DATE', 'FIELD_DATA', 'date'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'TITLE', 'Таб.№'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'CONTROLSOURCE', 'm.cAlias+".TAB_NUM"'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'SHORT_CODE_OBJ', 'TAB_NUM'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TAB_NUM"'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'CONTROL_NAME_EDIT', 'atxt3'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'REFERENCE_TO_FIELD', 'TAB_NUM'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'ATTRIBUTES', 'style="Z-INDEX: 108; LEFT: 288px; POSITION: absolute; TOP: 80px""
Width="120px"'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 115; LEFT: 16px; POSITION: absolute; TOP: 80px"'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'DICTIONARY', 'KU_EMPL_PLACING'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'DICTIONARY_COLUMNS_LIST', 'NF_TAB_NUM,NF_FM,NF_SUBDIV,NF_SUBDIV_LINK,NF_POST,NF_POST_LINK,NF_FACE_LINK'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'DICTIONARY_FIELDS_LIST', 'TAB,FIO,SUBDIV_NAME,subdiv_link,POST_NAME,post_link,LINK'
GO
EXEC X_SET_PROP 'NF_TAB_NUM', 'FIELD_DATA', 'tab_num'
GO
EXEC X_SET_PROP 'NF_FM', 'TITLE', 'Фамилия И.О.'
GO
EXEC X_SET_PROP 'NF_FM', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("KU_PERSON", oForm.icnt.alias, "LINK, FIO", "PERS_LINK, FIO", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'NF_FM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_FM', 'CONTROLSOURCE', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'NF_FM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_FM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_FM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_FM', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_FM', 'SHORT_CODE_OBJ', 'FIO'
GO
EXEC X_SET_PROP 'NF_FM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'NF_FM', 'CONTROL_NAME_EDIT', 'asel4'
GO
EXEC X_SET_PROP 'NF_FM', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_FM', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_FM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'NF_FM', 'DICTIONARY', 'KU_PERSON'
GO
EXEC X_SET_PROP 'NF_FM', 'DICTIONARY_COLUMNS_LIST', 'NF_FACE_LINK,NF_FM'
GO
EXEC X_SET_PROP 'NF_FM', 'DICTIONARY_FIELDS_LIST', 'link,fio'
GO
EXEC X_SET_PROP 'NF_FM', 'FIELD_DATA', 'fio'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'CONTROLSOURCE', 'm.cAlias+".SUBDIV_LINK"'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SUBDIV_LINK"'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'NF_SUBDIV_LINK', 'FIELD_DATA', 'SUBDIV_LINK'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'TITLE', 'Подразделение'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'CONTROLSOURCE', 'm.cAlias+".NEW_SUBDIV"'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'SHORT_CODE_OBJ', 'NEW_SUBDIV'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NEW_SUBDIV"'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'CONTROL_NAME_EDIT', 'apageframe.page1.asel5'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'ATTRIBUTES', 'style="Z-INDEX: 119; LEFT: 288px; POSITION: absolute; TOP: 144px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 120; LEFT: 16px; POSITION: absolute; TOP: 144px"'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'DICTIONARY', 'DICTIONARY_SUBDIVISION_ALL'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'DICTIONARY_COLUMNS_LIST', 'NF_SUBDIV_LINK,NF_SUBDIV'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'DICTIONARY_FIELDS_LIST', 'link_up,name'
GO
EXEC X_SET_PROP 'NF_SUBDIV', 'FIELD_DATA', 'new_subdiv'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'CONTROLSOURCE', 'm.cAlias+".STAFF_LINK"'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".STAFF_LINK"'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'NF_POST_LINK', 'FIELD_DATA', 'STAFF_LINK'
GO
EXEC X_SET_PROP 'NF_POST', 'TITLE', 'Должность'
GO
EXEC X_SET_PROP 'NF_POST', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("DICTIONARY_STAFF_ALL",oForm.icnt.ALIAS,"LINK_UP, POST_NAME, OKLAD", "STAFF_LINK, NEW_POST, OKLAD", "", "", "subdiv_link=?"+oForm.icnt.alias+".new_subdiv_link and link_up in (select link from dbo.sa_FreeStaffHead(?"+oForm.icnt.alias+".date_begin)) and ?"+oForm.icnt.alias+".date_begin between date_begin and date_end", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'NF_POST', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_POST', 'CONTROLSOURCE', 'm.cAlias+".NEW_POST"'
GO
EXEC X_SET_PROP 'NF_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_POST', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_POST', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_POST', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'NF_POST', 'SHORT_CODE_OBJ', 'NEW_POST'
GO
EXEC X_SET_PROP 'NF_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NEW_POST"'
GO
EXEC X_SET_PROP 'NF_POST', 'CONTROL_NAME_EDIT', 'apageframe.page1.asel6'
GO
EXEC X_SET_PROP 'NF_POST', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_POST', 'ATTRIBUTES', 'style="Z-INDEX: 118; LEFT: 288px; POSITION: absolute; TOP: 176px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_POST', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 16px; POSITION: absolute; TOP: 176px"'
GO
EXEC X_SET_PROP 'NF_POST', 'DICTIONARY', 'DICTIONARY_STAFF_ALL'
GO
EXEC X_SET_PROP 'NF_POST', 'DICTIONARY_COLUMNS_LIST', 'NF_POST_LINK,NF_POST,NF_OKLAD'
GO
EXEC X_SET_PROP 'NF_POST', 'DICTIONARY_FIELDS_LIST', 'link_up,post_name,oklad'
GO
EXEC X_SET_PROP 'NF_POST', 'FIELD_DATA', 'new_post'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'TITLE', 'Принять на работу с'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'SHORT_CODE_OBJ', 'DATE_BEGIN'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate7'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'REFERENCE_TO_FIELD', 'DATE_BEGIN'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'ATTRIBUTES', 'style="Z-INDEX: 114; LEFT: 288px; POSITION: absolute; TOP: 272px""
Width="176px"'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 126; LEFT: 16px; POSITION: absolute; TOP: 272px"'
GO
EXEC X_SET_PROP 'NF_DATE_BEGIN', 'FIELD_DATA', 'date_begin'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'TITLE', 'по'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'CONTROLSOURCE', 'm.cAlias+".DATE_END2"'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'SHORT_CODE_OBJ', 'DATE_END2'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_END2"'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate8'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'REFERENCE_TO_FIELD', 'DATE_END2'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'ATTRIBUTES', 'style="Z-INDEX: 112; LEFT: 288px; POSITION: absolute; TOP: 304px""
Width="176px"'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 127; LEFT: 16px; POSITION: absolute; TOP: 304px"'
GO
EXEC X_SET_PROP 'NF_DATE_END', 'FIELD_DATA', 'date_end2'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'TITLE', 'Условия приема'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'CONTROLSOURCE', 'm.cAlias+".USL_PR"'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'SHORT_CODE_OBJ', 'USL_PR'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'CONTROLSOURCE_EDIT', 'm.cAlias+".USL_PR"'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt9'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'REFERENCE_TO_FIELD', 'USL_PR'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 288px; POSITION: absolute; TOP: 336px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 128; LEFT: 16px; POSITION: absolute; TOP: 336px"'
GO
EXEC X_SET_PROP 'NF_USL_PR', 'FIELD_DATA', 'usl_pr'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'TITLE', 'Оклад'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'CONTROLSOURCE', 'm.cAlias+".OKLAD"'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'SHORT_CODE_OBJ', 'OKLAD'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".OKLAD"'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt10'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'REFERENCE_TO_FIELD', 'OKLAD'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'ATTRIBUTES', 'style="Z-INDEX: 104; LEFT: 288px; POSITION: absolute; TOP: 368px""
Width="144px"'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 129; LEFT: 16px; POSITION: absolute; TOP: 368px"'
GO
EXEC X_SET_PROP 'NF_OKLAD', 'FIELD_DATA', 'oklad'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'SHORT_CODE_OBJ', 'ETS_LINK'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ETS_LINK "'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'NF_ETS_LINK', 'FIELD_DATA', 'ets_link'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'TITLE', 'Разряд'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'CONTROLSOURCE', 'm.cAlias+".ETS_RAZR"'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'SHORT_CODE_OBJ', 'ETS_RAZR'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ETS_RAZR"'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt11'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'ATTRIBUTES', 'style="Z-INDEX: 130; LEFT: 288px; POSITION: absolute; TOP: 400px""
Width="104px"'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 122; LEFT: 16px; POSITION: absolute; TOP: 400px"'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'DICTIONARY', 'SU_ETS'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'DICTIONARY_COLUMNS_LIST', 'NF_ETS_LINK,NF_ETS_RAZR'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'DICTIONARY_FIELDS_LIST', 'link,razr'
GO
EXEC X_SET_PROP 'NF_ETS_RAZR', 'FIELD_DATA', 'ets_razr'
GO
EXEC X_SET_PROP 'NF_ISP', 'TITLE', 'Испытательный срок'
GO
EXEC X_SET_PROP 'NF_ISP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_ISP', 'CONTROLSOURCE', 'm.cAlias+".ISP"'
GO
EXEC X_SET_PROP 'NF_ISP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_ISP', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_ISP', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_ISP', 'SHORT_CODE_OBJ', 'ISP'
GO
EXEC X_SET_PROP 'NF_ISP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ISP"'
GO
EXEC X_SET_PROP 'NF_ISP', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt12'
GO
EXEC X_SET_PROP 'NF_ISP', 'REFERENCE_TO_FIELD', 'ISP'
GO
EXEC X_SET_PROP 'NF_ISP', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_ISP', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 288px; POSITION: absolute; TOP: 432px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_ISP', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 131; LEFT: 16px; POSITION: absolute; TOP: 432px"'
GO
EXEC X_SET_PROP 'NF_ISP', 'FIELD_DATA', 'isp'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'TITLE', 'Трудовой договор (контракт) от'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'CONTROLSOURCE', 'm.cAlias+".KONTR_DATE"'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'SHORT_CODE_OBJ', 'KONTR_DATE'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KONTR_DATE"'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'CONTROL_NAME_EDIT', 'apageframe.page1.adate13'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'REFERENCE_TO_FIELD', 'KONTR_DATE'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'ATTRIBUTES', 'style="Z-INDEX: 113; LEFT: 288px; POSITION: absolute; TOP: 464px""
Width="176px"'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 132; LEFT: 16px; POSITION: absolute; TOP: 464px""
Height="11px"'
GO
EXEC X_SET_PROP 'NF_KONTR_DATE', 'FIELD_DATA', 'kontr_date'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'TITLE', 'Номер трудового договора (контракта)'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'CONTROLSOURCE', 'm.cAlias+".KONTR_NUM"'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(15)'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'SHORT_CODE_OBJ', 'KONTR_NUM'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KONTR_NUM"'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt14'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'REFERENCE_TO_FIELD', 'KONTR_NUM'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'ATTRIBUTES', 'style="Z-INDEX: 105; LEFT: 288px; POSITION: absolute; TOP: 496px""
Width="144px"'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 133; LEFT: 16px; POSITION: absolute; TOP: 496px"'
GO
EXEC X_SET_PROP 'NF_KONTR_NUM', 'FIELD_DATA', 'kontr_num'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'CONTROLSOURCE', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'SHORT_CODE_OBJ', 'FACE_LINK'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMPL_LINK"'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'REFERENCE_TO_FIELD', 'FACE_LINK'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'NF_FACE_LINK', 'FIELD_DATA', 'EMPL_LINK'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'TITLE', 'Тип приказа'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'CONTROLSOURCE', 'm.cAlias+".ORDER_TYPE"'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'SHORT_CODE_OBJ', 'ORDER_TYPE'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".ORDER_TYPE"'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'REFERENCE_TO_FIELD', 'ORDER_TYPE'
GO
EXEC X_SET_PROP 'NF_ORDER_TYPE', 'FIELD_DATA', 'order_type'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'TITLE', 'Число ставок'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'CONTROLSOURCE', 'm.cAlias+".NUM_STAKE"'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'TYPE_FIELD_DICT', 'NUMERIC(3,2)'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'SHORT_CODE_OBJ', 'NUM_STAKE'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUM_STAKE"'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt17'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'REFERENCE_TO_FIELD', 'NUM_STAKE'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'ATTRIBUTES', 'style="Z-INDEX: 109; LEFT: 288px; POSITION: absolute; TOP: 208px""
Width="88px"'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 123; LEFT: 16px; POSITION: absolute; TOP: 208px"'
GO
EXEC X_SET_PROP 'NF_NUM_STAKE', 'FIELD_DATA', 'num_stake'
GO
EXEC X_SET_PROP 'NF_STATUS', 'TITLE', 'Статус'
GO
EXEC X_SET_PROP 'NF_STATUS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_STATUS', 'CONTROLSOURCE', 'm.cAlias+".STATUS"'
GO
EXEC X_SET_PROP 'NF_STATUS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_STATUS', 'ROWSOURCE', '''Основной,Совместитель,Внешний совместитель'''
GO
EXEC X_SET_PROP 'NF_STATUS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_STATUS', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_STATUS', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_STATUS', 'SHORT_CODE_OBJ', 'STATUS'
GO
EXEC X_SET_PROP 'NF_STATUS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".STATUS"'
GO
EXEC X_SET_PROP 'NF_STATUS', 'CONTROL_NAME_EDIT', 'apageframe.page1.acmb18'
GO
EXEC X_SET_PROP 'NF_STATUS', 'REFERENCE_TO_FIELD', 'NUM_STAKE'
GO
EXEC X_SET_PROP 'NF_STATUS', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'NF_STATUS', 'ATTRIBUTES', 'style="Z-INDEX: 125; LEFT: 288px; POSITION: absolute; TOP: 240px""
Width="160px"'
GO
EXEC X_SET_PROP 'NF_STATUS', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 124; LEFT: 16px; POSITION: absolute; TOP: 240px"'
GO
EXEC X_SET_PROP 'NF_STATUS', 'DICTIONARY', 'Основной#1@Совместитель#2@Внешний совместитель#3'
GO
EXEC X_SET_PROP 'NF_STATUS', 'FIELD_DATA', 'status'
GO
EXEC X_SET_PROP 'NF_STATUS', 'FIELD_KEY', 'status'
GO
EXEC X_SET_PROP 'NF_TEMP', 'TITLE', 'Временно'
GO
EXEC X_SET_PROP 'NF_TEMP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_TEMP', 'CONTROLSOURCE', 'm.cAlias+".TEMP"'
GO
EXEC X_SET_PROP 'NF_TEMP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_TEMP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_TEMP', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_TEMP', 'SHORT_CODE_OBJ', 'FIO'
GO
EXEC X_SET_PROP 'NF_TEMP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TEMP"'
GO
EXEC X_SET_PROP 'NF_TEMP', 'CONTROL_NAME_EDIT', 'apageframe.page1.acheckbox15'
GO
EXEC X_SET_PROP 'NF_TEMP', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_TEMP', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_TEMP', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'CONTROLSOURCE', 'm.cAlias+".TEMP_LINK"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_POST'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TEMP_LINK"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_LINK', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'TITLE', 'Вместо'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'CONTROLSOURCE', 'm.cAlias+".TEMP_FIO"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'SHORT_CODE_OBJ', 'FIO'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TEMP_FIO"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'CONTROL_NAME_EDIT', 'apageframe.page1.atxt16'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_TEMP_EMPL_FIO', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'NF_IO', 'TITLE', 'Исполняющий обязанности'
GO
EXEC X_SET_PROP 'NF_IO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'NF_IO', 'CONTROLSOURCE', 'm.cAlias+".IO"'
GO
EXEC X_SET_PROP 'NF_IO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NF_IO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'NF_IO', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'NF_IO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IO"'
GO
EXEC X_SET_PROP 'NF_IO', 'CONTROL_NAME_EDIT', 'apageframe.page1.acheckboxIO'
GO
EXEC X_SET_PROP 'NF_IO', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'NF_IO', 'ATTRIBUTES', 'style="Z-INDEX: 117; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'NF_IO', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'NEW_FACE', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'NEW_FACE', 'Зарплата-КС', 5,0
GO


GO
/****** Объект: Пункты постановления/распоряжения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ko_punkt_postanov')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ko_punkt_postanov')
	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 = 'ko_punkt_postanov')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ko_punkt_postanov')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ko_punkt_postanov'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ko_punkt_postanov')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KO_PUNKT_POSTANOV', 'Пункты постановления/распоряжения', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KO_PUNKT_POSTANOV', NAME = 'Пункты постановления/распоряжения', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KO_PUNKT_POSTANOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_TYP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_TYP', 'Тип приказа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_TYP', NAME = 'Тип приказа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_TYP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_NAME', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_NAME', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PUNKT_POSTANOV_PRIK_COD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PUNKT_POSTANOV_PRIK_COD', 'Код приказа', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PUNKT_POSTANOV_PRIK_COD', NAME = 'Код приказа', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KO_PUNKT_POSTANOV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PUNKT_POSTANOV_PRIK_COD'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'TITLE', 'Пункты постановления / распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'INIT_OBJECT_METHOD', 'XA_SPISOK_WITH_PRINT(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KO_PUNKT_POSTANOV", "KO_PUNKT_POSTANOV_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KO_PUNKT_POSTANOV_SAVE'', m.cAlias," CODE, NAME,PRIK_TYP_N, PRIK_TYP","ko_punkt_postanov")'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'EDIT_OBJECT_METHOD', 'K_BROW(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''ko_punkt_postanov'')'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE),'''', CODE) + [-] + IIF(ISNULL(NAME), '''', NAME) + [-] + IIF(ISNULL(PRIK_TYP_N), '''', PRIK_TYP_N)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'SERVER_TABLE_NAME', 'ko_punkt_postanov'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'HELP_TOPIC', 'Пункты постановления/распоряжения'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'KO_PUNKT_POSTANOV', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CHECKED', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROL_NAME', 'ATxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_CODE', 'CONTROL_NAME_EDIT', 'Atxt1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'TITLE', 'Тип приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("ORDER_TYPES", oForm.alias, "CODE, NAME", "PRIK_TYP, PRIK_TYP_N", "", "", "CODE IN (1,2,101,102)", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP_N"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP_N"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROL_NAME', 'Asel_spr2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_TYP', 'DICTIONARY', 'ORDER_TYPES'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(2000)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROL_NAME', 'ATxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'CONTROL_NAME_EDIT', 'Atxt3'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_NAME', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'TITLE', 'Код приказа'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'CONTROLSOURCE', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PRIK_TYP"'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'QUICKSEARCH', '1'
GO
EXEC X_SET_PROP 'PUNKT_POSTANOV_PRIK_COD', 'DICTIONARY', 'ORDER_TYPES'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'ko_punkt_postanov', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'ko_punkt_postanov', 'Зарплата-КС', 4,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Пункты постановления/распоряжения"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KO_PUNKT_POSTANOV')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_FOLDER'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'PUNKT_POSTANOVLENIA'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'PUNKT_POSTANOVLENIA', 'Пункты постановления/распоряжения', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Группа должностей******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_POST_GROUP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_POST_GROUP')
	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 = 'FACE_POST_GROUP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_POST_GROUP')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_POST_GROUP'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_POST_GROUP')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_POST_GROUP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_POST_GROUP', 'Группа должностей', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_POST_GROUP', NAME = 'Группа должностей', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_POST_GROUP'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'TITLE', 'Группа должностей'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'CONTROLSOURCE', 'm.cAlias+".POST_GROUP"'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'SHORT_CODE_OBJ', 'POST_GROUP'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".POST_GROUP"'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'CONTROL_NAME_EDIT', 'atxtn10'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'REFERENCE_TO_FIELD', 'POST_GROUP'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_POST_GROUP', 'FIELD_DATA', 'post_group'
GO



-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Классный чин******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_CHIN')
	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 = 'FACE_CHIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_CHIN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_CHIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_CHIN', 'Классный чин', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_CHIN', NAME = 'Классный чин', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_CHIN'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'TITLE', 'Классный чин'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'CONTROLSOURCE', 'm.cAlias+".CHIN"'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'SHORT_CODE_OBJ', 'CHIN'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHIN"'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'CONTROL_NAME_EDIT', 'atxtn11'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'REFERENCE_TO_FIELD', 'CHIN'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_CHIN', 'FIELD_DATA', 'CHIN'
GO



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Дата присвоения классного чина******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN_DATE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_CHIN_DATE')
	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 = 'FACE_CHIN_DATE')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_CHIN_DATE')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN_DATE'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_CHIN_DATE')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_CHIN_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_CHIN_DATE', 'Дата присвоения классного чина', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_CHIN_DATE', NAME = 'Дата присвоения классного чина', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_CHIN_DATE'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'TITLE', 'Дата присвоения чина'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'CONTROLSOURCE', 'm.cAlias+".CHIN_DATE"'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'SHORT_CODE_OBJ', 'CHIN_DATE'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHIN_DATE"'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'CONTROL_NAME_EDIT', 'atxtn12'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'REFERENCE_TO_FIELD', 'CHIN_DATE'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_CHIN_DATE', 'FIELD_DATA', 'CHIN_DATE'
GO



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Электронный адрес******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_EMAIL')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_EMAIL')
	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 = 'FACE_EMAIL')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_EMAIL')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_EMAIL'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_EMAIL')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_EMAIL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_EMAIL', 'Электронный адрес', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_EMAIL', NAME = 'Электронный адрес', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_EMAIL'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'TITLE', 'EMAIL'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'CONTROLSOURCE', 'm.cAlias+".EMAIL"'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'SHORT_CODE_OBJ', 'EMAIL'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMAIL"'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'CONTROL_NAME_EDIT', 'atxtn13'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_EMAIL', 'FIELD_DATA', 'EMAIL'
GO



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Рабочий телефон******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_WORK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_PHONE_WORK')
	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 = 'FACE_PHONE_WORK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_PHONE_WORK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_WORK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_WORK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_PHONE_WORK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_PHONE_WORK', 'Рабочий телефон', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_PHONE_WORK', NAME = 'Рабочий телефон', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_PHONE_WORK'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'TITLE', 'Раб телефон'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'CONTROLSOURCE', 'm.cAlias+".PHONE_WORK"'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'SHORT_CODE_OBJ', 'PHONE_WORK'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PHONE_WORK"'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'CONTROL_NAME_EDIT', 'atxtn14'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'REFERENCE_TO_FIELD', 'PHONE_WORK'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_PHONE_WORK', 'FIELD_DATA', 'PHONE_WORK'
GO



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: Мобильный телефон******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_MOB')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_PHONE_MOB')
	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 = 'FACE_PHONE_MOB')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_PHONE_MOB')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_MOB'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_PHONE_MOB')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_PHONE_MOB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_PHONE_MOB', 'Мобильный телефон', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_PHONE_MOB', NAME = 'Мобильный телефон', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_PHONE_MOB'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'TITLE', 'Моб телефон'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'CONTROLSOURCE', 'm.cAlias+".PHONE_MOB"'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'SHORT_CODE_OBJ', 'PHONE_MOB'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PHONE_MOB"'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'CONTROL_NAME_EDIT', 'atxtn15'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'REFERENCE_TO_FIELD', 'PHONE_MOB'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_PHONE_MOB', 'FIELD_DATA', 'PHONE_MOB'
GO



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: ИНН******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_INN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_INN')
	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 = 'FACE_INN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_INN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_INN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_INN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_INN', 'ИНН', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_INN', NAME = 'ИНН', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_INN'
GO
EXEC X_SET_PROP 'FACE_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'FACE_INN', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_INN', 'CONTROLSOURCE', 'm.cAlias+".INN"'
GO
EXEC X_SET_PROP 'FACE_INN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_INN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_INN', 'TYPE_FIELD_DICT', 'VARCHAR(12)'
GO
EXEC X_SET_PROP 'FACE_INN', 'SHORT_CODE_OBJ', 'INN'
GO
EXEC X_SET_PROP 'FACE_INN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".INN"'
GO
EXEC X_SET_PROP 'FACE_INN', 'CONTROL_NAME_EDIT', 'atxtn16'
GO
EXEC X_SET_PROP 'FACE_INN', 'REFERENCE_TO_FIELD', 'INN'
GO
EXEC X_SET_PROP 'FACE_INN', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_INN', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_INN', 'FIELD_DATA', 'INN'
GO




--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Объект: СНИЛС******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'FACE_SNILS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_SNILS')
	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 = 'FACE_SNILS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'FACE_SNILS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'FACE_SNILS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'FACE_SNILS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FACE_SNILS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FACE_SNILS', 'СНИЛС', 33, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FACE_SNILS', NAME = 'СНИЛС', ORDERS = '33', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_PLACING'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FACE_SNILS'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'TITLE', 'СНИЛС'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'CONTROLSOURCE', 'm.cAlias+".SNILS"'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'TYPE_FIELD_DICT', 'VARCHAR(14)'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'SHORT_CODE_OBJ', 'SNILS'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SNILS"'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'CONTROL_NAME_EDIT', 'atxtn17'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'REFERENCE_TO_FIELD', 'SNILS'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'ATTRIBUTES', 'style="Z-INDEX: 121; LEFT: 272px; POSITION: absolute; TOP: 176px""
Width="242px"
ReadOnly="True"'
GO
EXEC X_SET_PROP 'FACE_SNILS', 'FIELD_DATA', 'SNILS'
GO




GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Документы по классным чинам"*************/ 
 DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS'),0)

IF COALESCE(@LINK_SELF,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADRY_CHIN_REPORTS', 'Документы по классным чинам', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', NULL, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Экзаменационный лист"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KJ_EKZ_LIST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'K_CHIN_ATT_LIST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'K_CHIN_ATT_LIST', 'Экзаменационный лист', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Отзыв руководителя"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_MANAGER_COMMENT')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'MANAGER_COMMENT'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'MANAGER_COMMENT', 'Отзыв руководителя', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Присвоение классного чина"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_ASSIGNMENT_CLASS_CHIN')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_CHIN_REPORTS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'ASSIGNMENT_CLASS_CHIN'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'ASSIGNMENT_CLASS_CHIN', 'Присвоение классного чина', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO


GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Документы по изменению должности"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_REPLACE_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADRY_REPLACE_POST', 'Документы по изменению должности', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', NULL, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Постановление о переводе на другую должность"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_POSTANOVLENIE_REPLACE_POST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_REPLACE_POST')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_REPLACE_POST'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'POSTANOVLENIE_REPLACE_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'POSTANOVLENIE_REPLACE_POST', 'Постановление о переводе на другую должность', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Распоряжение о переводе на другую должность"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_RASPORIAZENIE_REPLACE_POST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_REPLACE_POST')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_REPLACE_POST'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RASPORIAZENIE_REPLACE_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RASPORIAZENIE_REPLACE_POST', 'Распоряжение о переводе на другую должность', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO


GO

/****** Объект: Каталог документов по графикам отпусков******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_VACATION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_VACATION')
	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 = 'GROUP_DOCUMENTS_VACATION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'GROUP_DOCUMENTS_VACATION')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_VACATION'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'GROUP_DOCUMENTS_VACATION')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='GROUP_DOCUMENTS_VACATION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'GROUP_DOCUMENTS_VACATION', 'Каталог документов по графикам отпусков', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'GROUP_DOCUMENTS_VACATION', NAME = 'Каталог документов по графикам отпусков', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS_CATALOG_TREE_ROOT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_DOC_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='GROUP_DOCUMENTS_VACATION'
GO
EXEC X_SET_PROP 'GROUP_DOCUMENTS_VACATION', 'SELECT_RECORDS_METHOD', 'KIR_GET_DOCS_BY_CODE(''KADRY_VACATION_GRAPH_REP'')'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

EXEC DBO.W_SPERM_WRITE 'GROUP_DOCUMENTS_VACATION', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'GROUP_DOCUMENTS_VACATION', 'public', 5,0
GO



/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Документы по графикам отпусков"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP'),0)

IF COALESCE(@LINK_SELF,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADRY_VACATION_GRAPH_REP', 'Документы по графикам отпусков', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', NULL, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "График отпусков с датой окончания отпуска"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KJ_VACATION_GRAPHICS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KJ_VACATION_GRAPHICS', 'График отпусков с датой окончания отпуска', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "График отпусков(форма № Т-7)"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_KJ_VACATION_GRAPHICS_T7')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_VACATION_GRAPH_REP'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KJ_VACATION_GRAPHICS_T7'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KJ_VACATION_GRAPHICS_T7', 'График отпусков(форма № Т-7)', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO


GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Документы о приеме на работу"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_INVISIBLE'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_NEW_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADRY_NEW_POST', 'Документы о приеме на работу', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', NULL, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Постановление о приеме на работу"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_POSTANOVLENIE_NEW_POST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_NEW_POST')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_NEW_POST'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'POSTANOVLENIE_NEW_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'POSTANOVLENIE_NEW_POST', 'Постановление о приеме на работу', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Распоряжение о приеме на работу"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'KOD_RASPORIAZENIE_NEW_POST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_NEW_POST')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_NEW_POST'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RASPORIAZENIE_NEW_POST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RASPORIAZENIE_NEW_POST', 'Распоряжение о приеме на работу', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO


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 = 'LEDGER_GR_TURNS_ACCT_GR') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_ACCT_GR'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'LEDGER_GR_TURNS_JO_IN_STR') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_JO_IN_STR'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_KBK') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_KBK'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_SGU') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_SGU'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_ZB') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_NAS1_ZB'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'LEDGER_GR_TURNS_ZABALANS') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'LEDGER_GR_TURNS_ZABALANS'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS11') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS11'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS12') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS12'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS13') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS13'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS14') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS14'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS15') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS15'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS16') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS16'),
	(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_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS17') 
INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
Select ( Select link from object_var where code = 'SQL_REP_OSV_SINT_NAS17'),
	(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
	'1'
GO

GO
-- сначала удалим навигатор
DELETE FROM S_NAVIGATOR 
WHERE CODE  IN (
'RO_UNION_EGRL', 
'RO_IMPORT_EGRL',
'folder86n', 
'RO_CONVERT_EGRUL',
'RO_IMPORT_IT_86n',
'RO_IMPORT_OKTMO_86n',
'RO_IMPORT_OGS_86n',
'RO_IMPORT__86n', 
'REPORT_CHECK_SCAN_FILES_86N', 
'R_NAV_SEND_86n',
'REPORT_CHECK_SCAN_FILES_86N',
'REPORT_NAV_SEND_ORG_86N')


/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "86н"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'OUTPUTS_OPTIONS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_86N')

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 = 'OUTPUTS_OPTIONS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'folder86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'folder86n', '86н', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузка справочников"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'folder86n')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_86n')

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 = 'OUTPUTS_OPTIONS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '86n_NAV_IMPORT', 'Загрузка справочников', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', @OBJECT, @LINK_VAR, 3
GO


/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Проверка файлов для 86н"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'folder86n')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_CHECK_SCAN_FILES_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'REPORT_CHECK_SCAN_FILES_86N'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'REPORT_CHECK_SCAN_FILES_86N', 'Проверка файлов для 86н', @ORD, NULL, 1, @LINK_SELF, 'NASTR', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Объединение приложений (86н) с ЕГРЮЛ"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_UNION_EGRUL')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_UNION_EGRL'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_UNION_EGRL', 'Объединение приложений (86н) с ЕГРЮЛ', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить из ЕГРЮЛ"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRUL')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_EGRL'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_EGRL', 'Загрузить из ЕГРЮЛ', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Конвертация ЕГРЮЛ из xml в xls"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_UNION_EGRUL_1')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_CONVERT_EGRUL'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_CONVERT_EGRUL', 'Конвертация ЕГРЮЛ из xml в xls', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник видов деятельности из XML"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_IT_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_IT_86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_IT_86n', 'Загрузить справочник видов деятельности из XML', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник ОГС из XML"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_OGS_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_OGS_86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_OGS_86n', 'Загрузить справочник ОГС из XML', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник ППО из XML"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_PPO_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT__86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT__86n', 'Загрузить справочник ППО из XML', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник ОКТМО XML"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_OKTMO_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_OKTMO_86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_OKTMO_86n', 'Загрузить справочник ОКТМО из XML', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник ЕГРЮЛ"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRL_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_EGRL'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_EGRL_86n', 'Загрузить из ЕГРЮЛ (XML из налоговой)', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO




/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Передача данных на сайт"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'folder86n')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_SEND_86N')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'R_NAV_SEND_86n'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'R_NAV_SEND_86n', 'Передача данных на сайт', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Справочник организаций для передачи"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'folder86n')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'R_DICTION_86N_SEND_ORG')

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 = 'folder86n'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'REPORT_NAV_SEND_ORG_86N'),0)

--IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'REPORT_NAV_SEND_ORG_86N', 'Справочник организаций для передачи', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO



-- права
exec w_sperm_write @CodeObject = 'RO_UNION_EGRL', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT_EGRL', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'folder86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_CONVERT_EGRUL', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT_IT_86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT_OKTMO_86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT_OGS_86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT__86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_CHECK_SCAN_FILES_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'R_NAV_SEND_86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_CHECK_SCAN_FILES_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_EGRL_86n', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0


exec w_sperm_write @CodeObject = 'R_DICTION_86N_SEND_ORG', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_CHECK_SCAN_FILES_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_86N_SEND_FORM', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_86N_CHECK_FORM', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_IT_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_OKTMO_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_OGS_86N ', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_PPO_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'REPORT_SEND_86N', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = '86n_NAV_IMPORT', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0
exec w_sperm_write @CodeObject = 'RO_IMPORT_EGRL', @UserName = 'СВОД-КС', @Permitted = 63, @Restricted = 0

GO

GO
/****** Объект: Конвертация Услуг******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'report_service_86n')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'report_service_86n')
	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 = 'report_service_86n')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'report_service_86n')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'report_service_86n'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'report_service_86n')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SERVICE_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SERVICE_86N', 'Конвертация Услуг', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SERVICE_86N', NAME = 'Конвертация Услуг', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SERVICE_86N'
GO
EXEC X_SET_PROP 'REPORT_SERVICE_86N', 'INIT_OBJECT_METHOD', 'rn_convert_service()'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить справочник услуг из XML"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_SERVICE_86N')

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 = '86n_NAV_IMPORT'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_SERVICE_86n'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_SERVICE_86n', 'Загрузить справочник услуг из XML', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Пенсионность (список сотрудников)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KJ_PERS_PENSION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KJ_PERS_PENSION')
	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 = 'KJ_PERS_PENSION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KJ_PERS_PENSION')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KJ_PERS_PENSION'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KJ_PERS_PENSION')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION', 'Пенсионность (список сотрудников)', 81, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_PERSON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION', NAME = 'Пенсионность (список сотрудников)', ORDERS = '81', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_PERSON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KJ_PERS_PENSION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_PERS_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_PERS_LINK', 'Ссылка на физ. лицо', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_PERS_LINK', NAME = 'Ссылка на физ. лицо', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_PERS_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_FIO', 'ФИО', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_FIO', NAME = 'ФИО', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_DATE_PENS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_DATE_PENS', 'Дата пенсии', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_DATE_PENS', NAME = 'Дата пенсии', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_DATE_PENS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_DOC_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_DOC_NUM', '№ документа', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_DOC_NUM', NAME = '№ документа', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_DOC_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_DOC_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_DOC_DATE', 'Дата документа', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_DOC_DATE', NAME = 'Дата документа', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_DOC_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_COMMENT', 'Комментарий', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_COMMENT', NAME = 'Комментарий', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_CHECK_SZV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_CHECK_SZV', 'Включать в расчеты для ПФ', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_CHECK_SZV', NAME = 'Включать в расчеты для ПФ', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_CHECK_SZV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_WORK_PENS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_WORK_PENS', 'Работающий пенсионер', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_WORK_PENS', NAME = 'Работающий пенсионер', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_WORK_PENS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_CHECK_SZVC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_CHECK_SZVC', 'Включать в расчеты для ПФ', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_CHECK_SZVC', NAME = 'Включать в расчеты для ПФ', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_CHECK_SZVC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION_WORK_PENSC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KJ_PERS_PENSION_WORK_PENSC', 'Работающий пенсионер', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KJ_PERS_PENSION_WORK_PENSC', NAME = 'Работающий пенсионер', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_PERS_PENSION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KJ_PERS_PENSION_WORK_PENSC'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'TITLE', 'Пенсионеры'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'INIT_OBJECT_METHOD', 'KJ_PERS_PENSION(''KJ_PERS_PENSION'')'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KJ_PERS_PENSION", "KJ_PERS_PENSION_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KJ_PERS_PENSION_SAVE'', m.cAlias," SQLNULL(PERS_LINK), DOC_NUM,SQLNULL(DOC_DATE),SQLNULL(DATE_PENS),CHECK_SZV,WORK_PENS,COMMENT","KJ_PERS_PENSION")'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'EDIT_OBJECT_METHOD', 'k_brow(''KJ_PERS_PENSION_EDIT'')'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''KJ_PERS_PENSION'')'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''KJ_PERS_PENSION'')'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_PERS_LINK', 'CONTROLSOURCE', 'm.cAlias+".PERS_LINK"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_PERS_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_PERS_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_PERS_LINK', 'SHORT_CODE_OBJ', 'PERS_LINK'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_PERS_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PERS_LINK"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("KU_PERSON  ",oForm.ALIAS,"LINK, FIO", "PERS_LINK, FIO", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'CONTROLSOURCE', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FIO"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_FIO', 'CONTROL_NAME_EDIT', 'ASEL_FIO'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'TITLE', 'Дата пенсии'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'CONTROLSOURCE', 'm.cAlias+".DATE_PENS"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_PENS"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DATE_PENS', 'CONTROL_NAME_EDIT', 'ASEL_PENS_DATE'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'TITLE', '№ документа'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'CONTROLSOURCE', 'm.cAlias+".DOC_NUM"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DOC_NUM"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_NUM', 'CONTROL_NAME_EDIT', 'txtDOC_NUM'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'TITLE', 'Дата документа'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'CONTROLSOURCE', 'm.cAlias+".DOC_DATE"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DOC_DATE"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_DOC_DATE', 'CONTROL_NAME_EDIT', 'ASEL_DOC_DATE'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'CONTROLSOURCE', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_COMMENT', 'CONTROL_NAME_EDIT', 'txtCOMMENT'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'TITLE', 'Включать для ПФ'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'CONTROLSOURCE', 'm.cAlias+".CHECK_SZV"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'FIELD_IN_ALIAS', '4'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECK_SZV"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'CONTROL_NAME_EDIT', 'Acheck_SZV'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZV', 'COMMENTARY', 'При расчете для ПФ , пенсионер будет включаться в расчет'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'TITLE', 'Работает'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'CONTROLSOURCE', 'm.cAlias+".WORK_PENS"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'FIELD_IN_ALIAS', '4'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".WORK_PENS"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'CONTROL_NAME_EDIT', 'Acheck_WORK_PENS'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENS', 'COMMENTARY', 'Работающий пенсионер'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'TITLE', 'Расчеты для ПФ'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'CONTROLSOURCE', 'm.cAlias+".CHECK_SZVC"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'FIELD_IN_ALIAS', '4'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'TYPE_FIELD_DICT', 'char(4)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_CHECK_SZVC', 'COMMENTARY', 'При расчете для ПФ , пенсионер будет включаться в расчет'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'TITLE', 'Работает'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'CONTROLSOURCE', 'm.cAlias+".WORK_PENSC"'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'FIELD_IN_ALIAS', '4'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'TYPE_FIELD_DICT', 'char(4)'
GO
EXEC X_SET_PROP 'KJ_PERS_PENSION_WORK_PENSC', 'COMMENTARY', 'Работающий пенсионер'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KJ_PERS_PENSION', 'Зарплата-КС', 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 = 'KADRY')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KJ_PERS_PENSION')

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 = 'KADRY'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KJ_PERS_PENSION_NAV'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KJ_PERS_PENSION_NAV', 'Пенсионеры', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
if NOT EXISTS(SELECT * FROM report_options WHERE razdel = 'FORM_155')
BEGIN
   INSERT dbo.report_options ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Str], [SID])
   VALUES ('FORM_155', 'IMPORT_KBP_155', 1, 'КБП при импорте', 3, '', 0x01)

   INSERT dbo.report_options ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Str], [SID])
   VALUES ('FORM_155', 'IMPORT_VB_155', 2, 'ВБ при импорте', 3, '', 0x01)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'FORM_155'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC]  'FORM_155'

END     
GO
/****** Объект: Вкладка "155"******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_155')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RA_REP_OPTIONS_FORM_155')
	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 = 'RA_REP_OPTIONS_FORM_155')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RA_REP_OPTIONS_FORM_155')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_155'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_155')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_155', 'Вкладка "155"', 41, (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_155', NAME = 'Вкладка "155"', ORDERS = '41', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_155'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155B_KBP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_155B_KBP', '155 КБП', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_155B_KBP', NAME = '155 КБП', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_155B_KBP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155B_VB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_155B_VB', '155 ВБ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_155B_VB', NAME = '155 ВБ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_155B_VB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_OPTIONS_FORM_155_UK', 'Соответствие УК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_OPTIONS_FORM_155_UK', NAME = 'Соответствие УК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_155'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_OPTIONS_FORM_155_UK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_OPTIONS_FORM_155_UK_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_OPTIONS_FORM_155_UK_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_OPTIONS_FORM_155_UK_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_OPTIONS_FORM_155_UK_CODE', 'Код УК', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_OPTIONS_FORM_155_UK_CODE', NAME = 'Код УК', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_OPTIONS_FORM_155_UK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK_KBP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_OPTIONS_FORM_155_UK_KBP', 'КБП', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_OPTIONS_FORM_155_UK_KBP', NAME = 'КБП', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_OPTIONS_FORM_155_UK_KBP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK_VB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_OPTIONS_FORM_155_UK_VB', 'Выгружаемый код бюджета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_OPTIONS_FORM_155_UK_VB', NAME = 'Выгружаемый код бюджета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_OPTIONS_FORM_155_UK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_OPTIONS_FORM_155_UK_VB'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155', 'SELECT_RECORDS_METHOD', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_FORM_155'', m.cAlias)'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_FORM_155'', m.cAlias)'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'CONTROLSOURCE', 'm.cAlias + ''.IMPORT_KBP_155'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'SHORT_CODE_OBJ', 'IMPORT_KBP_155'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.IMPORT_KBP_155'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_KBP', 'CONTROL_NAME_EDIT', 'txtIMPORT_KBP_155'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'CONTROLSOURCE', 'm.cAlias + ''.IMPORT_VB_155'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'SHORT_CODE_OBJ', 'IMPORT_VB_155'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.IMPORT_VB_155'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_155B_VB', 'CONTROL_NAME_EDIT', 'txtIMPORT_VB_155'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK', 'REMOVE_OBJECT_METHOD', 'ro_151_152_uk_delete(m.cAlias,''0503155'')'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK', 'EDIT_OBJECT_METHOD', 'ro_151_152_UK_edit(oForm)'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK', 'SELECT_RECORDS_METHOD', 'sql.exec("SELECT 0 as checked, 0 as upd, 0 as del, link, [UK], [KBP], [VB]  FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] WHERE [FORM_CODE] =             ''0503155''", m.cAlias)'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec("SELECT 0 as checked, 0 as upd, 0 as del, link, [UK], [KBP], [VB]  FROM dbo.[REPORT_EXCHANGE_ACCORDANCE] WHERE [FORM_CODE] =             ''0503155'' and Link =" + STR(m.nLink), m.cAlias)'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_MARKER', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_MARKER', 'CONTROLSOURCE', 'm.cAlias + ''.checked'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_MARKER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.checked'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_CODE', 'TITLE', 'Код УК'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_CODE', 'CONTROLSOURCE', 'm.cAlias + ''.UK'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.UK'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_KBP', 'TITLE', 'КБП'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_KBP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_KBP', 'CONTROLSOURCE', 'm.cAlias + ''.KBP'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_KBP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_KBP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.KBP'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_VB', 'TITLE', 'Выгружаемый код бюджета'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_VB', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_VB', 'CONTROLSOURCE', 'm.cAlias + ''.VB'''
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_VB', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_OPTIONS_FORM_155_UK_VB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.VB'''
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_86N', 'Отчетность: Все для 86н', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='OUTPUTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CONTAINER_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_86N', NAME = 'Отчетность: Все для 86н', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='OUTPUTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CONTAINER_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='REPORT_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_86N_SEND_FORM', 'Список форм для передачи 86н', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_86N_SEND_FORM', NAME = 'Список форм для передачи 86н', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_86N_SEND_FORM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_86N_CHECK_FORM', 'Контроль скан-копий для 86н', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_86N_CHECK_FORM', NAME = 'Контроль скан-копий для 86н', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_86N_CHECK_FORM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_NASTR_86_WEB', 'Настройки 86н WEB', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_NASTR_86_WEB', NAME = 'Настройки 86н WEB', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_NASTR_86_WEB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_EGRUL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_EGRUL', 'Загрузить из ЕГРЮЛ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_EGRUL', NAME = 'Загрузить из ЕГРЮЛ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_EGRUL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_UNION_EGRUL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_UNION_EGRUL', 'Объединение приложений (86н) с ЕГРЮЛ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_UNION_EGRUL', NAME = 'Объединение приложений (86н) с ЕГРЮЛ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_UNION_EGRUL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_UNION_EGRUL_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_UNION_EGRUL_1', 'Конвертация ЕГРЮЛ из xml в xls', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_UNION_EGRUL_1', NAME = 'Конвертация ЕГРЮЛ из xml в xls', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_UNION_EGRUL_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_CHECK_SCAN_FILES_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_CHECK_SCAN_FILES_86N', 'Проверка скан копий документов для 86н', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_CHECK_SCAN_FILES_86N', NAME = 'Проверка скан копий документов для 86н', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_CHECK_SCAN_FILES_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_IT_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_IT_86N', 'Конвертация Видов деятельности', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_IT_86N', NAME = 'Конвертация Видов деятельности', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_IT_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_OGS_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_OGS_86N', 'Конвертация ОГС', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_OGS_86N', NAME = 'Конвертация ОГС', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_OGS_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_PPO_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_PPO_86N', 'Конвертация ППО', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_PPO_86N', NAME = 'Конвертация ППО', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_PPO_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SEND_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SEND_86N', 'Передача данных', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SEND_86N', NAME = 'Передача данных', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SEND_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SERVICE_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SERVICE_86N', 'Конвертация Услуг', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SERVICE_86N', NAME = 'Конвертация Услуг', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SERVICE_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_OKTMO_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_OKTMO_86N', 'Конвертация ОКТМО', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_OKTMO_86N', NAME = 'Конвертация ОКТМО', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_OKTMO_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_BUDGET_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_BUDGET_86N', 'Конвертация Бюджетов', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_BUDGET_86N', NAME = 'Конвертация Бюджетов', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_BUDGET_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_DICTION_86N_SEND_ORG', 'Справочник Организаций для выгрузки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_DICTION_86N_SEND_ORG', NAME = 'Справочник Организаций для выгрузки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_DICTION_86N_SEND_ORG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_DICTION_86N_ORG', 'Справочник Организаций', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_DICTION_86N_ORG', NAME = 'Справочник Организаций', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_DICTION_86N_ORG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_ADRESS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_ADRESS', 'Адрес', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_ADRESS', NAME = 'Адрес', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_ADRESS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_USER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_USER', 'Логин', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_USER', NAME = 'Логин', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_USER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_PWD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_PWD', 'Пароль', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_PWD', NAME = 'Пароль', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_PWD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_PROXY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_PROXY', 'Использовать прокси', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_PROXY', NAME = 'Использовать прокси', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_PROXY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_P_ADR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_P_ADR', 'Адрес прокси', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_P_ADR', NAME = 'Адрес прокси', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_P_ADR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_P_LOG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_P_LOG', 'Логин', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_P_LOG', NAME = 'Логин', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_P_LOG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_P_PWD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_P_PWD', 'Пароль', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_P_PWD', NAME = 'Пароль', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_P_PWD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_P_PORT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_P_PORT', 'Порт', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_P_PORT', NAME = 'Порт', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_P_PORT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_WEB_TIMEOUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_WEB_TIMEOUT', 'Таймаут', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_WEB_TIMEOUT', NAME = 'Таймаут', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_WEB_TIMEOUT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='86REPORT_NASTR_SVOD_WEB_EXT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT '86REPORT_NASTR_SVOD_WEB_EXT', 'Внешняя программа для передачи', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = '86REPORT_NASTR_SVOD_WEB_EXT', NAME = 'Внешняя программа для передачи', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_NASTR_86_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='86REPORT_NASTR_SVOD_WEB_EXT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FROM_MARKE_6')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'Поле-маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FROM_MARKE_6', NAME = 'Поле-маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FROM_MARKE_6'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2', 'Статус отчета', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2', NAME = 'Статус отчета', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_KS_1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_KS_1_2', 'Правильность контрольных соотношений', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_KS_1_2', NAME = 'Правильность контрольных соотношений', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_KS_1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_STATUS_ECP_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_STATUS_ECP_2', 'Статус ЭЦП отчета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_STATUS_ECP_2', NAME = 'Статус ЭЦП отчета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_STATUS_ECP_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_CLOSE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_CLOSE', 'Организация закрыта', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_CLOSE', NAME = 'Организация закрыта', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_CLOSE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2_1', 'Статус передачи', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2_1', NAME = 'Статус передачи', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2_2', 'Количество переданных документов', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2_2', NAME = 'Количество переданных документов', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2_3', 'Дата передачи', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2_3', NAME = 'Дата передачи', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FORM_CODE__5')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FORM_CODE__5', 'Код', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FORM_CODE__5', NAME = 'Код', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FORM_CODE__5'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_ATR_VAL_1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_ATR_VAL_1_2', 'Атрибут', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_ATR_VAL_1_2', NAME = 'Атрибут', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_ATR_VAL_1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ORG_BUDG_1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'Код бюджетополучателя организации', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', NAME = 'Код бюджетополучателя организации', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ORG_BUDG_1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ORG_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ORG_INN', 'ИНН', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ORG_INN', NAME = 'ИНН', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ORG_INN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_PERIOD_1_2_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'Период', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_PERIOD_1_2_2', NAME = 'Период', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_PERIOD_1_2_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_VERSION_1__2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_VERSION_1__2', 'Версия', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_VERSION_1__2', NAME = 'Версия', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_VERSION_1__2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_SVOD_TYPE_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_SVOD_TYPE_2', 'Тип свода', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_SVOD_TYPE_2', NAME = 'Тип свода', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_SVOD_TYPE_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FORM_NAME__5')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FORM_NAME__5', 'Форма отчетности', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FORM_NAME__5', NAME = 'Форма отчетности', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FORM_NAME__5'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ORG_1_2_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ORG_1_2_2', 'Организация', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ORG_1_2_2', NAME = 'Организация', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ORG_1_2_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_COND_WHO_LAST_EDIT_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_COND_WHO_LAST_EDIT_2', 'Автор последних изменений', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_COND_WHO_LAST_EDIT_2', NAME = 'Автор последних изменений', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_COND_WHO_LAST_EDIT_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_COND_DATE_LAST_EDIT_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_COND_DATE_LAST_EDIT_2', 'Дата последнего изменения', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_COND_DATE_LAST_EDIT_2', NAME = 'Дата последнего изменения', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_COND_DATE_LAST_EDIT_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ANALIT_1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ANALIT_1_2', 'Примечание', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ANALIT_1_2', NAME = 'Примечание', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ANALIT_1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_VIEW_START_DATE_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_VIEW_START_DATE_2', 'Дата ввода', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_VIEW_START_DATE_2', NAME = 'Дата ввода', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_VIEW_START_DATE_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_DATE_TRANSFER_WE_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_DATE_TRANSFER_WE_3', 'Дата передачи в Свод-WEB', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_DATE_TRANSFER_WE_3', NAME = 'Дата передачи в Свод-WEB', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_SEND_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_DATE_TRANSFER_WE_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FROM_MARKE_5')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'Поле-маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FROM_MARKE_5', NAME = 'Поле-маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FROM_MARKE_5'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2_4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2_4', 'Статус отчета', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2_4', NAME = 'Статус отчета', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2_4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_KS_1_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_KS_1_2_1', 'Правильность контрольных соотношений', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_KS_1_2_1', NAME = 'Правильность контрольных соотношений', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_KS_1_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_STATUS_ECP_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_STATUS_ECP_2_1', 'Статус ЭЦП отчета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_STATUS_ECP_2_1', NAME = 'Статус ЭЦП отчета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_STATUS_ECP_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_STATUS_1_2_5')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_STATUS_1_2_5', 'Статус контроля', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_STATUS_1_2_5', NAME = 'Статус контроля', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_STATUS_1_2_5'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FORM_CODE__4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FORM_CODE__4', 'Код', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FORM_CODE__4', NAME = 'Код', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FORM_CODE__4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_ATR_VAL_1_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_ATR_VAL_1_2_1', 'Атрибут', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_ATR_VAL_1_2_1', NAME = 'Атрибут', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_ATR_VAL_1_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_PERIOD_1_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'Период', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_PERIOD_1_2_1', NAME = 'Период', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_PERIOD_1_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_VERSION_1__1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_VERSION_1__1', 'Версия', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_VERSION_1__1', NAME = 'Версия', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_VERSION_1__1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_SVOD_TYPE_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_SVOD_TYPE_2_1', 'Тип свода', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_SVOD_TYPE_2_1', NAME = 'Тип свода', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_SVOD_TYPE_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_FORM_NAME__4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_FORM_NAME__4', 'Форма отчетности', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_FORM_NAME__4', NAME = 'Форма отчетности', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_FORM_NAME__4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ORG_1_2_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'Организация', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ORG_1_2_2_1', NAME = 'Организация', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ORG_1_2_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ORG_BUDG_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'Код бюджетополучателя организации', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', NAME = 'Код бюджетополучателя организации', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ORG_BUDG_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_COND_WHO_LAST_EDIT_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_COND_WHO_LAST_EDIT_2_1', 'Автор последних изменений', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_COND_WHO_LAST_EDIT_2_1', NAME = 'Автор последних изменений', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_COND_WHO_LAST_EDIT_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_COND_DATE_LAST_EDIT_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_COND_DATE_LAST_EDIT_2_1', 'Дата последнего изменения', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_COND_DATE_LAST_EDIT_2_1', NAME = 'Дата последнего изменения', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_COND_DATE_LAST_EDIT_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FORMS_ANALIT_1_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'Примечание', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FORMS_ANALIT_1_2_1', NAME = 'Примечание', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FORMS_ANALIT_1_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_VIEW_START_DATE__1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_VIEW_START_DATE__1', 'Дата ввода', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_VIEW_START_DATE__1', NAME = 'Дата ввода', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_VIEW_START_DATE__1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SVOD_DATE_TRANSFER_WE_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SVOD_DATE_TRANSFER_WE_2', 'Дата передачи в Свод-WEB', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SVOD_DATE_TRANSFER_WE_2', NAME = 'Дата передачи в Свод-WEB', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N_CHECK_FORM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SVOD_DATE_TRANSFER_WE_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_MARKER_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_MARKER_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_MARKER_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_MARKER_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_CODE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_CODE_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_CODE_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_CODE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_NAME_1', 'ИНН', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_NAME_1', NAME = 'ИНН', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_CODE_ADM_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_CODE_ADM_1', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_CODE_ADM_1', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_CODE_ADM_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG_OGS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_DICTION_86N_SEND_ORG_OGS', 'ОГС', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_DICTION_86N_SEND_ORG_OGS', NAME = 'ОГС', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_DICTION_86N_SEND_ORG_OGS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG_OGS_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_DICTION_86N_SEND_ORG_OGS_1', 'Привязка', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_DICTION_86N_SEND_ORG_OGS_1', NAME = 'Привязка', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_DICTION_86N_SEND_ORG_OGS_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_DICTION_86N_SEND_ORG_END', 'Закрыта', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_DICTION_86N_SEND_ORG_END', NAME = 'Закрыта', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_DICTION_86N_SEND_ORG_END'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_MARKER_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_MARKER_1_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_MARKER_1_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_MARKER_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_CODE_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_CODE_1_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_CODE_1_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_CODE_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_NAME_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_NAME_1_1', 'ИНН', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_NAME_1_1', NAME = 'ИНН', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_NAME_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_LINK_ADM_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'КБП', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_LINK_ADM_1_1', NAME = 'КБП', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_LINK_ADM_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_CODE_ADM_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_CODE_ADM_1_1', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_CODE_ADM_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KL_VKR_SGU_CODE_ADM_1_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'Тип', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', NAME = 'Тип', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_DICTION_86N_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_KL_VKR_SGU_CODE_ADM_1_1_1'
GO
EXEC X_SET_PROP 'REPORT_86N_SEND_FORM', 'TITLE', 'Список форм'
GO
EXEC X_SET_PROP 'REPORT_86N_SEND_FORM', 'CLOSE_CODE', 'LINK_form'
GO
EXEC X_SET_PROP 'REPORT_86N_SEND_FORM', 'SELECT_RECORDS_METHOD', 'sql.exec(''RN_86n_GET_SEND_FORMS'', m.cAlias)'
GO
EXEC X_SET_PROP 'REPORT_86N_CHECK_FORM', 'TITLE', 'Список форм'
GO
EXEC X_SET_PROP 'REPORT_86N_CHECK_FORM', 'CLOSE_CODE', 'LINK_form'
GO
EXEC X_SET_PROP 'REPORT_86N_CHECK_FORM', 'SELECT_RECORDS_METHOD', 'sql.exec(''RN_86n_CHECK_SCAN_FILES  @iMode=1'', m.cAlias)'
GO
EXEC X_SET_PROP 'REPORT_EGRUL', 'INIT_OBJECT_METHOD', 'ro_import_egrl()'
GO
EXEC X_SET_PROP 'REPORT_UNION_EGRUL', 'INIT_OBJECT_METHOD', 'ro_union_egrl()'
GO
EXEC X_SET_PROP 'REPORT_UNION_EGRUL_1', 'INIT_OBJECT_METHOD', 'ro_convert_egrl()'
GO
EXEC X_SET_PROP 'REPORT_CHECK_SCAN_FILES_86N', 'INIT_OBJECT_METHOD', 'rn_check_86n()'
GO
EXEC X_SET_PROP 'REPORT_IT_86N', 'INIT_OBJECT_METHOD', 'rn_convert_it()'
GO
EXEC X_SET_PROP 'REPORT_OGS_86N', 'INIT_OBJECT_METHOD', 'rn_convert_ogs()'
GO
EXEC X_SET_PROP 'REPORT_PPO_86N', 'INIT_OBJECT_METHOD', 'rn_convert_ppo()'
GO
EXEC X_SET_PROP 'REPORT_SEND_86N', 'INIT_OBJECT_METHOD', 'rn_send_86n()'
GO
EXEC X_SET_PROP 'REPORT_SERVICE_86N', 'INIT_OBJECT_METHOD', 'rn_convert_service()'
GO
EXEC X_SET_PROP 'REPORT_OKTMO_86N', 'INIT_OBJECT_METHOD', 'rn_convert_oktmo()'
GO
EXEC X_SET_PROP 'REPORT_BUDGET_86N', 'INIT_OBJECT_METHOD', 'rn_convert_budget()'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'TITLE', 'Справочник Организаций для выгрузки'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'INIT_OBJECT_METHOD', 'rn_86n_org_send(''R_DICTION_86N_SEND_ORG'')'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "REPORT_KBK", "RN_DELETE_REPORT_KBK", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SAVE_OBJECT_METHOD', 'X_SAVE(''RN_SAVE_REPORT_KBK'', m.cAlias, "CODE,0,NAME, ''R_86n_SEND_ORG'',0,INN,0,LINK_SITE+''#''+END,OGS","REPORT_KBK")'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'EDIT_OBJECT_METHOD', 'x_brow()'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SELECT_RECORDS_METHOD', 'SQL.EXEC("SELECT 0 as checked, 0 as UPD, 0 AS DEL,LINK,LINK_SELF,CODE, LEFT(INN,20) AS INN, NAME, ''R_86n_SEND_ORG'' AS CODE_FORM, LEFT(OGS,20) AS OGS,LINK_SITE,[END] FROM R_86n_SEND_ORG",m.cAlias)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'ROWSOURCE', 'ДА ,НЕТ'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SELECT_RECORDS_METHOD_EDIT', 'SQL.EXEC(''SELECT 0 AS DEL, LINK,0 AS UPD,CODE, LEFT(INN,20) AS INN,  NAME,  LEFT(OGS,20) AS OGS,LINK_SITE, [END] FROM R_86n_SEND_ORG WHERE LINK=''+STR(m.nLink),m.cAlias)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SERVER_TABLE_NAME', 'REPORT_KBK'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''R_DICTION_86N_SEND_ORG '''
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''RO_KL_VKR_SGU'''
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG', 'SAVE_OBJECT_METHOD_SQL', 'RO_WEB_SAVE_KL_VKR_SGU'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'TITLE', 'Справочник Организаций'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'INIT_OBJECT_METHOD', 'x_spisok(''R_DICTION_86N_ORG'')'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'EDIT_OBJECT_METHOD', 'x_brow()'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'SELECT_RECORDS_METHOD', 'SQL.EXEC("SELECT 0 as checked, 0 as UPD, 0 AS DEL,LINK,CODE, INN, LEFT(BUDG,20) AS KBP, NAME, NM_BUHTYPE FROM DICTIONARY_DEPARTMENT",m.cAlias)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'SERVER_TABLE_NAME', 'REPORT_KBK'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''R_DICTION_86N_SEND_ORG '''
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''RO_KL_VKR_SGU'''
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'SAVE_OBJECT_METHOD_SQL', 'RO_WEB_SAVE_KL_VKR_SGU'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_6', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2', 'TITLE', 'Статус'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2', 'CONTROLSOURCE', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2', 'TITLE', 'КС'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2', 'CONTROLSOURCE', 'm.cAlias+".IsRightKS"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRightKS"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2', 'TITLE', 'П'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2', 'CONTROLSOURCE', 'm.cAlias+".IsSign"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsSign"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_CLOSE', 'TITLE', 'Организация закрыта'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_CLOSE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_CLOSE', 'CONTROLSOURCE', 'm.cAlias+".CLOSE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_CLOSE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_1', 'TITLE', 'Статус передачи'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_1', 'CONTROLSOURCE', 'm.cAlias+".SEND_STATUS"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_2', 'TITLE', 'Количество переданных документов'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_2', 'CONTROLSOURCE', 'm.cAlias+".SEND_COUNT_DOC"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_3', 'TITLE', 'Дата передачи'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_3', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_3', 'CONTROLSOURCE', 'm.cAlias+".SEND_DATE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_3', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__5', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__5', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__5', 'CONTROLSOURCE', 'm.cAlias+".FORM_CODE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__5', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FORM_CODE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__5', 'CONTROL_NAME_EDIT', 'pages.page1.ATextCODE'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'TITLE', 'Атрибуты'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'CONTROLSOURCE', 'm.cAlias+".atr_val"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".atr_val"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'ATTRIBUTES', 'style="Z-INDEX: 109; LEFT: 128px; POSITION: absolute; TOP: 118px"
Width="64px"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 108; LEFT: 24px; POSITION: absolute; TOP: 118px"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'FIELD_ALIAS', 'REP_HEAD'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'FIELD_DATA', 'ATR_VAL'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2', 'FIELD_KEY', 'ATR_VAL'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'TITLE', 'КБП'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'CONTROLSOURCE', 'm.cAlias+".Dep_Budg"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Dep_Budg"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_INN', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_INN', 'CONTROLSOURCE', 'm.cAlias+".INN"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_INN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".INN"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_INN', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'TITLE', 'Период'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'CONTROLSOURCE', 'm.cAlias+".Period"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Period"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__2', 'TITLE', 'Версия'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__2', 'CONTROLSOURCE', 'm.cAlias+".Version"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Version"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2', 'TITLE', 'Тип свода'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2', 'CONTROLSOURCE', 'm.cAlias+".Type_Svod"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Type_Svod"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__5', 'TITLE', 'Форма отчетности'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__5', 'CONTROLSOURCE', 'm.cAlias+".Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__5', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__5', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2', 'CONTROLSOURCE', 'm.cAlias+".Dep_Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Dep_Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2', 'TITLE', 'Автор'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2', 'CONTROLSOURCE', 'm.cAlias+".WhoLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".WhoLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2', 'CONTROLSOURCE', 'm.cAlias+".DateLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DateLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2', 'TITLE', 'Прим.'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2', 'CONTROLSOURCE', 'm.cAlias+".Note"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Note"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE_2', 'TITLE', 'Дата ввода'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE_2', 'CONTROLSOURCE', 'm.cAlias+".START_DATE"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".START_DATE"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_3', 'TITLE', 'Дата передачи в Свод-WEB'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_3', 'CONTROLSOURCE', 'm.cAlias+".date_transfer_web"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_3', 'CONTROLSOURCE_EDIT', 'm.cAlias+".date_transfer_web"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FROM_MARKE_5', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_4', 'TITLE', 'Статус'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_4', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_4', 'CONTROLSOURCE', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_4', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2_1', 'TITLE', 'КС'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2_1', 'CONTROLSOURCE', 'm.cAlias+".IsRightKS"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_KS_1_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRightKS"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2_1', 'TITLE', 'П'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2_1', 'CONTROLSOURCE', 'm.cAlias+".IsSign"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_STATUS_ECP_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsSign"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_5', 'TITLE', 'Статус контроля скан-документов'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_5', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_5', 'CONTROLSOURCE', 'm.cAlias+".CHECK_STATUS"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_STATUS_1_2_5', 'CONTROLSOURCE_EDIT', 'm.cAlias+".IsRO"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__4', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__4', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__4', 'CONTROLSOURCE', 'm.cAlias+".FORM_CODE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__4', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FORM_CODE"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_CODE__4', 'CONTROL_NAME_EDIT', 'pages.page1.ATextCODE'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'TITLE', 'Атрибуты'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'CONTROLSOURCE', 'm.cAlias+".atr_val"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".atr_val"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'ATTRIBUTES', 'style="Z-INDEX: 109; LEFT: 128px; POSITION: absolute; TOP: 118px"
Width="64px"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 108; LEFT: 24px; POSITION: absolute; TOP: 118px"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'FIELD_ALIAS', 'REP_HEAD'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'FIELD_DATA', 'ATR_VAL'
GO
EXEC X_SET_PROP 'REPORT_SVOD_ATR_VAL_1_2_1', 'FIELD_KEY', 'ATR_VAL'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'TITLE', 'Период'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'CONTROLSOURCE', 'm.cAlias+".Period"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Period"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_PERIOD_1_2_1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__1', 'TITLE', 'Версия'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__1', 'CONTROLSOURCE', 'm.cAlias+".Version"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Version"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_VERSION_1__1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2_1', 'TITLE', 'Тип свода'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2_1', 'CONTROLSOURCE', 'm.cAlias+".Type_Svod"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Type_Svod"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_SVOD_TYPE_2_1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__4', 'TITLE', 'Форма отчетности'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__4', 'CONTROLSOURCE', 'm.cAlias+".Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__4', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_FORM_NAME__4', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'CONTROLSOURCE', 'm.cAlias+".Dep_Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Dep_Name"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_1_2_2_1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'TITLE', 'КБП'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'CONTROLSOURCE', 'm.cAlias+".Dep_Budg"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Dep_Budg"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ORG_BUDG_1_1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2_1', 'TITLE', 'Автор'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2_1', 'CONTROLSOURCE', 'm.cAlias+".WhoLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_WHO_LAST_EDIT_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".WhoLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2_1', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2_1', 'CONTROLSOURCE', 'm.cAlias+".DateLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_COND_DATE_LAST_EDIT_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DateLastEdit"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'TITLE', 'Прим.'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'CONTROLSOURCE', 'm.cAlias+".Note"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Note"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FORMS_ANALIT_1_2_1', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE__1', 'TITLE', 'Дата ввода'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE__1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE__1', 'CONTROLSOURCE', 'm.cAlias+".START_DATE"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_VIEW_START_DATE__1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".START_DATE"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_2', 'TITLE', 'Дата передачи в Свод-WEB'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_2', 'CONTROLSOURCE', 'm.cAlias+".date_transfer_web"'
GO
EXEC X_SET_PROP 'REPORT_SVOD_DATE_TRANSFER_WE_2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".date_transfer_web"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DEPARTMENT",oForm.ALIAS, "CODE, INN,BUDG,NAME", "CODE,INN,KBP,NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'CONTROLSOURCE', 'm.cAlias + ".INN"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".INN"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 16px""
Width="510px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1', 'FIELD_DATA', 'INN'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'TITLE', 'ОГС'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SPR_86n_OGS",oForm.ALIAS, "CODE", "OGS", "", "", "INN=''"+INN+"''", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'CONTROLSOURCE', 'm.cAlias + ".OGS"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OGS"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'CONTROL_NAME_EDIT', 'ASel_Spr4'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'TITLE', 'Привязка'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_SITE"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'ROWSOURCE', '"ДА ,НЕТ"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_SITE"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'CONTROL_NAME_EDIT', 'aCMB5'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_OGS_1', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'TITLE', 'Закрыта'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'CONTROLSOURCE', 'm.cAlias + ".END"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'ROWSOURCE', '"ДА,НЕТ"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".END"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'CONTROL_NAME_EDIT', 'aCMB6'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'R_DICTION_86N_SEND_ORG_END', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_MARKER_1_1', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DEPARTMENT",oForm.ALIAS, "CODE, INN,BUDG,NAME", "CODE,INN,KBP,NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_1_1', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'CONTROLSOURCE', 'm.cAlias + ".INN"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".INN"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 16px""
Width="510px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_NAME_1_1', 'FIELD_DATA', 'INN'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'TITLE', 'КБП'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'CONTROLSOURCE', 'm.cAlias + ".KBP"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBP"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_LINK_ADM_1_1', 'FIELD_DATA', 'KBP'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'CONTROL_NAME_EDIT', 'ATxt4'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'TITLE', 'Тип организации'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'CONTROLSOURCE', 'm.cAlias + ".NM_BUHTYPE"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NM_BUHTYPE"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'CONTROL_NAME_EDIT', 'ATxt4'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 46px""
Width="70px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'RO_KL_VKR_SGU_CODE_ADM_1_1_1', 'FIELD_DATA', 'CODE_ADM'
GO
EXEC X_SET_PROP 'REPORT_86N_SEND_FORM', 'SELECT_RECORDS_METHOD', 'sql.exec(''RN_86n_GET_SEND_FORMS''+"''"+m.cgetForm+"''", m.cAlias)'
GO
EXEC X_SET_PROP 'R_DICTION_86N_ORG', 'EDIT_OBJECT_METHOD', ''
GO

GO
/****** Объект: Конвертация ЕГРЮЛ******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRL_86N')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_EGRL_86N')
	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 = 'REPORT_EGRL_86N')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_EGRL_86N')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRL_86N'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRL_86N')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_EGRL_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_EGRL_86N', 'Конвертация ЕГРЮЛ', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_EGRL_86N', NAME = 'Конвертация ЕГРЮЛ', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_EGRL_86N'
GO
EXEC X_SET_PROP 'REPORT_EGRL_86N', 'INIT_OBJECT_METHOD', 'rn_convert_egrl()'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORT_EGRL_86N', 'Свод-КС', 63,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Загрузить из ЕГРЮЛ (XML из налоговой)"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '86n_NAV_IMPORT')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_EGRL_86N')

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 = '86n_NAV_IMPORT'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'RO_IMPORT_EGRL_86n'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'RO_IMPORT_EGRL_86n', 'Загрузить из ЕГРЮЛ (XML из налоговой)', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: История наименований КБК******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RO_KBK_HIST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RO_KBK_HIST')
	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 = 'RO_KBK_HIST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RO_KBK_HIST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RO_KBK_HIST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RO_KBK_HIST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_KBK_HIST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_KBK_HIST', 'История наименований КБК', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_VIEW'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_KBK_HIST', NAME = 'История наименований КБК', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_VIEW'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='RO_KBK_HIST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='FIELD_DH_CHECKED_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'FIELD_DH_CHECKED_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'FIELD_DH_CHECKED_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='FIELD_DH_CHECKED_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KBK_LINK_UP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KBK_LINK_UP', 'Ссылка на КБК', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KBK_LINK_UP', NAME = 'Ссылка на КБК', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KBK_LINK_UP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KBK_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KBK_NAME', 'Краткое наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KBK_NAME', NAME = 'Краткое наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KBK_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KBK_FULL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KBK_FULL_NAME', 'Полное наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KBK_FULL_NAME', NAME = 'Полное наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KBK_FULL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KBK_DATE_BEGIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KBK_DATE_BEGIN', 'Действует с ..', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KBK_DATE_BEGIN', NAME = 'Действует с ..', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KBK_DATE_BEGIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KBK_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KBK_DATE_END', 'Действует по ..', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KBK_DATE_END', NAME = 'Действует по ..', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_KBK_HIST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KBK_DATE_END'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'TITLE', 'История наименований КБК'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'INIT_OBJECT_METHOD', 'X_SPISOK("RO_KBK_HIST")'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'SAVE_OBJECT_METHOD', 'xd_department_hist_save(oForm)'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'CLOSE_CODE', 'LINK_UP'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''RO_KBK_HIST'')'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''RO_KBK_HIST'')'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'SERVER_TABLE_NAME', 'REPORT_KBK_HIST'
GO
EXEC X_SET_PROP 'RO_KBK_HIST', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'FIELD_DH_CHECKED_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'FIELD_DH_CHECKED_1', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'FIELD_DH_CHECKED_1', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'FIELD_DH_CHECKED_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'KBK_LINK_UP', 'CONTROLSOURCE', 'm.cAlias+".LINK_UP"'
GO
EXEC X_SET_PROP 'KBK_LINK_UP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KBK_LINK_UP', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'KBK_LINK_UP', 'SHORT_CODE_OBJ', 'LINK_UP'
GO
EXEC X_SET_PROP 'KBK_LINK_UP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".LINK_UP"'
GO
EXEC X_SET_PROP 'KBK_NAME', 'TITLE', 'Краткое наименование'
GO
EXEC X_SET_PROP 'KBK_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'KBK_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'KBK_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KBK_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KBK_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'KBK_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'KBK_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'KBK_NAME', 'CONTROL_NAME_EDIT', 'AtxtNAME'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'TITLE', 'Полное наименование'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'CONTROLSOURCE', 'm.cAlias+".LONG_NAME"'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(8000)'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'SHORT_CODE_OBJ', 'LONG_NAME'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".LONG_NAME"'
GO
EXEC X_SET_PROP 'KBK_FULL_NAME', 'CONTROL_NAME_EDIT', 'AtxtFULL_NAME'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'TITLE', 'Действует с ..'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'CONTROLSOURCE', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'SHORT_CODE_OBJ', 'DATE_BEGIN'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_BEGIN"'
GO
EXEC X_SET_PROP 'KBK_DATE_BEGIN', 'CONTROL_NAME_EDIT', 'datDate1'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'TITLE', 'Действует по ..'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'CONTROLSOURCE', 'm.cAlias+".DATE_END"'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'SHORT_CODE_OBJ', 'DATE_END'
GO
EXEC X_SET_PROP 'KBK_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_END"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
EXEC X_SET_PROP 'REPORTS_ATR_RRO_TYPE', 'DEFAULT_VALUE', 'Уточненный'
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RT_CALC_0503125M_ITOG_2011]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
	DROP PROCEDURE dbo.[RT_CALC_0503125M_ITOG_2011]
GO

/* © Кейсистемс (Keysystems), 2010 Процедура формирования строк и значений формы 0503125 */

CREATE PROCEDURE dbo.RT_CALC_0503125M_ITOG_2011
	@Void int,--@table int,
	@LSF int
AS

if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#res]')) begin
	select 0
	return
end

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
		@cSource char(1),
		@cSinth char(3),
		@cAnalit char(2),
		@cSGU char(3),
		@iLinkAccount int,
		@dBeginDate datetime,
		@dEndDate datetime,
		@iThisDep int,
		@iCorrDep int,
		@i int,
		@j int,
		@jj int,
		@iLink_col int,
		@code_row varchar(50),
		@float_val numeric(20,4),
		@str_val varchar(250),
		@cVidForm varchar(250),
		@cVidFormCode int,
		@iLink_Table int,
		@code_form varchar(50)

declare @table2 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(8), KBK varchar(50), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(9), dnd tinyint, link varchar(254), key_prov int, tabsource tinyint)

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ

set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
set @cVidFormCode = -1
select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

select @code_form = rtrim(code) from dbo.report_forms where link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF)

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dBeginDate = Begin_Date from dbo.report_saved_forms where link_saved_form = @LSF
-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate - (datepart(dd,@dBeginDate)) end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')
set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

set @j = 0
declare @table tinyint
set @table = 1
while @table !> 3 begin
	select @iLink_Table = link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table
	if @table in (1,3) begin
		insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
		select
			coalesce(rd1.Str_Val,''),
			substring(coalesce(rd2.Str_Val,''),1,3),
			substring(coalesce(rd3.Str_Val,''),1,8),
			substring(coalesce(rd4.Str_Val,''),1,2),
			case
            WHEN  right(rtrim(@cAccount),8) in ('30406000') 
            THEN '00000000000000000' 
				when @table = 1 and right(rtrim(@cAccount),8) in ('20551560','20551660')
				then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),14)+'0000000000',14)
				when @table = 1 and right(rtrim(@cAccount),8) in ('40110180','40110151','40120251','20651560','20651660')
				then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
				when @table = 1 and right(rtrim(@cAccount),8) not in ('40110180','40110151','40120251','20551560','20551660','20651560','20651660')
				then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),3)+'00000000000000',14)
				when @table = 3 and right(rtrim(@cAccount),8) in ('30111000','30131000','30141000','30151000','30121000')
				then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),14)+'00000000000000',14)
				when @table = 3 and right(rtrim(@cAccount),8) in ('30111810','30131810', '30111710')
				then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
				else right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),4)+'00000000000000',14)
			end,
			case WHEN right(rtrim(@cAccount),8) in ('30406000')
               THEN CASE WHEN substring(coalesce(rd9.Str_Val,''),2,1) IN ('1', '2') AND substring(coalesce(rd9.Str_Val,''),2,3) <> '104'
                     THEN case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
                           THEN LEFT(@cAccount,6) + '730'
                           ELSE LEFT(@cAccount,6) + '830' END
                     ELSE case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
                           THEN LEFT(@cAccount,6) + '830'
                           ELSE LEFT(@cAccount,6) + '730' END END
                     
               ELSE @cAccount
         END,
			isnull(rd7.Float_Val,0.00),
			isnull(rd8.Float_Val,0.00),
			substring(coalesce(rd9.Str_Val,''),1,9),
			case when cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) end,
			srows.Code_Row,
			null,
			@table
		from (
				select Code_Row from #report_dinamics
				where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
				group by Code_Row
			 ) as srows
		left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
	end
	else begin
		insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
		select
			coalesce(rd1.Str_Val,''),
			substring(coalesce(rd2.Str_Val,''),1,3),
			substring(coalesce(rd3.Str_Val,''),1,8),
			substring(coalesce(rd4.Str_Val,''),1,2),
			--right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) + '0000000000',
			right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) +
				case
					when (  (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151') or
							(@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') or
							(@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or
							(@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or
							(@cSinth = '207' and @cAnalit = '31' and @cSGU = '540') or
							(@cSinth = '207' and @cAnalit = '21' and @cSGU = '540') or
							(@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('710','810')) or
							(@cSinth = '302' and @cAnalit = '51' and @cSGU = '830'))
					then right('0000000'+rtrim(coalesce(rd7.Str_Val,'')),7) + '000'
					else '0000000000'
				end,
			case WHEN right(rtrim(@cAccount),8) in ('30406000')
               THEN CASE WHEN substring(coalesce(rd9.Str_Val,''),2,1) IN ('1', '2') AND substring(coalesce(rd9.Str_Val,''),2,3) <> '104'
                     THEN case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
                           THEN LEFT(@cAccount,6) + '730'
                           ELSE LEFT(@cAccount,6) + '830' END
                     ELSE case when substring(coalesce(rd9.Str_Val,''),7,3) IN (SELECT code FROM dbo.[KOSGU] k WHERE k.[DB_KR] = 0)
                           THEN LEFT(@cAccount,6) + '830'
                           ELSE LEFT(@cAccount,6) + '730' END END
                     
               ELSE @cAccount
         END,
			isnull(rd9.Float_Val,0.00),
			isnull(rd10.Float_Val,0.00),
			substring(coalesce(rd11.Str_Val,''),1,9),
			case when cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) end,
			srows.Code_Row,
			null,
			@table
		from (
				select Code_Row from #report_dinamics
				where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
				group by Code_Row
			 ) as srows
		left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd11 on rd11.link_sf = @LSF and rd11.Code_Row = srows.Code_Row and 11 = (select Orders from dbo.report_coloumns where link_col = rd11.link_col) and rd11.link_col = (select link_col from dbo.report_coloumns where Orders = 11 and Link_Table = @iLink_Table)
		left join #report_dinamics as rd12 on rd12.link_sf = @LSF and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12 and Link_Table = @iLink_Table)
	end
	set @table = @table + 1
end
update @table2 set link = cast(nn as varchar(10)), key_prov = nn -- для уникальности записей собраных с трёх таблиц. Ибо пользователю доверять нельзя!

update @table2  -- устанавливаем признак Денежные/Неденежные рассчёты | неденежные считаем все с СГУ 310,320,330,340 и сотые корреспондирующие счета
set dnd = case
			when dnd not in (1,0)
			then
				(case
					when
						right(left(korr_acc,6),5) in ('21002','30405') or
						right(korr_acc,3) in ('510','610')
					then 1 -- денежные рассчёты
					else 0 -- не денежные рассчёты
				 end)
			else dnd
		  end

select @j = count(*) from @table2

if (@j > 0)begin -- если кол-во полученных строк больше нуля, то...
	-- формирование итоговых строчек для 304.04 счёта
	--select * from @table2
	-- 30404000 ####################################################################################################

	if (@cSinth = '304' and (@cAnalit = '04' OR @cAnalit = '06') and @cSGU = '000') begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,link)
		select KBK,Code_Acc,coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
		group by KBK,Code_Acc
		-- итоговые по неденежным
		insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
		select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,summa_kr,link)
			select coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
		select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,summa_kr,link)
			select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,summa_kr,link)
			select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 40120241 ####################################################################################################

	-- формирование итоговых строчек для счёта 40120241
	if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '241'/*@cVidFormCode = 2*/)begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (ppp,KBK,Code_Acc,summa_db,link)
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
		group by ppp,KBK,Code_Acc
		-- итоговые по неденежным
		insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by ppp,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by ppp,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 40110180 ####################################################################################################

	-- формирование итоговых строчек для счёта 40110180
	if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '180' /*and @cVidFormCode = 3*/)begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (ppp,KBK,Code_Acc,summa_kr,link)
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
		group by ppp,KBK,Code_Acc
		-- итоговые по неденежным
		insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
		--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_db),0)) > 0.0 then -coalesce(SUM(summa_db),0) else coalesce(SUM(summa_kr),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by ppp,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by ppp,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 20731540 ####################################################################################################

	-- формирование итоговых строчек для счётов 20702540
	if (@cSinth = '207' and @cAnalit in ('11','21','31') and @cSGU = '540') begin
		-- итоговые. в том числе по номеру (коду) счета
		/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
		select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by el_bud,okato,Code_Acc*/
				insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
		select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by ppp, el_bud,okato,Code_Acc
		-- итоговые по неденежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
				where dnd = 1
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 40120251 ####################################################################################################

	if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') begin
		-- итоговые. в том числе по номеру (коду) счета
		/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
		select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by el_bud,okato,Code_Acc*/
		if @code_form like '425_' begin
			insert into @table2 (/*ppp,*/el_bud,okato,Code_Acc,summa_db,link)
			select /*ppp,*/el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by /*ppp, */el_bud,okato,Code_Acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
			select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by ppp,el_bud,okato,Code_Acc
		end
		-- итоговые по неденежным
		--insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from 		
				(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 1
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from 		
				(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0 and tabsource = 3
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from 		
				(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
				where dnd = 1 and tabsource = 1
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from 		
				(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
				where dnd = 1 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1 and tabsource = 3
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
						where dnd = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 20651560(660) ####################################################################################################

	if (@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660'))begin
		-- итоговые. в том числе по номеру (коду) счета
		if @code_form like '425_' begin
			insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
			select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by el_bud,okato,Code_Acc
		end
		else begin
			insert into @table2 (ppp, el_bud,okato,Code_Acc,summa_db,link)
			select ppp, el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by ppp, el_bud,okato,Code_Acc
		end
		-- итоговые по неденежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
		from
			(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
			where dnd = 0 and tabsource = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
		group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0 and tabsource <> 1
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr) ,0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
				where dnd = 1 and tabsource = 1
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1 and tabsource <> 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 30212830 ####################################################################################################

	if (@cSinth = '302' and @cAnalit = '51' and @cSGU = '830')begin
	-- итоговые. в том числе по номеру (коду) счета
		if @code_form like '425_' begin
			insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
			select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by el_bud,okato,Code_Acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
			select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by ppp,el_bud,okato,Code_Acc
		end
		-- итоговые по неденежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
		--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from 		
				(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
				where dnd = 1 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1 and tabsource <> 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 20551000,20651000,20731000 ####################################################################################################

	if (
		(@cSinth = '205' and @cAnalit = '51' and @cSGU = '000' /*and @cVidFormCode = 9*/)-- or @cVidFormCode = 11)) or
		or (@cSinth = '206' and @cAnalit = '51' and @cSGU = '000'/*and @cVidFormCode = 9*/)-- or @cVidFormCode = 5)) or
		or (@cSinth = '207' and @cAnalit = '31' and @cSGU = '000'/*and @cVidFormCode = 9*/)
		or (@cSinth = '207' and @cAnalit = '21' and @cSGU = '000')
		or (@cSinth = '207' and @cAnalit = '11' and @cSGU = '000'))begin-- or @cVidFormCode = 6 or @cVidFormCode = 13)))begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
		select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by ppp,el_bud,okato,Code_Acc
		-- общая итоговая строчка
		if exists(select * from @table2 where right(link,2) = 'ИП') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where right(link,2) = 'ИП'
		end
	end

	-- 301X1000 ####################################################################################################
	if (@cSinth = '301' and @cAnalit in ('11','21','31','41') and @cSGU = '000') or
		(@cSinth = '302' and @cAnalit = '51' and @cSGU = '000') begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by ppp,el_bud,okato,KBK,Code_Acc
		-- общая итоговая строчка
		if exists(select * from @table2 where right(link,2) = 'ИП') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where right(link,2) = 'ИП'
		end
	end

	-- 40110151 ####################################################################################################
	-- формирование итоговых строчек для счётов 40101151
	if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151' /*and @cVidFormCode = 10*/) begin
		--		-- сначала извращаемся над кбк в соответствии с письмом от 19.12.2008
		--		update @table2
		--		set KBK = case when tabsource = 1 then left(KBK,6)+'00000000000' else KBK end
		-- итоговые. в том числе по номеру (коду) счета
		if @code_form like '425_' begin
			insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
			select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by el_bud,okato,Code_Acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
			select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by ppp,el_bud,okato,Code_Acc
		end
		-- итоговые по неденежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 1
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
						where dnd = 0 and tabsource = 3
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end

		-- подитоговые для денежных
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
		from
			(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
			where dnd = 1 and tabsource = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
		group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
		from
			(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
			where dnd = 1 and tabsource = 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
		group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
				where dnd = 1 and tabsource = 3
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 20551560(660) ####################################################################################################

	if (@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) begin
		-- итоговые. в том числе по номеру (коду) счета
		if @code_form like '425_' begin
			insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
			select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by el_bud,okato,Code_Acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
			select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
			group by ppp,el_bud,okato,Code_Acc
		end
		-- итоговые по неденежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 1
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0 and tabsource = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end

		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
		from
			(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
			where dnd = 0 and tabsource = 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
		group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0 and tabsource = 3
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 20731640,20711640 ####################################################################################################

	-- формирование итоговых строчек для счётов 20702640
	if ((@cSinth = '207' and @cAnalit = '31' and @cSGU = '640') or
		(@cSinth = '207' and @cAnalit = '11' and @cSGU = '640'))begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
		select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by ppp,el_bud,okato,Code_Acc
		-- итоговые по неденежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end


	-- 30111810 ####################################################################################################
	-- формирование итоговых строчек для счётов 30101710
	if (@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('810')) begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
		select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by el_bud,okato,Code_Acc
		-- итоговые по неденежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0 and tabsource <> 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
						select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
						from
							(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
							where dnd = 1 and tabsource = 2
							group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
						group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1 and tabsource <> 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 30111710 ####################################################################################################
	-- формирование итоговых строчек для счётов 30101710
	if (@cSinth = '301' and @cAnalit in ('11','21','31') and @cSGU in ('710')) begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
		select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
		group by el_bud,okato,Code_Acc
		-- итоговые по неденежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
			from
				(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
				where dnd = 0 and tabsource = 2
				group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
			group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0 and tabsource <> 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
			where dnd = 0
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		if @code_form like '425_' begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
						select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
						from
							(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
							where dnd = 1 and tabsource = 2
							group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
						group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1 and tabsource <> 2
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

		end
		else begin
			insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
			select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
			where dnd = 1
			group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
		end
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- формирование итоговых строчек для счётов 021100560, 021200560
	if ((@cSinth = '211' or @cSinth = '212') and @cAnalit = '00' and (@cSGU = '560' or @cSGU = '660') /*and @cVidFormCode = 15*/)begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (okato,Code_Acc,summa_db,link)
		select okato, Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
		group by okato, Code_Acc
		-- итоговые по неденежным
		insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
		select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
		select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_db,link)
			select coalesce(SUM(summa_db),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end

	-- 30800730,30900730,30800830,30900830 ####################################################################################################

	-- формирование итоговых строчек для счётов 030800730 и 030900730
	if ((@cSinth = '308' or @cSinth = '309') and @cAnalit = '00' and (@cSGU = '730' or @cSGU = '830') /*and @cVidFormCode = 16*/)begin
		-- итоговые. в том числе по номеру (коду) счета
		insert into @table2 (okato,Code_Acc,summa_kr,link)
		select okato, Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
		group by okato, Code_Acc
		-- итоговые по неденежным
		insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
		where dnd = 0
		group by okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым неденежным
		if exists(select * from @table2 where right(link,2) = 'ИН') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
			where right(link,2) = 'ИН'
		end
		-- итоговые по денежным
		insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
		select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
		where dnd = 1
		group by okato,KBK,Code_Acc,korr_acc
		-- итоговая строчка суммы по итоговым денежным
		if exists(select * from @table2 where right(link,2) = 'ИД') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
			where right(link,2) = 'ИД'
		end
		-- общая итоговая строчка
		if exists(select * from @table2 where left(link,5) = 'итог_') begin
			insert into @table2 (summa_kr,link)
			select coalesce(SUM(summa_kr),0),'Итого' from @table2
			where left(link,5) = 'итог_'
		end
	end
end

delete from @table2 where right(link,1) like '[0-9]'
----------------------------------------- Делаем кодовое значение более коротким (на базе nn)
select @j = MIN(nn) from @table2

update @table2
set link = rtrim(cast((nn - @j) as varchar)) + right(link,2)
where right(link,2) in ('ИД','ИН')
-----------------------------------------
if not exists(select * from @table2 where right(link,2) = 'ИД')
insert into @table2 (link) values ('ИД')

if not exists(select * from @table2 where right(link,2) = 'ИН')
insert into @table2 (link) values ('ИН')

if not exists(select * from @table2 where rtrim(link) = 'итог_денежные_рассчёты')
insert into @table2 (link) values ('итог_денежные_рассчёты')

if not exists(select * from @table2 where rtrim(link) = 'итог_неденежные_рассчёты')
insert into @table2 (link) values ('итог_неденежные_рассчёты')

select @j = MIN(nn) from @table2
select @jj = MAX(nn) from @table2

delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги
delete from #report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги

while @j <= @jj begin
	set @i = 1
		while @i < 9 begin
			select @iLink_col = link_col from dbo.report_coloumns where Orders = @i and Link_Table = (select link_table from dbo.report_tables where Orders = 4/*итоги*/ and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF))
			select
			@code_row = rtrim(link),
			@float_val =
			(case when @i in (1,2,3,4,5,8) then 0.0000
			when @i = 6 then coalesce(summa_db,0.0000)
			when @i = 7 then coalesce(summa_kr,0.0000)
			end),
			@str_val =
			(case when @i in (6,7) then ''
			when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
			when @i = 2 then cast(coalesce(ppp,'') as varchar (250))
			when @i = 3 then cast(coalesce(okato,'') as varchar (250))
			when @i = 4 then cast(coalesce(el_bud,'') as varchar (250))
			when @i = 5 then cast(coalesce(KBK,'')+coalesce(Code_acc,'') as varchar (250))
			when @i = 8 then cast(coalesce(korr_acc,'') as varchar (250))
			end)
			from @table2
			where nn = @j

			if @code_row in ('ИД','ИН','итог_денежные_рассчёты','итог_неденежные_рассчёты') and @float_val = 0.0
			insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val) values (@LSF,@iLink_col,@code_row,@float_val,@str_val)

			insert into #report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
			values (@LSF,@iLink_col,@code_row,@float_val,@str_val)


			set @i = @i + 1
		end
	set @j = @j + 1
end
----------------------------------------------------------------------------
select 0

GO
GRANT EXECUTE ON dbo.[RT_CALC_0503125M_ITOG_2011] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
GO




GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_04_03_2011',0,'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_04_03_2011',@link_self,'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_110_04_03_2011')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_110_04_03_2011')
delete report_kbk where code_form= 'R_SPR_110_04_03_2011'
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 '340110110',0,'R_SPR_110_04_03_2011',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110120',0,'R_SPR_110_04_03_2011',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110130',0,'R_SPR_110_04_03_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110140',0,'R_SPR_110_04_03_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110151',0,'R_SPR_110_04_03_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110152',0,'R_SPR_110_04_03_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110153',0,'R_SPR_110_04_03_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110160',0,'R_SPR_110_04_03_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110171',0,'R_SPR_110_04_03_2011',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110172',0,'R_SPR_110_04_03_2011',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110173',0,'R_SPR_110_04_03_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110180',0,'R_SPR_110_04_03_2011',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120211',0,'R_SPR_110_04_03_2011',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120212',0,'R_SPR_110_04_03_2011',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120213',0,'R_SPR_110_04_03_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120221',0,'R_SPR_110_04_03_2011',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120222',0,'R_SPR_110_04_03_2011',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120223',0,'R_SPR_110_04_03_2011',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120224',0,'R_SPR_110_04_03_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120225',0,'R_SPR_110_04_03_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120226',0,'R_SPR_110_04_03_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120231',0,'R_SPR_110_04_03_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120232',0,'R_SPR_110_04_03_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120241',0,'R_SPR_110_04_03_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120242',0,'R_SPR_110_04_03_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120251',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120252',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120253',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120261',0,'R_SPR_110_04_03_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120262',0,'R_SPR_110_04_03_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120263',0,'R_SPR_110_04_03_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120271',0,'R_SPR_110_04_03_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120272',0,'R_SPR_110_04_03_2011',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120273',0,'R_SPR_110_04_03_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120290',0,'R_SPR_110_04_03_2011',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_110_04_03_2011'

GO


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_KSBU_125',0,'Справочник счетов бюджетного учета для формы 0503125 (атрибут)','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_KSBU_125',@link_self,'Справочник счетов бюджетного учета для формы 0503125 (атрибут)','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_KSBU_125')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_KSBU_125')
delete report_kbk where code_form= 'R_SPR_KSBU_125'
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 '120551000',0,'R_SPR_KSBU_125',1,'Расчеты по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120551660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по поступлениям от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651000',0,'R_SPR_KSBU_125',1,'Расчеты по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по авансовым перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120651660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по выданным авансам по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по предоставленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120711640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по представленным бюджетным кредитам',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации в рамках  целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120721640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации в рамках  целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731540',0,'R_SPR_KSBU_125',1,'Увеличение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '120731640',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности бюджетов бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121100660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '121200660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130111810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рублях',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130121810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по привлеченным бюджетным кредитам в рамках целевых иностранных кредитов (заимствований)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131000',0,'R_SPR_KSBU_125',1,'Расчеты с бюджетами бюджетной системы Российской Федерации по государственным (муниципальным гарантиям)',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131710',0,'R_SPR_KSBU_125',1,'Увеличение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130131810',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251000',0,'R_SPR_KSBU_125',1,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130251830',0,'R_SPR_KSBU_125',1,'Уменьшение задолженности перед бюджетами бюджетной системы Российской Федерации по государственным (муниципальным) гарантиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130404000',0,'R_SPR_KSBU_125',1,'Внутриведомственные расчеты',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130406000',0,'R_SPR_KSBU_125',1,'Расчеты с прочими кредиторами',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130800830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '130900830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям.',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110151',0,'R_SPR_KSBU_125',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110180',0,'R_SPR_KSBU_125',1,'Прочие доходы',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120241',0,'R_SPR_KSBU_125',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120251',0,'R_SPR_KSBU_125',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221100660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200560',0,'R_SPR_KSBU_125',1,'Увеличение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '221200660',0,'R_SPR_KSBU_125',1,'Уменьшение дебиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230404000',0,'R_SPR_KSBU_125',1,'Внутриведомственные расчеты',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230406000',0,'R_SPR_KSBU_125',1,'Расчеты с прочими кредиторами',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230800830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по поступлениям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900730',0,'R_SPR_KSBU_125',1,'Увеличение кредиторской задолженности по внутренним расчетам по выбытиям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230900830',0,'R_SPR_KSBU_125',1,'Уменьшение кредиторской задолженности по внутренним расчетам по выбытиям.',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110180',0,'R_SPR_KSBU_125',1,'Прочие доходы',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120241',0,'R_SPR_KSBU_125',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730406000',0,'R_SPR_KSBU_125',1,'Расчеты с прочими кредиторами',0,'',0,'','', NULL,NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_KSBU_125'

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='ARCHE_OPT13'

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_ARCHE_OPT13]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ARCHE_OPT13]

CREATE TABLE  dbo._UPD_OPT_ARCHE_OPT13 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_ARCHE_OPT13 (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 = 'ARCHE_OPT13')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ARCHE_OPT13')
	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 = 'ARCHE_OPT13')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ARCHE_OPT13')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ARCHE_OPT13'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ARCHE_OPT13')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ARCHE_OPT13')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ARCHE_OPT13', 'Не начисять суммы за счёт ФСС', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_ARCHE_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ARCHE_OPT13', NAME = 'Не начисять суммы за счёт ФСС', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_ARCHE_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ARCHE_OPT13'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'TITLE', 'Не начисять суммы за счёт ФСС'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'STORAGE', 'SK'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'CONTROL_NAME_EDIT', 'ACheckBox13'
GO
EXEC X_SET_PROP 'ARCHE_OPT13', 'COMMENTARY', 'Не начисять суммы за счёт ФСС в соответствии с постановлением Правительства №294 от 21.04.2011 о новом порядке выплаты пособий по нетрудоспособности.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ARCHE_OPT13' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_ARCHE_OPT13] WHERE CODE = 'ARCHE_OPT13')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ARCHE_OPT13'), SID, VALUE FROM [dbo].[_UPD_OPT_ARCHE_OPT13] WHERE CODE = 'ARCHE_OPT13'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'ARCHE_OPT13'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_ARCHE_OPT13]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ARCHE_OPT13]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'ARCHE_OPT13', 'Зарплата-КС', 63,0
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='DELO_OPTIONS1_OPT4'

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_DELO_OPTIONS1_OPT4]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DELO_OPTIONS1_OPT4]

CREATE TABLE  dbo._UPD_OPT_DELO_OPTIONS1_OPT4 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_DELO_OPTIONS1_OPT4 (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 = 'DELO_OPTIONS1_OPT4')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DELO_OPTIONS1_OPT4')
	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 = 'DELO_OPTIONS1_OPT4')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DELO_OPTIONS1_OPT4')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DELO_OPTIONS1_OPT4'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DELO_OPTIONS1_OPT4')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DELO_OPTIONS1_OPT4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DELO_OPTIONS1_OPT4', 'Вид документа, с которым нужно сохранять входящие документы СЭВ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DELO_OPTIONS1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DELO_OPTIONS1_OPT4', NAME = 'Вид документа, с которым нужно сохранять входящие документы СЭВ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DELO_OPTIONS1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DELO_OPTIONS1_OPT4'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'TITLE', 'Вид документа, с которым нужно сохранять входящие документы СЭВ'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("WF_DICTIONARY_DOCVID", oForm.cSel_Spr_Alias, "LINK,CODE, NAME", "AN_OPT4,AN_OPT4C,AN_OPT4N", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'SHORT_CODE_OBJ', 'AN_OPT4'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'CONTROL_NAME_EDIT', 'Asel_spr4'
GO
EXEC X_SET_PROP 'DELO_OPTIONS1_OPT4', 'COMMENTARY', 'Вид документа, с которым нужно сохранять входящие документы СЭВ.
Если параметр не указан, то сохраняется с видом, указанным во входящем документе.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'DELO_OPTIONS1_OPT4' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DELO_OPTIONS1_OPT4] WHERE CODE = 'DELO_OPTIONS1_OPT4')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'DELO_OPTIONS1_OPT4'), SID, VALUE FROM [dbo].[_UPD_OPT_DELO_OPTIONS1_OPT4] WHERE CODE = 'DELO_OPTIONS1_OPT4'
GO

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_DELO_OPTIONS1_OPT4]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DELO_OPTIONS1_OPT4]

GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DELO_OPTIONS1_OPT4', 'Дело-КС - ОКО', 63,0
GO

GO
EXEC X_SET_PROP 'COLUMN_COD_DED_T_INC', 'VISIBLE', '15'
GO

EXEC X_SET_PROP 'COLUMN_CODE_T_INC_1', 'VISIBLE', '0'
GO


GO
/****** Объект: Начисления по уходу за ребёнком******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_CHILD')
	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_CHILD')
	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_CHILD')
	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_CHILD')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_CHILD'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_CHILD')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_CHILD', 'Начисления по уходу за ребёнком', 29, (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_CHILD', NAME = 'Начисления по уходу за ребёнком', ORDERS = '29', 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_CHILD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_FLAG_JC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_FLAG_JC', 'Признак проведения в журнале расчетов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_FLAG_JC', NAME = 'Признак проведения в журнале расчетов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_FLAG_JC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_NUMBER', 'Номер документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_NUMBER', NAME = 'Номер документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_DATE', 'Дата документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_DATE', NAME = 'Дата документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_CODE_SFIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_CODE_SFIN', 'Источник', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_CODE_SFIN', NAME = 'Источник', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_CODE_SFIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_NAME_SFIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_NAME_SFIN', 'Наименование источника', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_NAME_SFIN', NAME = 'Наименование источника', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_NAME_SFIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_MONTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_MONTH', 'Месяц периода расчета', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_MONTH', NAME = 'Месяц периода расчета', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_MONTH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_YEAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_YEAR', 'Год периода расчета', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_YEAR', NAME = 'Год периода расчета', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_YEAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_COMMENTARY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_COMMENTARY', 'Комментарий', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_COMMENTARY', NAME = 'Комментарий', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_COMMENTARY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_SUMMA', 'Сумма', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_SUMMA', NAME = 'Сумма', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_ISREGION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_ISREGION', 'Начислять районный коэффициент', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_ISREGION', NAME = 'Начислять районный коэффициент', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_ISREGION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_CODE_PAY1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_CODE_PAY1', 'Код начисления для районного коэффициента', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_CODE_PAY1', NAME = 'Код начисления для районного коэффициента', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_CODE_PAY1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_NAME_PAY1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_NAME_PAY1', 'Наименование начисления для районного коэффициента', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_NAME_PAY1', NAME = 'Наименование начисления для районного коэффициента', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_NAME_PAY1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_ISNORTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_ISNORTH', 'Начислять северный коэффициент', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_ISNORTH', NAME = 'Начислять северный коэффициент', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_ISNORTH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_CODE_PAY2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_CODE_PAY2', 'Код начисления для северного коэффициента', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_CODE_PAY2', NAME = 'Код начисления для северного коэффициента', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_CODE_PAY2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_NAME_PAY2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_NAME_PAY2', 'Наименование начисления для северного коэффициента', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_NAME_PAY2', NAME = 'Наименование начисления для северного коэффициента', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_NAME_PAY2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_CHILD_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_CHILD_NAME_DEP', 'Организация', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_CHILD_NAME_DEP', NAME = 'Организация', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_CHILD_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_CHILD_TABLE', 'Начисление суммой таблица', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_ADD_CHILD_TABLE', NAME = 'Начисление суммой таблица', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_ADD_CHILD_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADD_CHILD_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADD_CHILD_OPTIONS', 'Настройки', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADD_CHILD_OPTIONS', NAME = 'Настройки', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADD_CHILD_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_ORDERS', 'Номер строки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_ORDERS', NAME = 'Номер строки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_ORDERS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_TAB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_TAB', 'Табельный номер', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_TAB', NAME = 'Табельный номер', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_TAB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_FIO', 'ФИО', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_FIO', NAME = 'ФИО', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_CODE_SFIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_CODE_SFIN', 'Источник', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_CODE_SFIN', NAME = 'Источник', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_CODE_SFIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_NAME_CALC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_NAME_CALC', 'Тип расчёта', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_NAME_CALC', NAME = 'Тип расчёта', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_NAME_CALC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_BASE_SUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_BASE_SUM', 'Баз.сумма', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_BASE_SUM', NAME = 'Баз.сумма', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_BASE_SUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_DAYS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_DAYS', 'Дни', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_DAYS', NAME = 'Дни', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_DAYS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_HOURS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_HOURS', 'Часы', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_HOURS', NAME = 'Часы', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_HOURS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_DAYS_NORM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_DAYS_NORM', 'Дни норм.', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_DAYS_NORM', NAME = 'Дни норм.', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_DAYS_NORM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_HOURS_NORM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_HOURS_NORM', 'Часы норм.', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_HOURS_NORM', NAME = 'Часы норм.', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_HOURS_NORM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_SUMMA_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_SUMMA_NEW', 'Начислить', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_SUMMA_NEW', NAME = 'Начислить', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_SUMMA_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_SUMMA_OLD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_SUMMA_OLD', 'Начислено', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_SUMMA_OLD', NAME = 'Начислено', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_SUMMA_OLD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_SUMMA', 'Сумма', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_SUMMA', NAME = 'Сумма', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_DATE_BEG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_DATE_BEG', 'Нач. периода', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_DATE_BEG', NAME = 'Нач. периода', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_DATE_BEG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_DATE_END', 'Кон. периода', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_DATE_END', NAME = 'Кон. периода', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_DATE_END'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_CODE_PAYS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_CODE_PAYS', 'Код начисления', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_CODE_PAYS', NAME = 'Код начисления', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_CODE_PAYS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_NAME_PAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_NAME_PAY', 'Наименование начисления', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_NAME_PAY', NAME = 'Наименование начисления', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_NAME_PAY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_REGION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_REGION', 'Район.%', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_REGION', NAME = 'Район.%', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_REGION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_REGSUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_REGSUM', 'Район.сумма', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_REGSUM', NAME = 'Район.сумма', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_REGSUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_NORTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_NORTH', 'Северн.%', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_NORTH', NAME = 'Северн.%', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_NORTH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ACHILD_TAB_NORTHSUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ACHILD_TAB_NORTHSUM', 'Северн.сумма', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ACHILD_TAB_NORTHSUM', NAME = 'Северн.сумма', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_CHILD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ACHILD_TAB_NORTHSUM'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'TITLE', 'Начисления по уходу за ребёнком'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'INIT_OBJECT_METHOD', 'S_SPISOK("DOCUMENTS_ADD_CHILD")'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOCUMENTS_ADD_CHILD", "SALARY_DELETE_SDOC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'SAVE_OBJECT_METHOD', 'sd_n_child_save(oForm)'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''sd_n_child'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'SELECT_RECORDS_METHOD', 'sa_select_document_list_zb1(''DOCUMENTS_ADD_CHILD'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''DOCUMENTS_ADD_CHILD'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'SERVER_TABLE_NAME', 'SDOC'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'OPTIONS_OBJECT_CODE', 'ADD_CHILD_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'HELP_TOPIC', '16'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'COMMENTARY', 'Начисления по уходу за ребёнком'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_FLAG_JC', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_FLAG_JC', 'CONTROLSOURCE', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_FLAG_JC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'TITLE', '№'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.numdate1.number'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NUMBER', 'COMMENTARY', 'Номер документа по порядку'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.numdate1.date'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_DATE', 'COMMENTARY', 'Дата расчета'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.ALIAS, ''LINK, CODE, NAME'', ''LINK_SFIN,CODE_SFIN,NAME_SFIN'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'CONTROLSOURCE', 'm.cAlias + ".CODE_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Asel_spr1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_SFIN', 'COMMENTARY', 'Источник финансирования'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'TITLE', 'Наименование источника'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'CONTROLSOURCE', 'm.cAlias + ".NAME_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Atextbox1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_SFIN', 'COMMENTARY', 'Источник финансирования'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'TITLE', 'Месяц'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'CONTROLSOURCE', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'TYPE_FIELD_DICT', 'NUMERIC(4,0)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Amonth1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_MONTH', 'COMMENTARY', 'Месяц периода расчета'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'TITLE', 'Год'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'CONTROLSOURCE', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'TYPE_FIELD_DICT', 'NUMERIC(10,0)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Ayear1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_YEAR', 'COMMENTARY', 'Год периода расчета'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Atextbox04'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_COMMENTARY', 'COMMENTARY', 'Комментарий к расчету'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'TITLE', 'Всего'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_SUMMA', 'CONTROL_NAME_EDIT', 'Atextbox07'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'TITLE', 'Начислять районный коэффициент'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'CONTROLSOURCE', 'm.cAlias + ".isREGION"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".isREGION"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.acheckbox1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISREGION', 'COMMENTARY', 'Начислять районный коэффициент'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'TITLE', 'Районный коэф.'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_PAY_SALARY'', oForm.ALIAS, ''LINK, CODE, NAME'', ''LINK_PAY1, CODE_PAY1, NAME_PAY1'', '''', '''', ''WAY_CALC = 5'', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY1"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY1"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY1', 'COMMENTARY', 'Код начисления для районного коэффициента'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'TITLE', 'Районный коэф.'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY1"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY1"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Atextbox2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY1', 'COMMENTARY', 'Наименование начисления для районного коэффициента'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'TITLE', 'Начислять северный коэффициент'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'CONTROLSOURCE', 'm.cAlias + ".isNORTH"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".isNORTH"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Acheckbox2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_ISNORTH', 'COMMENTARY', 'Начислять северный коэффициент'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'TITLE', 'Северный коэф.'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_PAY_SALARY'', oForm.ALIAS, ''LINK, CODE, NAME'', ''LINK_PAY2, CODE_PAY2, NAME_PAY2'', '''', '''', ''WAY_CALC = 5'', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY2"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY2"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Asel_spr4'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_CODE_PAY2', 'COMMENTARY', 'Код начисления для северного коэффициента'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'TITLE', 'Северный коэф.'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY2"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY2"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Atextbox5'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_PAY2', 'COMMENTARY', 'Наименование начисления для северного коэффициента'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_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 'DOC_ADD_CHILD_NAME_DEP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.cnt_dep.asel_spr01'
GO
EXEC X_SET_PROP 'DOC_ADD_CHILD_NAME_DEP', 'COMMENTARY', 'Наименование организации'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_CHILD_TABLE', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable, m.cAlias,''DOCUMENTS_ADD_CHILD_TABLE'',''*'')'
GO
EXEC X_SET_PROP 'ADD_CHILD_OPTIONS', 'TITLE', 'Настройки'
GO
EXEC X_SET_PROP 'ADD_CHILD_OPTIONS', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("SALARY_OPTIONS", "Общие настройки по зарплате")'
GO
EXEC X_SET_PROP 'ADD_CHILD_OPTIONS', 'COMMENTARY', 'Настройки устанавливают параметры для режима "Начисления суммой"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'TITLE', '№'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'CONTROLSOURCE', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'TITLE', 'Tаб.№'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 (''KU_EMPL_PLACING'', oForm.apageframe1.page2.bSpisok.bGrid1.RecordSource, ''LINK, TAB, NAME_EMPL,SUBDIV_NAME, POST_NAME'', ''LINK_EMPL, TAB, FIO,  NAME_SUBDIV, NAME_POST'', '''', '''',''DEP_LINK= '' + STR(EVALUATE(oFORM.ALIAS + ".LINK_DEP")), .T., 1, oForm, oObj)
'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'CONTROLSOURCE', 'm.cAlias + ".TAB"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'TYPE_FIELD_DICT', 'VARCHAR(5)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_TAB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAB"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_FIO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.apageframe1.page2.bSpisok.bGrid1.RecordSource, ''LINK, CODE'', ''LINK_SFIN,CODE_SFIN'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'CONTROLSOURCE', 'm.cAlias + ".CODE_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_SFIN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_SFIN"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'TITLE', 'Тип расчёта'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'CONTROLSOURCE', 'm.cAlias + ".NAME_CALC"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_CALC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_CALC"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'TITLE', 'Баз.сумма'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'CONTROLSOURCE', 'm.cAlias + ".BASE_SUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BASE_SUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_BASE_SUM', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'TITLE', 'Дни'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'CONTROLSOURCE', 'm.cAlias + ".DAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'TYPE_FIELD_DICT', 'NUMERIC(4,0)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'TITLE', 'Часы'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'CONTROLSOURCE', 'm.cAlias + ".HOURS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".HOURS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'TITLE', 'Дни норм.'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'ORDER_NUMBER', '7'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'CONTROLSOURCE', 'm.cAlias + ".DAYS_NORM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'TYPE_FIELD_DICT', 'NUMERIC(4,0)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DAYS_NORM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DAYS_NORM', 'INPUT_MASK', '9999'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'TITLE', 'Часы норм.'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'ORDER_NUMBER', '8'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'CONTROLSOURCE', 'm.cAlias + ".HOURS_NORM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".HOURS_NORM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_HOURS_NORM', 'INPUT_MASK', '99999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'TITLE', 'Начислить'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_NEW"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_NEW"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_NEW', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'TITLE', 'Начислено'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA_OLD', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_SUMMA', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'TITLE', 'Нач. периода'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'CONTROLSOURCE', 'm.cAlias + ".DATE_BEG"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_BEG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_BEG"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'TITLE', 'Кон. периода'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'CONTROLSOURCE', 'm.cAlias + ".DATE_END"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_END"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'TITLE', 'Код начисления'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_PAY_SALARY'', oForm.ALIAS, ''LINK, CODE, NAME'', ''LINK_PAYS, CODE_PAYS, NAME_PAYS'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Asel_spr03'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_CODE_PAYS', 'COMMENTARY', 'Код начисления'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'TITLE', 'Наименование начисления'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAYS"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NAME_PAY', 'COMMENTARY', 'Наименование начисления'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'TITLE', 'Район.%'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'CONTROLSOURCE', 'm.cAlias + ".REGION"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REGION"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGION', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'TITLE', 'Район.сумма'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'CONTROLSOURCE', 'm.cAlias + ".REGSUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REGSUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_REGSUM', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'TITLE', 'Северн.%'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'CONTROLSOURCE', 'm.cAlias + ".NORTH"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NORTH"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTH', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'TITLE', 'Северн.сумма'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'CONTROLSOURCE', 'm.cAlias + ".NORTHSUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NORTHSUM"'
GO
EXEC X_SET_PROP 'DOC_ACHILD_TAB_NORTHSUM', 'INPUT_MASK', '999 999 999.99'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_ADD_CHILD', 'Зарплата-КС', 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 = '4618')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_CHILD')

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 = '4618'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_DOC_ADD_CHILD'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_DOC_ADD_CHILD', 'Начисления по уходу за ребёнком', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Расчет отчислений в ФСС по травматизму******/


DECLARE @T TABLE (LINK INT, CODE VARCHAR(30), FLAG TINYINT)

/******--Запомнить настройки на базе пользователя ******/
INSERT @T (LINK, CODE, FLAG)
SELECT LINK, CODE, 1
FROM  dbo.S_OBJECTS SO WHERE CODE='DOCUMENTS_CLOSE_MONTH'

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_CLOSE_MONTH]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH]

CREATE TABLE  dbo._UPD_OPT_DOCUMENTS_CLOSE_MONTH (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_DOCUMENTS_CLOSE_MONTH (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_CLOSE_MONTH')
	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_CLOSE_MONTH')
	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_CLOSE_MONTH')
	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_CLOSE_MONTH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_CLOSE_MONTH', 'Расчет отчислений в ФСС по травматизму', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENT_SALARY_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_CLOSE_MONTH', NAME = 'Расчет отчислений в ФСС по травматизму', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENT_SALARY_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_CLOSE_MONTH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_CM', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_CM', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FLAG_J_C_DED_OTHER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FLAG_J_C_DED_OTHER', 'Признак проведения в журнале расчетов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_FLAG_J_C_DED_OTHER', NAME = 'Признак проведения в журнале расчетов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_FLAG_J_C_DED_OTHER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_CM', 'Номер документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_CM', NAME = 'Номер документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE_CM', 'Дата документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE_CM', NAME = 'Дата документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MONTH_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MONTH_CM', 'Месяц периода расчета', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MONTH_CM', NAME = 'Месяц периода расчета', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MONTH_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_YEAR_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_YEAR_CM', 'Год периода расчета', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_YEAR_CM', NAME = 'Год периода расчета', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_YEAR_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_PERIOD_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_PERIOD_CM', 'Дата (период)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_PERIOD_CM', NAME = 'Дата (период)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_PERIOD_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_ISUMMA_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_ISUMMA_CM', 'Итоговая сумма', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_ISUMMA_CM', NAME = 'Итоговая сумма', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_ISUMMA_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_RKO_DED_PR_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_RKO_DED_PR_1', 'Бух. документ', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_RKO_DED_PR_1', NAME = 'Бух. документ', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_RKO_DED_PR_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_COMMENTARY_CM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_COMMENTARY_CM', 'Комментарий', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_COMMENTARY_CM', NAME = 'Комментарий', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_COMMENTARY_CM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CLOSE_MONTH_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CLOSE_MONTH_NAME_DEP', 'Организация', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CLOSE_MONTH_NAME_DEP', NAME = 'Организация', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CLOSE_MONTH_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_CLOSE_MONTH_TABLE', 'Прочие отчисления таблица', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_CLOSE_MONTH_TABLE', NAME = 'Прочие отчисления таблица', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_CLOSE_MONTH_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO', 'Расшифровка скидки', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO', NAME = 'Расшифровка скидки', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO', 'Расшифровка вычета', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO', NAME = 'Расшифровка вычета', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESNTR_OPTIONS', 'Настройка отчисления по травматизму', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESNTR_OPTIONS', NAME = 'Настройка отчисления по травматизму', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_CLOSE_MONTH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESNTR_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_CM_T', 'Маркер', 1, (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_MARKER_CM_T', NAME = 'Маркер', ORDERS = '1', 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_MARKER_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_CM_T', 'Номер строки', 2, (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_NUMBER_CM_T', NAME = 'Номер строки', ORDERS = '2', 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_NUMBER_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_DED_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_DED_CM_T', 'Код отчисления', 3, (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_CODE_DED_CM_T', NAME = 'Код отчисления', ORDERS = '3', 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_CODE_DED_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_DED_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_DED_CM_T', 'Наименование отчисления', 4, (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_DED_CM_T', NAME = 'Наименование отчисления', ORDERS = '4', 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_DED_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_DED_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_DED_CM_T', 'Ссылка на отчисление', 5, (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_REF_DED_CM_T', NAME = 'Ссылка на отчисление', ORDERS = '5', 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_REF_DED_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR_CM_T', 'Источник', 6, (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_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
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_CM_TABLE_NAME_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_CM_TABLE_NAME_EKR', 'ЭКР', 7, (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 = 'DOC_CM_TABLE_NAME_EKR', NAME = 'ЭКР', ORDERS = '7', 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 ='DOC_CM_TABLE_NAME_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_VKR_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_VKR_CM_T', 'Ссылка на источник', 8, (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_LINK_VKR_CM_T', NAME = 'Ссылка на источник', ORDERS = '8', 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_LINK_VKR_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_BASE_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_BASE_CM_T', 'Базовая сумма', 9, (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_SUMMA_BASE_CM_T', NAME = 'Базовая сумма', ORDERS = '9', 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_SUMMA_BASE_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DED_OTHER_SKIDKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DED_OTHER_SKIDKA', 'Скидка', 10, (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 = 'DED_OTHER_SKIDKA', NAME = 'Скидка', ORDERS = '10', 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 ='DED_OTHER_SKIDKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DED_OTHER_VYCHET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DED_OTHER_VYCHET', 'Вычет', 11, (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 = 'DED_OTHER_VYCHET', NAME = 'Вычет', ORDERS = '11', 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 ='DED_OTHER_VYCHET'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PERCENT_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PERCENT_CM_T', 'Процент', 12, (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_PERCENT_CM_T', NAME = 'Процент', ORDERS = '12', 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_PERCENT_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_CM_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_CM_T', 'Сумма', 13, (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_SUMMA_CM_T', NAME = 'Сумма', ORDERS = '13', 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_SUMMA_CM_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESNTR_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESNTR_OPT1', 'Платежка - образец для перечисления взносов по травматизму', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESNTR_OPT1', NAME = 'Платежка - образец для перечисления взносов по травматизму', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESNTR_OPT1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESNTR_OPT2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESNTR_OPT2', 'Заявка на кассовый расход - образец для перечисления СВ по травматизму', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESNTR_OPT2', NAME = 'Заявка на кассовый расход - образец для перечисления СВ по травматизму', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESNTR_OPT2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS_OPT3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESNTR_OPTIONS_OPT3', 'Предоставлять скидки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESNTR_OPTIONS_OPT3', NAME = 'Предоставлять скидки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESNTR_OPTIONS_OPT3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS_OPT4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESNTR_OPTIONS_OPT4', 'Предоставлять вычеты', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESNTR_OPTIONS_OPT4', NAME = 'Предоставлять вычеты', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESNTR_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESNTR_OPTIONS_OPT4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_CM_T_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_CM_T_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_CM_T_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_CM_T_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO_CODE_INC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO_CODE_INC', 'Код дохода', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO_CODE_INC', NAME = 'Код дохода', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO_CODE_INC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO_FIO', 'Ф.И.О.', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO_FIO', NAME = 'Ф.И.О.', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO_CODE_S_FIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'Источник', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', NAME = 'Источник', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO_CODE_S_FIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO_CODE_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'ЭКР', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', NAME = 'ЭКР', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO_CODE_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'Сумма', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_SKIDKI_FIO_SUMMA', NAME = 'Сумма', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_SKIDKI_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_SKIDKI_FIO_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_CODE_DED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_CODE_DED', 'Код вычета', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_CODE_DED', NAME = 'Код вычета', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_CODE_DED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_FIO', 'Ф.И.О.', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_FIO', NAME = 'Ф.И.О.', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_CODE_S_FIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'Источник', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', NAME = 'Источник', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_CODE_S_FIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_CODE_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'ЭКР', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_CODE_EKR', NAME = 'ЭКР', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_CODE_EKR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SDOC_DOT_VYCHET_FIO_SUMMA', 'Сумма', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SDOC_DOT_VYCHET_FIO_SUMMA', NAME = 'Сумма', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SDOC_DOT_VYCHET_FIO'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SDOC_DOT_VYCHET_FIO_SUMMA'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'TITLE', 'Расчет отчислений в ФСС по травматизму'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'INIT_OBJECT_METHOD', 'S_SPISOK("DOCUMENTS_CLOSE_MONTH")'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOCUMENTS_CLOSE_MONTH", "SALARY_DELETE_SDOC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'SAVE_OBJECT_METHOD', 'sd_o_other_save(oForm)'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SD_O_OTHER'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'SELECT_RECORDS_METHOD', 'sa_select_document_list_zb1(''DOCUMENTS_DED_OTHER'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''DOCUMENTS_DED_OTHER'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'SERVER_TABLE_NAME', 'SDOC'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'OPTIONS_OBJECT_CODE', 'ESNTR_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'HELP_TOPIC', '35'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'COMMENTARY', 'Режим предназначен для расчета отчислений в Фонд травматизма. При входе в режим на экран выводится реестр сформированных отчислений. Каждую строку с записью можно скорректировать, нажав кнопку   Открыть. Заполняется новый документ по кнопке   Добавить. 
1.	Заполните обязательные поля, отмеченные цветом. Поля «Номер» и «Дата» документа запол-няются программой автоматически. Базовая сумма рассчитывается за указанный период рас-чета путем сложения  всех начислений, входящих в базу расчета данного отчисления. 
2.	Нажмите кнопку <ЗАПОЛНИТЬ >. Появятся две строки, содержащие следующие данные: код и наименование отчисления, базовая сумма, процент.  Для работников-инвалидов размер процентной ставки равен  0.12, для остальных работников – 0.2%.
3.	Нажмите кнопку < РАССЧИТАТЬ>.  При расчете учитываются суммы льгот для инвалидов, указанные в справочнике НАСТРОЙКА ПО ЗАРПЛАТЕ (закладка «Инвалиды»). Полученная сумма отразится в соответствующей графе.
4.	Нажмите кнопку <СОХРАНИТЬ>.
5.	Нажмите кнопку <ОПЕРАЦИИ>, для того чтобы удержания попали в «Реестр операций по заработной плате» и могли быть использованы для других расчетов.
6.	Нажмите кнопку «Бух. Док.», чтобы сформировать или открыть сформированные платежные поручения на перечисление ЕСН по данному расчету.
Для успешного формирования платежных поручений и проводок, следует установить кредитовые счета проводок в справочнике отчислений. Дополнительно, в настройках данного режима должна быть установлена настройка «Платежка - образец для перечисления ЕСН».
'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_OTHER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_OTHER', 'CONTROLSOURCE', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_J_C_DED_OTHER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'CONTROL_NAME_EDIT', 'ATxtNomDok'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM', 'COMMENTARY', 'Номер документа по порядку'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_CM', 'CONTROL_NAME_EDIT', 'Aseldate02'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'TITLE', 'Месяц'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'CONTROLSOURCE', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'TYPE_FIELD_DICT', 'NUMERIC(2,0)'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_CM', 'CONTROL_NAME_EDIT', 'Acmbmonth05'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'TITLE', 'Год'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'CONTROLSOURCE', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'TYPE_FIELD_DICT', 'NUMERIC(4,0)'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_CM', 'CONTROL_NAME_EDIT', 'AspinnerYear06'
GO
EXEC X_SET_PROP 'COLUMN_REF_PERIOD_CM', 'CONTROLSOURCE', 'm.cAlias + ".PERIOD"'
GO
EXEC X_SET_PROP 'COLUMN_REF_PERIOD_CM', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_REF_PERIOD_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERIOD"'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_CM', 'TITLE', 'Итого сумма'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_CM', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_CM', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_CM', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_RKO_DED_PR_1', 'TITLE', 'Бух. документ'
GO
EXEC X_SET_PROP 'COLUMN_RKO_DED_PR_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_RKO_DED_PR_1', 'CONTROLSOURCE', 'm.cAlias + ".RKO"'
GO
EXEC X_SET_PROP 'COLUMN_RKO_DED_PR_1', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'COLUMN_RKO_DED_PR_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RKO"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_CM', 'CONTROL_NAME_EDIT', 'Atextbox04'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_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 'CLOSE_MONTH_NAME_DEP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'CONTROL_NAME_EDIT', 'cnt_dep.asel_spr01'
GO
EXEC X_SET_PROP 'CLOSE_MONTH_NAME_DEP', 'COMMENTARY', 'Наименование организации'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH_TABLE', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable,m.cAlias,''DOCUMENTS_DED_OTHER_TABLE'','' * '')'
GO
EXEC X_SET_PROP 'DOCUMENTS_CLOSE_MONTH_TABLE', 'SERVER_TABLE_NAME', 'SDOC_DOT_TABLE'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable,m.cAlias,''SDOC_DOT_SKIDKI_FIO'','' * '')'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable,m.cAlias,''SDOC_DOT_VYCHET_FIO'','' * '')'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS', 'TITLE', 'Настройка отчисления по травматизму'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("DOCUMENTS_CLOSE_MONTH,SALARY_OPTIONS,DOCUMENTS_DEDUCT_ESN_G", "Настройки отчисления по травматизму,Общие настройки по зарплате,Настройки отчислений страховых взносов")
'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS', 'COMMENTARY', 'Настройки устанавливают особенности для режима "Расчет отчислений в ФСС по травматизму"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_DEDUCT_SALARY'', oForm.APageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, CODE, NAME'', ''REF_DED, CODE_DED, NAME_DED'', '''', '''', ''WAY_CALC=5'', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".CODE_DED"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_DED_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_DED"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'TITLE', 'Наименование отчисления'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DED"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DED_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DED"'
GO
EXEC X_SET_PROP 'COLUMN_REF_DED_CM_T', 'ORDER_NUMBER', '4'
GO
EXEC X_SET_PROP 'COLUMN_REF_DED_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".REF_DED"'
GO
EXEC X_SET_PROP 'COLUMN_REF_DED_CM_T', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_DED_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_DED"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.apageframe1.page1.bSPISOK.bGRID1.RecordSource, ''LINK, CODE'', ''LINK_VKR,NAME_VKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_CM_T', 'COMMENTARY', 'Источник финансирования'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.apageframe1.page1.bSPISOK.bGRID1.RecordSource, ''LINK, CODE'', ''LINK_EKR,NAME_EKR'', '''', '''', ''CODE LIKE ''21%'' OR CODE LIKE ''22%''  OR CODE LIKE ''26%''"'', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'CONTROLSOURCE', 'm.cAlias + ".NAME_EKR"'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_EKR"'
GO
EXEC X_SET_PROP 'DOC_CM_TABLE_NAME_EKR', 'COMMENTARY', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_CM_T', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'TITLE', 'Базовая сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'ORDER_NUMBER', '5'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_CM_T', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'TITLE', 'Скидка'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'ORDER_NUMBER', '5'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'CONTROLSOURCE', 'm.cAlias + ".SKIDKA"'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SKIDKA"'
GO
EXEC X_SET_PROP 'DED_OTHER_SKIDKA', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'TITLE', 'Вычет'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'ORDER_NUMBER', '5'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'CONTROLSOURCE', 'm.cAlias + ".VYCHET"'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VYCHET"'
GO
EXEC X_SET_PROP 'DED_OTHER_VYCHET', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'TITLE', 'Процент'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'TYPE_FIELD_DICT', 'NUMERIC(6,2)'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'COLUMN_PERCENT_CM_T', 'INPUT_MASK', '9999.99'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'ORDER_NUMBER', '7'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_CM_T', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'TITLE', 'Платежка - образец для перечисления взносов по травматизму'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DOCUMENTS_PAY ", oForm.cSel_Spr_Alias, "LINK, NUMBER, TITLE", "AN_OPT1,AN_OPT1C,AN_OPT1N", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'STORAGE', 'SK'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'SHORT_CODE_OBJ', 'AN_OPT1'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'INPUT_MASK', 'XXXXXXXX'
GO
EXEC X_SET_PROP 'ESNTR_OPT1', 'COMMENTARY', 'В этой настройке указывается в качестве образца платежное поручение на перечисление взносов по травматизму. При автоматическом формировании подобной платежки, программа будет указывать основные реквизита платежки так же, как в платежке - образце.'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'TITLE', 'Заявка на кассовый расход - образец для перечисления СВ по травматизму'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BB_ZAYAVKA_KR", oForm.cSel_Spr_Alias, "LINK, NUMBER, TITLE", "AN_OPT2,AN_OPT2C,AN_OPT2N", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'STORAGE', 'SK'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'SHORT_CODE_OBJ', 'AN_OPT2'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'INPUT_MASK', 'XXXXXXXX'
GO
EXEC X_SET_PROP 'ESNTR_OPT2', 'COMMENTARY', 'В этой настройке указывается в качестве образца заявка на кассовый расход на перечисление взносов по травматизму. При автоматическом формировании подобной платежки, программа будет указывать основные реквизита платежки так же, как в платежке - образце.'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'TITLE', 'Предоставлять скидки'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'SHORT_CODE_OBJ', 'SKIDKI'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SKIDKI"'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'CONTROL_NAME_EDIT', 'Acheckbox3'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT3', 'COMMENTARY', 'При включенной опции программа будет предоставлять установленные скидки к доходам. Размер скидок указывается в настройках по зарплате на вкладке ЕСН. После изменения данной настройки требуется пересчитать отчисления по травматизму с начала года!'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'TITLE', 'Предоставлять вычеты'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'SHORT_CODE_OBJ', 'VYCHET'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VYCHET"'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'CONTROL_NAME_EDIT', 'Acheckbox4'
GO
EXEC X_SET_PROP 'ESNTR_OPTIONS_OPT4', 'COMMENTARY', 'При включенной опции программа будет предоставлять установленные вычеты. Размер вычетов указывается в настройках по зарплате на вкладке ЕСН. После изменения данной настройки требуется пересчитать отчисления по травматизму с начала года!'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T_1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_CM_T_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_INC', 'TITLE', 'Код дохода'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_INC', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_INC', 'CONTROLSOURCE', 'm.cAlias + ".CODE_INC"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_INC', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_FIO', 'TITLE', 'Ф.И.О.'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_FIO', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_FIO', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_FIO', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_FIO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'CONTROLSOURCE', 'm.cAlias + ".CODE_S_FIN"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_S_FIN', 'COMMENTARY', 'Источник финансирования'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_CODE_EKR', 'COMMENTARY', 'ЭКР'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'ORDER_NUMBER', '7'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_SKIDKI_FIO_SUMMA', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_DED', 'TITLE', 'Код вычета'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_DED', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_DED', 'CONTROLSOURCE', 'm.cAlias + ".CODE_DED"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_DED', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_FIO', 'TITLE', 'Ф.И.О.'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_FIO', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_FIO', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_FIO', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_FIO', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'CONTROLSOURCE', 'm.cAlias + ".CODE_S_FIN"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_S_FIN', 'COMMENTARY', 'Источник финансирования'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_CODE_EKR', 'COMMENTARY', 'ЭКР'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'ORDER_NUMBER', '7'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SDOC_DOT_VYCHET_FIO_SUMMA', 'INPUT_MASK', '999999999.99'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESNTR_OPT1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPT1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPT1'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPT1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '24495' FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPT1'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESNTR_OPT2' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPT2')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPT2'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPT2'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '59664' FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPT2'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESNTR_OPTIONS_OPT3' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPTIONS_OPT3')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPTIONS_OPT3'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPTIONS_OPT3'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPTIONS_OPT3'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESNTR_OPTIONS_OPT4' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPTIONS_OPT4')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPTIONS_OPT4'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH] WHERE CODE = 'ESNTR_OPTIONS_OPT4'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'ESNTR_OPTIONS_OPT4'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_CLOSE_MONTH]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_CLOSE_MONTH', 'Зарплата-КС', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/
EXEC DBO.W_SPERM_WRITE 'ESNTR_OPT1', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'ESNTR_OPT2', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'ESNTR_OPTIONS_OPT3', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'ESNTR_OPTIONS_OPT4', 'Зарплата-КС', 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 = '4335')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')

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 = '4335'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4197'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '4197', 'Расчет отчислений в ФСС по травматизму', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
/****** Объект: Расчеты по договорам******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOCUMENTS_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOCUMENTS_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOCUMENTS_DGH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH', 'Расчеты по договорам', 25, (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_DGH', NAME = 'Расчеты по договорам', ORDERS = '25', 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_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_DGH', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_DGH', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FLAG_JC_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FLAG_JC_DGH', 'Признак проведения в журнале расчетов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_FLAG_JC_DGH', NAME = 'Признак проведения в журнале расчетов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_FLAG_JC_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_DGH', 'Номер документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_DGH', NAME = 'Номер документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE_DGH', 'Дата документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE_DGH', NAME = 'Дата документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MONTH_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MONTH_DGH', 'Месяц расчета', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MONTH_DGH', NAME = 'Месяц расчета', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MONTH_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_YEAR_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_YEAR_DGH', 'Год расчета', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_YEAR_DGH', NAME = 'Год расчета', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_YEAR_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_DGH', 'Итоговая сумма', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_DGH', NAME = 'Итоговая сумма', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_COMMENTARY_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_COMMENTARY_DGH', 'Комментарий', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_COMMENTARY_DGH', NAME = 'Комментарий', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_COMMENTARY_DGH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_RKO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_RKO', 'Бух. документ', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_RKO', NAME = 'Бух. документ', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_RKO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_NAME_DEP', 'Организация', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_NAME_DEP', NAME = 'Организация', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T1', 'Договорники таблица начисления', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T1', NAME = 'Договорники таблица начисления', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T2', 'Договорники таблица удержания', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T2', NAME = 'Договорники таблица удержания', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T3', 'Договорники таблица отчисления', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T3', NAME = 'Договорники таблица отчисления', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_OPTIONS', 'Настройка расчетов по договорам', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_OPTIONS', NAME = 'Настройка расчетов по договорам', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_DGH_T1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_DGH_T1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_DGH_T1', 'Номер строки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_DGH_T1', NAME = 'Номер строки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FIO_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FIO_DGH_T1', 'ФИО', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_FIO_DGH_T1', NAME = 'ФИО', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_FIO_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_DEP_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_DEP_DGH_T1', 'Ссылка на работника', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_DEP_DGH_T1', NAME = 'Ссылка на работника', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_DEP_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_PAY_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_PAY_DGH_T1', 'Код начисления', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_PAY_DGH_T1', NAME = 'Код начисления', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_PAY_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_PAY_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_PAY_DGH_T1', 'Наименование начисления', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_PAY_DGH_T1', NAME = 'Наименование начисления', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_PAY_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_PAY_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_PAY_DGH_T1', 'Ссылка на начисление', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_PAY_DGH_T1', NAME = 'Ссылка на начисление', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_PAY_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_DGH_T1', 'Сумма', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_DGH_T1', NAME = 'Сумма', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_DOG_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_DOG_DGH_T1', 'Описание договора', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_DOG_DGH_T1', NAME = 'Описание договора', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_DOG_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_DOG_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_DOG_DGH_T1', 'Ссылка на договор', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_DOG_DGH_T1', NAME = 'Ссылка на договор', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_DOG_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_VKR_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_VKR_DGH_T1', 'Ссылка на источник', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_VKR_DGH_T1', NAME = 'Ссылка на источник', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_VKR_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR_DGH_T1', 'Источник', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR_DGH_T1', NAME = 'Источник', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_EKR_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_EKR_DGH_T1', 'Ссылка на ЭКР', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_EKR_DGH_T1', NAME = 'Ссылка на ЭКР', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_EKR_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_DGH_T1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_DGH_T1', 'ЭКР', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EKR_DGH_T1', NAME = 'ЭКР', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EKR_DGH_T1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_DGH_T2', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_DGH_T2', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_DGH_T2', 'Номер строки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_DGH_T2', NAME = 'Номер строки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FIO_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FIO_DGH_T2', 'ФИО', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_FIO_DGH_T2', NAME = 'ФИО', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_FIO_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_DEP_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_DEP_DGH_T2', 'Ссылка на работника', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_DEP_DGH_T2', NAME = 'Ссылка на работника', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_DEP_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_PAY_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_PAY_DGH_T2', 'Код удержания', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_PAY_DGH_T2', NAME = 'Код удержания', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_PAY_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_PAY_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_PAY_DGH_T2', 'Наименование удержания', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_PAY_DGH_T2', NAME = 'Наименование удержания', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_PAY_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_PAY_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_PAY_DGH_T2', 'Ссылка на удержание', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_PAY_DGH_T2', NAME = 'Ссылка на удержание', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_PAY_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2_BASE_YEAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T2_BASE_YEAR', 'Базовая сумма с нач. года', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T2_BASE_YEAR', NAME = 'Базовая сумма с нач. года', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T2_BASE_YEAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_BASE_SUMMA_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_BASE_SUMMA_DGH_T2', 'База за месяц', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_BASE_SUMMA_DGH_T2', NAME = 'База за месяц', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_BASE_SUMMA_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2_PERCENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T2_PERCENT', 'Процент', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T2_PERCENT', NAME = 'Процент', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T2_PERCENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2_SUMMA_YEAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'Удержать', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T2_SUMMA_YEAR', NAME = 'Удержать', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T2_SUMMA_YEAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2_SUMMA_OLD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'Удержано', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_DGH_T2_SUMMA_OLD', NAME = 'Удержано', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_DGH_T2_SUMMA_OLD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_DGH_T2', 'Сумма', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_DGH_T2', NAME = 'Сумма', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_VKR_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_VKR_DGH_T2', 'Ссылка на источник', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_VKR_DGH_T2', NAME = 'Ссылка на источник', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_VKR_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR_DGH_T2', 'Источник', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_VKR_DGH_T2', NAME = 'Источник', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_VKR_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_EKR_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_EKR_DGH_T2', 'Ссылка на ЭКР', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_LINK_EKR_DGH_T2', NAME = 'Ссылка на ЭКР', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_LINK_EKR_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_DGH_T2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_DGH_T2', 'ЭКР', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EKR_DGH_T2', NAME = 'ЭКР', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EKR_DGH_T2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_DGH_T3', 'Маркер', 1, (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_MARKER_DGH_T3', NAME = 'Маркер', ORDERS = '1', 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_MARKER_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_DGH_T3', 'Номер строки', 2, (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_NUMBER_DGH_T3', NAME = 'Номер строки', ORDERS = '2', 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_NUMBER_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_FIO_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_FIO_DGH_T3', 'ФИО', 3, (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_FIO_DGH_T3', NAME = 'ФИО', ORDERS = '3', 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_FIO_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_DEP_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_DEP_DGH_T3', 'Ссылка на работника', 4, (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_LINK_DEP_DGH_T3', NAME = 'Ссылка на работника', ORDERS = '4', 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_LINK_DEP_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_PAY_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_PAY_DGH_T3', 'Код отчисления', 5, (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_CODE_PAY_DGH_T3', NAME = 'Код отчисления', ORDERS = '5', 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_CODE_PAY_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_PAY_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_PAY_DGH_T3', 'Наименование отчисления', 6, (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_PAY_DGH_T3', NAME = 'Наименование отчисления', ORDERS = '6', 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_PAY_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_PAY_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_PAY_DGH_T3', 'Ссылка на отчисление', 7, (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_LINK_PAY_DGH_T3', NAME = 'Ссылка на отчисление', ORDERS = '7', 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_LINK_PAY_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3_BASE_YEAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T3_BASE_YEAR', 'Базовая сумма с нач. года', 8, (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 = 'DOCUMENTS_DGH_T3_BASE_YEAR', NAME = 'Базовая сумма с нач. года', ORDERS = '8', 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 ='DOCUMENTS_DGH_T3_BASE_YEAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_BASE_SUMMA_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_BASE_SUMMA_DGH_T3', 'База за месяц', 9, (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_BASE_SUMMA_DGH_T3', NAME = 'База за месяц', ORDERS = '9', 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_BASE_SUMMA_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3_PERCENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T3_PERCENT', 'Процент', 10, (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 = 'DOCUMENTS_DGH_T3_PERCENT', NAME = 'Процент', ORDERS = '10', 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 ='DOCUMENTS_DGH_T3_PERCENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3_SUMMA_YEAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'Отчислить', 11, (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 = 'DOCUMENTS_DGH_T3_SUMMA_YEAR', NAME = 'Отчислить', ORDERS = '11', 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 ='DOCUMENTS_DGH_T3_SUMMA_YEAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_DGH_T3_SUMMA_OLD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'Отчислено', 12, (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 = 'DOCUMENTS_DGH_T3_SUMMA_OLD', NAME = 'Отчислено', ORDERS = '12', 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 ='DOCUMENTS_DGH_T3_SUMMA_OLD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_DGH_T3', 'Сумма', 13, (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_SUMMA_DGH_T3', NAME = 'Сумма', ORDERS = '13', 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_SUMMA_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_VKR_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_VKR_DGH_T3', 'Ссылка на источник', 14, (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_LINK_VKR_DGH_T3', NAME = 'Ссылка на источник', ORDERS = '14', 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_LINK_VKR_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_VKR_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_VKR_DGH_T3', 'Источник', 15, (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_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
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_LINK_EKR_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_LINK_EKR_DGH_T3', 'Ссылка на ЭКР', 16, (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_LINK_EKR_DGH_T3', NAME = 'Ссылка на ЭКР', ORDERS = '16', 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_LINK_EKR_DGH_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_DGH_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_DGH_T3', 'ЭКР', 17, (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_CODE_EKR_DGH_T3', NAME = 'ЭКР', ORDERS = '17', 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_CODE_EKR_DGH_T3'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'TITLE', 'Расчеты по договорам'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'INIT_OBJECT_METHOD', 'S_SPISOK("DOCUMENTS_DGH")'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOCUMENTS_DGH", "SALARY_DELETE_SDOC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'SAVE_OBJECT_METHOD', 'sd_nuo_dgh_save(oForm)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SD_NUO_DGH'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'SELECT_RECORDS_METHOD', 'sa_select_document_list_zb1(''DOCUMENTS_DGH'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''DOCUMENTS_DGH'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'SERVER_TABLE_NAME', 'SDOC'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'OPTIONS_OBJECT_CODE', 'DOCUMENTS_DGH_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'HELP_TOPIC', '38'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'COMMENTARY', 'Режим предназначен для расчетов с работниками по договорам гражданско-правового характера. 
При входе в режим откроется окно стандартного списка программы, содержащее реестр расчетов, произведенных за расчетный период.  Формирование нового расчета – кнопка   Добавить. Окно ввода/редактирования расчета содержит три закладки: начисления, удержания, отчисления.
 
1.	Заполните обязательные поля, отмеченные цветом. Поля «Номер» и «Дата» документа заполняются программой автоматически. 
Нажмите кнопку <ЗАПОЛНИТЬ>. Откроется список договоров, действующих в данном месяце и по которым еще не создан расчет. Отметьте нужные и нажмите кнопку «Выбрать». После этого будет выполнен автоматический расчет сумм начислений удержаний и отчислений по настройкам, указанным в данных договорах. Если в электронной форме договора установлены флажки на полях «Облагается НДФЛ и ЕСН», «Учитывать при расчете отчисления в ФСС» на соответствующих закладках формы расчета появятся записи с рассчитанными суммами удержаний и отчислений.
2.	Нажмите кнопку <СОХРАНИТЬ>.
3.	Нажмите кнопку <ОПЕРАЦИИ>, для того чтобы удержания попали в «Реестр операций по заработной плате» и могли быть использованы для других расчетов.
4.	Нажмите кнопку «Бух. Док.», чтобы сформировать или открыть сформированные платежные поручения на перечисление НДЛФ и ЕСН по данному расчету.
'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_JC_DGH', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_JC_DGH', 'CONTROLSOURCE', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_FLAG_JC_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FLAG_JC"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'CONTROL_NAME_EDIT', 'ATxtNomDok'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH', 'COMMENTARY', 'Номер документа по порядку'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_DGH', 'CONTROL_NAME_EDIT', 'Aseldate02'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'CONTROLSOURCE', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_DGH', 'CONTROL_NAME_EDIT', 'Acmbmonth1'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'CONTROLSOURCE', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_DGH', 'CONTROL_NAME_EDIT', 'AYear1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'TITLE', 'Cумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'TYPE_FIELD_DICT', 'VARCHAR(200)'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'COLUMN_COMMENTARY_DGH', 'CONTROL_NAME_EDIT', 'Atextbox04'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_RKO', 'TITLE', 'Бух. документ'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_RKO', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_RKO', 'CONTROLSOURCE', 'm.cAlias + ".RKO"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_RKO', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_RKO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RKO"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_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 'DOCUMENTS_DGH_NAME_DEP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'CONTROL_NAME_EDIT', 'cnt_dep.asel_spr01'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_NAME_DEP', 'COMMENTARY', 'Наименование организации'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T1', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable, m.cAlias,''DOCUMENTS_DGH_T1'','' * '')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T1', 'SERVER_TABLE_NAME', 'SDOC_DGH_TABLE'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable, m.cAlias,''DOCUMENTS_DGH_T2'','' * '')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2', 'SERVER_TABLE_NAME', 'SDOC_DGH_TABLE'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable, m.cAlias,''DOCUMENTS_DGH_T3'','' * '')'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3', 'SERVER_TABLE_NAME', 'SDOC_DGH_TABLE'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_OPTIONS', 'TITLE', 'Настройка расчетов по договорам'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_OPTIONS', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("DOCUMENTS_DEDUCT_ESN_G,DOCUMENTS_INCOME_TAX,DOCUMENTS_CLOSE_MONTH , SALARY_OPTIONS", "Настройки удержания ЕСН,Настройки удержания НДФЛ,Расчет отчислений в ФСС по травматизму,Общие настройки по зарплате")'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_OPTIONS', 'COMMENTARY', 'Настройки устанавливают особенности для режима "Расчетов по договорам"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'CONTROLSOURCE', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_DEPARTMENT'', oForm.Apageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, NAME'', ''LINK_DEP,FIO'', '''', '''', "  type = 5 ", .T., 1, oForm, oObj)
'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T1', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_PAY_SALARY'', oForm.Apageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, CODE, NAME'', ''LINK_PAY, CODE_PAY, NAME_PAY'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T1', 'TITLE', 'Наименование начисления'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_REF_PAY_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_REF_PAY_DGH_T1', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_PAY_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T1', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'TITLE', 'Номер договора'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_REESTR_DGH'', oForm.Apageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, NUMBER'', ''LINK_DOG,NAME_DOG'', '''', '''','''', .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DOG"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_DOG_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DOG"'
GO
EXEC X_SET_PROP 'COLUMN_REF_DOG_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_DOG"'
GO
EXEC X_SET_PROP 'COLUMN_REF_DOG_DGH_T1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_REF_DOG_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_DOG"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.Apageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_VKR,NAME_VKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.Apageframe1.Page1.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T2', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'CONTROLSOURCE', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_REESTR_DGH'', oForm.Apageframe1.Page2.BSpisok.BGrid1.RecordSource, ''PERS_LINK, FIO'', ''PERS_LINK, FIO'', '''', '''', " PERS_LINK = " + STR(EVAL(oForm.Apageframe1.Page1.Bspisok.BGrid1.RecordSource + ".PERS_LINK")) , .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T2', 'FIELD_IN_SEARCH', '1'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T2', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_TAX_SALARY'', oForm.Apageframe1.Page2.BSpisok.BGrid1.RecordSource, ''LINK, CODE, NAME'', ''LINK_PAY, CODE_PAY, NAME_PAY'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'REFERENCE_TO_DICT', 'DICTIONARY_TAX_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T2', 'TITLE', 'Наименование удержания'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T2', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T2', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'TITLE', 'Баз.сум.с Н.Г.'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'CONTROLSOURCE', 'm.cAlias + ".BASE_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BASE_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_BASE_YEAR', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'TITLE', 'База за месяц'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T2', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'TITLE', 'Процент'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'CONTROLSOURCE', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_PERCENT', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'TITLE', 'Удержать'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_YEAR', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'TITLE', 'Удержано'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T2_SUMMA_OLD', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T2', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T2', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.Apageframe1.Page2.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_VKR,NAME_VKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T2', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.Apageframe1.Page2.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T3', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'CONTROLSOURCE', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_DEPARTMENT'', oForm.Apageframe1.Page3.BSpisok.BGrid1.RecordSource, ''LINK, NAME'', ''LINK_DEP,FIO'', '''', '''', "  type =5  ", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'COLUMN_FIO_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T3', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_LINK_DEP_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_DEP"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_DEDUCT_SALARY'', oForm.Apageframe1.Page3.BSpisok.BGrid1.RecordSource, ''LINK, CODE, NAME'', ''LINK_PAY, CODE_PAY, NAME_PAY'', '''', '''', '''', .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'REFERENCE_TO_DICT', 'DICTIONARY_PAY_SALARY'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_PAY_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T3', 'TITLE', 'Наименование отчисления'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_PAY_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T3', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_LINK_PAY_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_PAY"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'TITLE', 'Баз.сум.с Н.Г.'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'CONTROLSOURCE', 'm.cAlias + ".BASE_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BASE_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_BASE_YEAR', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'TITLE', 'База за месяц'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_BASE_SUMMA_DGH_T3', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'TITLE', 'Процент'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'CONTROLSOURCE', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PERCENT"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_PERCENT', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'TITLE', 'Отчислить'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_YEAR"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_YEAR', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'TITLE', 'Отчислено'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_OLD"'
GO
EXEC X_SET_PROP 'DOCUMENTS_DGH_T3_SUMMA_OLD', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DGH_T3', 'INPUT_MASK', '999999999.99'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T3', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_VKR_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN '', oForm.Apageframe1.Page3.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_VKR,NAME_VKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_VKR_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_VKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T3', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_LINK_EKR_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.Apageframe1.Page3.BSpisok.BGrid1.RecordSource, ''LINK, CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', '''', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'TYPE_FIELD_DICT', 'VARCHAR(3)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DGH_T3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_DGH', 'Зарплата-КС', 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 = '4642')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')

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 = '4642'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4045'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '4045', 'Расчеты по договорам', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC', 'OPTIONS_OBJECT_CODE', 'DOCUMENTS_RECALC_OPTIONS'
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_RECALC_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_DOCUMENTS_RECALC_OPTIONS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_RECALC_OPTIONS]

CREATE TABLE  dbo._UPD_OPT_DOCUMENTS_RECALC_OPTIONS (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_DOCUMENTS_RECALC_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 = 'DOCUMENTS_RECALC_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 = 'DOCUMENTS_RECALC_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 = 'DOCUMENTS_RECALC_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 = 'DOCUMENTS_RECALC_OPTIONS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_RECALC_OPTIONS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_RECALC_OPTIONS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_RECALC_OPTIONS', 'Настройки перерасчёта начислений', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_RECALC_OPTIONS', NAME = 'Настройки перерасчёта начислений', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_RECALC_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_RECALC_OPT1', 'Суммы перерасчёта учитывать в месяце', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_RECALC_OPT1', NAME = 'Суммы перерасчёта учитывать в месяце', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_RECALC_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_RECALC_OPT1'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPTIONS', 'TITLE', 'Настройки перерасчёта начислений'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPTIONS', 'EDIT_OBJECT_METHOD', 'SALARY_FORM_LOAD(''sa_options'',''"DOCUMENTS_RECALC_OPTIONS  "'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPTIONS', 'COMMENTARY', 'Настройки устанавливают параметры по умолчанию и особенности для режима "Перерасчёт начислений"'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'TITLE', 'Суммы перерасчёта учитывать в месяце'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'ROWSOURCE', '1. за который перерассчитывали,2. в котором перерассчитывали'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'CONTROL_NAME_EDIT', 'Acombobox1'
GO
EXEC X_SET_PROP 'DOCUMENTS_RECALC_OPT1', 'COMMENTARY', 'Настройка устанавливает способ учёта перерассчитанных сумм в расчётах по среднему (б/л, отпускные и пр.). Для рассчёта НДФЛ и взносов в фонды суммы однозначно учитываются в том же месяце, в котором были начислены.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'DOCUMENTS_RECALC_OPT1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_RECALC_OPTIONS] WHERE CODE = 'DOCUMENTS_RECALC_OPT1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_RECALC_OPT1'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_RECALC_OPTIONS] WHERE CODE = 'DOCUMENTS_RECALC_OPT1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_RECALC_OPT1'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_DOCUMENTS_RECALC_OPTIONS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_RECALC_OPTIONS]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_RECALC_OPTIONS', 'Зарплата-КС', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/

EXEC DBO.W_SPERM_WRITE 'DOC_DED_WRIT_OPTIONS', 'Зарплата-КС', 63,0
GO

GO
/****** Объект: FOT******/
EXEC X_SET_PROP 'EMPLS_WP_FOT', 'COMMENTARY', 'Способ формирования оклада: ПКГ - на основе базового оклада ПКГ и коэф, ЕТС - по ЕТС и квалификационному разряду, БОУ - по стоимости бюджетной образовательной услуги,Сумма - месячная ставка задаётся при вводе нагрузки.'
GO

GO

DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

INSERT INTO dbo.MINROT_PAYS (LINK_MINROT, LINK_PAYS, OBJECT)
SELECT M.LINK, P.LINK, @LINK_OBJ 
FROM dbo.MINROT M INNER JOIN dbo.PAYS P ON 1=1
WHERE 
	M.PERIOD >= '20120101'
	AND
	M.PERIOD < '20990101'
	AND
	P.[OBJECT] = 3 AND P.WAY_CALC IN (2,3,6,7)
	AND
	NOT EXISTS (SELECT * FROM dbo.DICTIONARY_MROT_TABLE4 T4 WHERE T4.LINK_MINROT = M.LINK AND T4.REF_PAY = P.LINK)
ORDER BY
	M.LINK, P.LINK

DELETE FROM dbo.MINROT_PAYS
WHERE 
	[OBJECT] = @LINK_OBJ
	AND
	EXISTS (SELECT * FROM dbo.PAYS P WHERE P.[OBJECT] = 3 AND P.WAY_CALC IN (8,9) AND P.LINK = dbo.MINROT_PAYS.LINK_PAYS)
	AND
	EXISTS (SELECT * FROM dbo.MINROT M WHERE M.PERIOD >= '20120101' AND M.PERIOD < '20990101' AND M.LINK = dbo.MINROT_PAYS.LINK_MINROT)

GO



/*НАСТРОЙКИ ТАРИФОВ 2012 ГОДА*/

--Общий (НР) 
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 512000 AND TARIF = 1)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',512000, 22, 22, 16, 1
set @p1 = 0 
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 1)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',999999999, 10, 10, 10, 1
GO

--ЕНВД (УСЕН) 
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 512000 AND TARIF = 2)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',512000, 22, 22, 16, 2
set @p1 = 0 
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 2)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',999999999, 10, 10, 10, 2
GO

--Инвалиды (ОЗОИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 512000 AND TARIF = 3)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',512000, 22, 22, 16, 3
set @p1 = 0 
if not exists (select * from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 3)
	exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',999999999, 10, 10, 10, 3
GO

GO

--- Вычеты и МРОТ
declare @PERIOD datetime
	
	declare @P1 int, @LINK_DED INT
				
	DECLARE @Object int, @LinkDep int
	SELECT @Object = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'
	SELECT @LinkDep = LINK FROM dbo.DICTIONARY_DEPARTMENT WHERE TYPE = 4

	DECLARE @Cur1 CURSOR
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT LINK FROM dbo.MINROT WHERE YEAR(PERIOD) = 2011
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @P1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
		
			IF COALESCE(@Object,0) > 0 AND COALESCE(@P1,0) > 0 BEGIN
				-- Заполняем первую вкладку

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '104'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,500)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '105'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,3000)
			--
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '114'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,1000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '115'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,1000)
					
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '116'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,3000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '117'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,3000)
			--
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '118'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,2000)
				
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '119'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,2000)
					
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '120'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,6000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '121'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,6000)			
			--
				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '122'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,2000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '123'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,2000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '124'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,6000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '125'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,280000,6000)									

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '311'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '312'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '318'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '501'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,4000)				

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '502'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,4000)				

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,4000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '108'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '109'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '110'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '111'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '112'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '113'
				IF COALESCE(@LINK_DED,0) > 0
					DELETE FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object					

			END

		END
		FETCH NEXT FROM @Cur1 INTO @P1
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1
GO
	
UPDATE E
SET E.DATE2 = '20101231'
FROM 
	dbo.EMPL_DED E
	INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = E.DED_LINK
WHERE
	E.DATE2 IS NULL OR E.DATE2 >= '20110101'
	AND
	T.SNAME IN ('108','109','110','111','112','113')
GO



--- Вычеты и МРОТ
declare @PERIOD datetime
	
	declare @P1 int, @LINK_DED INT
				
	DECLARE @Object int, @LinkDep int
	SELECT @Object = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'
	SELECT @LinkDep = LINK FROM dbo.DICTIONARY_DEPARTMENT WHERE TYPE = 4

	DECLARE @Cur1 CURSOR
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT LINK FROM dbo.MINROT WHERE YEAR(PERIOD) = 2012
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @P1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
		
			IF COALESCE(@Object,0) > 0 AND COALESCE(@P1,0) > 0 BEGIN
				-- Заполняем первую вкладку

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '311'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '312'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '318'
				IF COALESCE(@LINK_DED,0) > 0 AND NOT EXISTS(SELECT * FROM dbo.MINROT_DICTION WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object)
					INSERT INTO dbo.MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
					VALUES(@P1,@LINK_DED,@Object,0,2000000)					

				SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
				DELETE FROM dbo.MINROT_DICTION
				WHERE LINK_MINROT = @P1 AND LINK_DICTION = @LINK_DED AND OBJECT = @Object			

			END

		END
		FETCH NEXT FROM @Cur1 INTO @P1
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1
GO

GO

--Удаление дубликатов настроек
DECLARE @Cur1 CURSOR, @OBJECT INT, @VALUE VARCHAR(1000)

SET @Cur1 = CURSOR FORWARD_ONLY

FOR 
	SELECT [OBJECT]
	FROM dbo.S_OPTIONS OP INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = OP.[OBJECT]
	WHERE
		[SID] IS NULL
		AND 
		SO.CODE NOT IN ('OBJ_UPDATE_SVOD')
	GROUP BY
		[OBJECT] 
	HAVING
		COUNT(*) > 1

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @OBJECT
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SET @VALUE = ISNULL( (
				SELECT TOP 1 VALUE FROM S_OPTIONS WHERE [OBJECT] = 	
				(SELECT LINK FROM S_OBJECTS SO WHERE SO.LINK = @OBJECT) 
				AND SID IS NULL 
				ORDER BY VALUE DESC), '')

		DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND [OBJECT] = @OBJECT
		
		INSERT INTO dbo.S_OPTIONS ([OBJECT], [VALUE], [SID])
		VALUES (@OBJECT, @VALUE, 0)				

	END

	FETCH NEXT FROM @Cur1 INTO @OBJECT
END

CLOSE @Cur1
DEALLOCATE @Cur1
GO

GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Постоянные начисления, удержания и заявленные вычеты"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_PAY_EMPL')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_REP_EMPL')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'QUERY_SQL')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_REP_EMPL'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SQL_REP_PAY_EMPL'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_SQL_REP_PAY_EMPL', 'Постоянные начисления, удержания и заявленные вычеты', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO


GO
--Обновление настроек 2012 года
exec dbo.SA_SET_STATIC_NASTR '2012'
GO


/*Формирование всех используемых графиков на 2012 год*/
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 = 2012, @MONTH = 5
		WHILE @MONTH <= 5
		BEGIN

			IF EXISTS(SELECT @LinkGrophik FROM dbo.KD_GRAPH_TABLE WHERE [YEAR] = @YEAR AND [MONTH] = @MONTH AND LINK_GR = @LinkGrophik)
			BEGIN
				DELETE FROM dbo.GRAPHICS WHERE YEAR(PERIOD) = @YEAR AND MONTH(PERIOD) = @MONTH AND GRAPH_LINK = @LinkGrophik
			END	

			IF NOT EXISTS(SELECT @LinkGrophik FROM dbo.KD_GRAPH_TABLE WHERE [YEAR] = @YEAR AND [MONTH] = @MONTH AND LINK_GR = @LinkGrophik)
			BEGIN
				IF object_id('tempdb..#sa_tmp_graph') is not null
				drop table #sa_tmp_graph
				
				CREATE TABLE #sa_tmp_graph(CHECKED tinyint, UPD tinyint, DEL tinyint, [DAY] tinyint, [HOUR] numeric(18,2), TD_LINK int, TD_CODE varchar(10),
						TD_NAME varchar(254), PRIORITET tinyint )
				
				INSERT INTO #sa_tmp_graph(CHECKED, UPD, DEL, [DAY], [HOUR], TD_LINK, TD_CODE, TD_NAME, PRIORITET)
				exec dbo.KD_GRAPH_FILL @VID_LINK, @MONTH, @YEAR
			
				Select @gHourNorm = DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOUR],@ISMINUTES)),@ISMINUTES) from #sa_tmp_graph where [HOUR] > 0
				Select @gDayNorm = COUNT(DISTINCT [DAY]) from #sa_tmp_graph where [HOUR] > 0
				
				IF COALESCE(@gHourNorm,0) > 0 AND coalesce(@gDayNorm,0) > 0
				BEGIN
				
					EXEC dbo.KD_GRAPH_SAVE @LinkGrophik OUT, @LINK2 OUT, @NAME_GR, @MONTH, @YEAR, @VID_LINK, @gDayNorm, @gHourNorm
		
					SET @Cur2 = CURSOR FORWARD_ONLY
					
					FOR select [DAY], [HOUR], [TD_LINK] from #sa_tmp_graph order by [DAY]
					OPEN @Cur2
					FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN
							exec dbo.KD_GRAPH_TABLE_SAVE @LINK2, @DAY, @HOUR, @TD_LINK
						END
					
						FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					END
					
					CLOSE @Cur2
					DEALLOCATE @Cur2
				END
			END

			Set @MONTH = @MONTH + 1
		END
		
	END
	FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
END

CLOSE @Cur1
DEALLOCATE @Cur1
GO

GO
exec X_SET_OPTION 'SA_SZV4_OPT2','0',1
GO
exec X_SET_OPTION 'SA_SZV4_OPT5','0',1
GO
exec X_SET_OPTION 'SA_SZV4_OPT4','0',1
GO


IF NOT EXISTS (SELECT * FROM dbo.SZV4_SPR WHERE CODE = 'ДЛДЕТИ')
	INSERT INTO dbo.SZV4_SPR WITH (ROWLOCK) (spr_code, code, [name], date1) 
		VALUES ('ISCHISL_STAZH_DOP_SV', 'ДЛДЕТИ', 'Отпуск по уходу за ребенком от 1,5 до 3 лет', '20100101')
ELSE
	UPDATE dbo.SZV4_SPR WITH (ROWLOCK)
	SET spr_code = 'ISCHISL_STAZH_DOP_SV', [name] = 'Отпуск по уходу за ребенком от 1,5 до 3 лет', date1 = '20100101'
	WHERE CODE = 'ДЛДЕТИ'
GO
			
GO
/****** Объект: Долг по страх. части******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_STR')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_STR'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_STR')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_DOLG_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_DOLG_STR', 'Долг по страх. части', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_DOLG_STR', NAME = 'Долг по страх. части', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_DOLG_STR'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'TITLE', 'Долг по страх. части'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'CONTROLSOURCE', 'm.cAlias + ".sum_dolg_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".sum_dolg_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_STR', 'COMMENTARY', 'Остаток задолженности за прошлый год по страховой части'
GO

/****** Объект: Уплата долга по страх. части******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_PLAT_DOLG_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'Уплата долга по страх. части', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', NAME = 'Уплата долга по страх. части', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_PLAT_DOLG_STR'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'TITLE', 'Уплата долга по страх. части'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'CONTROLSOURCE', 'm.cAlias + ".sum_uplata_dolga_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".sum_uplata_dolga_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_STR', 'COMMENTARY', 'Уплата остатка задолженности за прошлый год по страховой части'
GO

/****** Объект: Долг по накоп. части******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_DOLG_NAK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_DOLG_NAK', 'Долг по накоп. части', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_DOLG_NAK', NAME = 'Долг по накоп. части', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_DOLG_NAK'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'TITLE', 'Долг по накоп. части'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'CONTROLSOURCE', 'm.cAlias + ".sum_dolg_nak"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".sum_dolg_nak"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DOLG_NAK', 'COMMENTARY', 'Остаток задолженности за прошлый год по накопительной части'
GO

/****** Объект: Уплата долга по накопит. части******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_PLAT_DOLG_NAK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'Уплата долга по накопит. части', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', NAME = 'Уплата долга по накопит. части', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_PLAT_DOLG_NAK'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'TITLE', 'Уплата долга по накопит. части'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'CONTROLSOURCE', 'm.cAlias + ".sum_uplata_dolga_nak"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".sum_uplata_dolga_nak"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_PLAT_DOLG_NAK', 'COMMENTARY', 'Уплата остатка задолженности за прошлый год по страховой части'
GO



GO
/****** Объект: FOT******/
EXEC X_SET_PROP 'SD_EMPL_FOT', 'COMMENTARY', 'Способ формирования оклада: ПКГ - на основе базового оклада ПКГ и коэф, ЕТС - по ЕТС и квалификационному разряду, БОУ - по стоимости бюджетной образовательной услуги,Сумма - месячная ставка задаётся при вводе нагрузки.'
GO


GO
-- Отчет "Карточка-справка (ф. 417)"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REPORT_F417'

/*** Сам отчет ***/


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_F417'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REPORT_F417'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Карточка-справка (ф. 417)',3, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REPORT_F417',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REPORT_F417') 
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	DECLARE @nLINK INT
	SET @nLINK = CAST( @cText1 AS INT)
	EXEC SD_REP_F417 @cYear1, @nLINK, @nCheck1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#REPORT_F417'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KIRREPMAKERMULTISHEET.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(!task.Workmode("Mode70N"),"F-417.XLT",IIF(task.Workmode("Mode70N"),"F-0504417.XLT",""))'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	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_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #REPORT_F417
	@cYear1 VARCHAR(4)	/* Год */,
	@cText1 varchar(8000)	/* Лицо */,
	@nCheck1 int	/* Объединять начисления */
AS
BEGIN

	DECLARE @nLINK INT
	SET @nLINK = CAST( @cText1 AS INT)
	EXEC SD_REP_F417 @cYear1, @nLINK, @nCheck1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	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_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'KIRREPF417.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REPORT_F417') 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_F417'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REPORT_F417_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_F417'),
		'SQL_REPORT_F417_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_F417_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Лицо',3, 
					(Select link from object_var where code = 'SQL_REPORT_F417_NASTR_GR'),
					'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'17309'
						
						
						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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'1960'
						
						
						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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'17103'
						
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_F417_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_F417_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_YEARBOX'),
					'Год',2, 
					(Select link from object_var where code = 'SQL_REPORT_F417_NASTR_GR'),
					'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'FORMAT'),
							'9999'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'MASKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cYear1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'2011'
						
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_F417_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REPORT_F417_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'),
					'Объединять начисления',4, 
					(Select link from object_var where code = 'SQL_REPORT_F417_NASTR_GR'),
					'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_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_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REPORT_F417_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REPORT_F417_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "Дата наступления заданного стажа у сотрудников"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REP_SA_GET_STAGE_DATE'

/*** Сам отчет ***/

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var

CREATE TABLE #UPD_object_var (link_navigator int)

INSERT INTO #UPD_object_var (link_navigator)
SELECT  SN.LINK
FROM S_NAVIGATOR SN,OBJECT_VAR OV
WHERE SN.LINK_VAR = OV.LINK AND OV.CODE= 'SQL_REP_SA_GET_STAGE_DATE'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Дата наступления заданного стажа у сотрудников',104, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REP_SA_GET_STAGE_DATE',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE') 
	FROM S_NAVIGATOR S INNER JOIN #UPD_object_var U on S.LINK = U.link_navigator
GO

if object_id('tempdb..#UPD_object_var') is not null
	drop table #UPD_object_var
GO
/*** Свойства отчета ***/
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'INIT_OBJECT_METHOD')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'INIT_OBJECT_METHOD'),
	VALUE= 'm_print_query(nLink_Var)'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'VISIBLE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'VISIBLE'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'CHECK_VALUE_IN_TABLE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'AFTER_CHANGE_PROG_NASTR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_CHANGE_PROG_NASTR'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'BEFORE_CHANGE_PROG_NASTR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'BEFORE_CHANGE_PROG_NASTR'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_CENTER_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_CENTER_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_DATETIME')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_DATETIME'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_FOOTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FOOTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_LEFT_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_LEFT_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_PAGES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'NASTR_XL_RIGHT_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'NASTR_XL_RIGHT_HEADER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDFROM')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDFROM'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDINTO')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDINTO'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDSELECT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDSELECT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADDWHERE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADDWHERE'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_AFTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AFTER'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_BEFORE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'SET @cText1 = LTRIM(RTRIM(@cText1))

IF ISNUMERIC(LTRIM(RTRIM(@cText1))) = 0
	SET @cText1 = ''0''

IF LEN(@cText1) > 2	
	SET @cText1 = ''99''

EXEC dbo.SA_GET_STAGE_DATE
	@nSel_Spr1 /* Вид стажа */,
	@cText1 /* Количество лет */,
	@dDateB1 /* Начало периода */,
	@dDateE1 /* Конец перода */
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_DATETIME')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DATETIME'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_DISTINCT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_DISTINCT'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_FOOTER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FOOTER'),
	VALUE= '="Исполнитель                               " & User_FIO
                                 подпись'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_FREEZEPANES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_FREEZEPANES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_HEADER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_HEADER'),
	VALUE= '=User_Name'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_PAGES')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PAGES'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_PROCEDURE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SQL_REP_SA_GET_STAGE_DATE'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPMAKER')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPMAKER'),
	VALUE= 'KIRREPMAKER.XLS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"REP_Z_STAGE_DATE.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_REPORT_PATH')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT_PATH'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_SQL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SQL_REP_SA_GET_STAGE_DATE
	@nSel_Spr1 int	/* Вид стажа */,
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@cText1 VARCHAR(100)	/* Количество лет */
AS
BEGIN

SET @cText1 = LTRIM(RTRIM(@cText1))

IF ISNUMERIC(LTRIM(RTRIM(@cText1))) = 0
	SET @cText1 = ''0''

IF LEN(@cText1) > 2	
	SET @cText1 = ''99''

EXEC dbo.SA_GET_STAGE_DATE
	@nSel_Spr1 /* Вид стажа */,
	@cText1 /* Количество лет */,
	@dDateB1 /* Начало периода */,
	@dDateE1 /* Конец перода */


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_SYSTEM')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SYSTEM'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOP')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOP'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTAL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTAL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTALCOL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTALCOL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_TOTALROW')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_TOTALROW'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_AP_LIST')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_AP_LIST'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'EOD_PROTOCOL')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'EOD_PROTOCOL'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'AFTER_REPORT_PROG')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'AFTER_REPORT_PROG'),
	VALUE= ''
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'QUERY_ADD_MODULE')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'KirRepCommon.bas'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE') and  PROPERTY = (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_GET_STAGE_DATE'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE_G1P' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_NASTRS'),
		'Группа настроек',1, 
		(Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE'),
		'SQL_REP_SA_GET_STAGE_DATE_G1P',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE_G1P1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_LSEL_SPR'),
					'Вид стажа',2, 
					(Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P'),
					'SQL_REP_SA_GET_STAGE_DATE_G1P1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Вид стажа'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'LSel_Spr'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'EXPIR'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nSel_Spr1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'8'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'8'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'8'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'8'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(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_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							'med'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							'med'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							'med'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							'med'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							'GEN'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE_G1P2' 
					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_REP_SA_GET_STAGE_DATE_G1P'),
					'SQL_REP_SA_GET_STAGE_DATE_G1P2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'FORMAT'),
							'99'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Количество лет'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'TEXTBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@cText1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'VARCHAR(100)'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'10'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'10'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'10'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'10'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'10'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE_G1P3' 
					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'),
					'Начало периода',3, 
					(Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P'),
					'SQL_REP_SA_GET_STAGE_DATE_G1P3',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Начало периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'DATEBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@dDateB1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'datetime'
						
GO
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Начало расч. месяца'
						
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_GET_STAGE_DATE_G1P4' 
					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'),
					'Конец периода',4, 
					(Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P'),
					'SQL_REP_SA_GET_STAGE_DATE_G1P4',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Конец периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'DATEBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@dDateE1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'datetime'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Конец расч. месяца'
						
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_GET_STAGE_DATE_G1P4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO

/*НАСТРОЙКИ ТАРИФОВ ДЛЯ ИНВАЛИДОВ 2012 ГОДА*/


--Инвалиды (ОЗОИ)
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 = '20120101' and predel = 512000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20120101','ФСС РФ',512000, 1.9, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20120101','ФСС РФ',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 = '20120101' and predel = 512000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20120101','ФФОМС',512000, 2.3, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20120101','ФФОМС',999999999, 0, 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 512000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',512000, 16, 16, 10, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20120101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20120101','ПФ Страховая часть',999999999, 0, 0, 0, 3
GO

GO
/****** Объект: Месячная ставка******/
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='STO_WHT_PERC_M_STAVKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'STO_WHT_PERC_M_STAVKA', 'Месячная ставка', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='STO_W_HOURS_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'STO_WHT_PERC_M_STAVKA', NAME = 'Месячная ставка', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='STO_W_HOURS_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='STO_WHT_PERC_M_STAVKA'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'TITLE', 'Месячная ставка'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'CONTROLSOURCE', 'm.cAlias + ".M_STAVKA"'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'STORAGE', 'STO_WEEK_HOURS'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'SHORT_CODE_OBJ', 'M_STAVKA'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".M_STAVKA"'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'CONTROL_NAME_EDIT', 'CTRL_11'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'COMMENTARY', 'Сумма оплаты за полный месяц. От этой суммы будет рассчитываться сумма за часы нагрузки.'
GO

GO
EXEC X_SET_PROP 'STO_WHT_TAB', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("SA_EMPLS_W", oForm.ALIAS, "TAB,link_empl,LINK, FIO, POST_NAME,LINK_KBK,CODE_KBK,CODE_TYPE,FOT","tab,link_empl,link_tar_empl,fio,POST_NAME,LINK_KBK, CODE_KBK,CODE_TYPE,FOT", "", "", "(SACK = 0 OR SACK_PER = 1) and DATE_BEGIN IS NOT NULL AND DEP_LINK = " + oForm.cDEP_LINK, .T., 1, oForm, oObj, "")'
GO

GO
EXEC X_SET_PROP 'STO_W_HOURS_TABLE', 'SELECT_RECORDS_METHOD_EDIT', 'sa_exec_sp("SELECT 0 as CHECKED, 0 as DEL, 0 UPD, convert(bit,0) as LOCKED, link = link_wh,link_up = link_doc_wh,HOURS = fact,LINK_KBK = link_sfin,CODE_KBK = CODE_SFIN,* FROM dbo.sa_dict_wh_pays_empl(DEFAULT," + iif(type(''m.nLINK_EMPL'') = ''N'',STR(m.nLINK_EMPL),''-1'') +  "," +  iif(type(''m.nLINK_SOVM'') = ''N'',STR(m.nLINK_SOVM),''-1'')  +",default,default) where link_wh = " + iif(type(''m.nLINK'') = ''N'',STR(m.nLINK),''-1'') )'
GO
EXEC X_SET_PROP 'STO_W_HOURS_TABLE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''STO_W_HOURS_SAVE'', m.cAlias," link_up, link_empl,link_tar_empl, link_pay, link_les, t, link_paral, link_clas, hours, perc, LINK_KBK, SQLNULL(DATE_BEGIN), SQLNULL(DATE_END), NO_CALC,M_STAVKA",''STO_W_HOURS_TABLE'')'
GO
EXEC X_SET_PROP 'STO_WHT_PERC_M_STAVKA', 'FIELD_IN_ALIAS', '3'
GO

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_TABESL_EMPL_FILL_BUFFER_CORRECT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_TABESL_EMPL_FILL_BUFFER_CORRECT]

GO

CREATE PROCEDURE DBO.SA_TABESL_EMPL_FILL_BUFFER_CORRECT (@BUFFERCODE VARCHAR(10), @LINK INT, @LINK_SOVM INT = -1, @OSN TINYINT = 0)
/*
СОХРАНЕНИЯ СПИСКА СОТРУДНИКОВ В ТАБЕЛЬ ИЗ БУФФЕРА
*/
AS
--@LINK_SOVM  = -1, ЕСЛИ ДОБАВЛЕНИЕ ВСЕГО ДЛЯ СОТРУДНИКА
-- >= 0, ЕЛСИ ЗАПОЛНИТЬ ЗАНОВО ДЛЯ СОТРУДНИКА
DECLARE @VARKSERROR	TINYINT,
			@VARKSSQLERROR	INT,
			@VARKSSTRVALUE	VARCHAR(7000),
			@VARKSTRANCOUNT	INT

SET @VARKSTRANCOUNT = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

SET @LINK_SOVM = COALESCE(@LINK_SOVM,-1)

DELETE FROM DBO.BUFFER
WHERE 
		@LINK_SOVM = -1
	AND
		RTRIM(LTRIM(ID)) = RTRIM(LTRIM(@BUFFERCODE))
	AND 
		EXISTS (SELECT * FROM DBO.TABELS S WHERE S.LINK_DOC = @LINK AND S.LINK_EMPL = DBO.BUFFER.LINK)
		
----------------		
CREATE TABLE #LOCAL_BUFFER(LINK INT)		
CREATE INDEX #LOCAL_BUFFER_LINK ON #LOCAL_BUFFER (LINK ASC)

INSERT INTO #LOCAL_BUFFER (LINK)
SELECT B.LINK FROM DBO.BUFFER B WHERE RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@BUFFERCODE))

---------------
DECLARE @PERIOD DATETIME, @COMMENT VARCHAR(254), @DEP_LINK INT
SELECT TOP 1 @PERIOD = DATE_CALC, @COMMENT = COMMENTARY, @DEP_LINK = LINK_DEP FROM SDOC WHERE LINK = @LINK

INSERT INTO TABELS WITH (ROWLOCK) (LINK_EMPL, LINK_DOC, PERIOD)
SELECT LINK, @LINK, @PERIOD 
FROM #LOCAL_BUFFER B 
WHERE NOT EXISTS (SELECT * FROM DBO.TABELS T WHERE T.LINK_DOC = @LINK AND T.LINK_EMPL = B.LINK)

--ФОРМИРОВАНИЕ ТАБЕЛЯ

DECLARE @M INT, @Y INT
SELECT @M = MONTH(@PERIOD), @Y = YEAR(@PERIOD)
CREATE TABLE #EMPL_DAYS (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, DATE1 DATETIME, [DAY] TINYINT, HOURS NUMERIC(5,2), DAY_TIP INT,
			 LINK_UP INT, SYMB VARCHAR(4), [NAME] VARCHAR(60), DOP_TAB TINYINT, DATEACCEPT DATETIME, DATESACK DATETIME, GRAPH_LINK INT, ETS_RAZR TINYINT)
INSERT INTO #EMPL_DAYS
EXEC DBO.SA_TABEL_FILL_EMPL @Y, @M, @LINK, @DEP_LINK, @BUFFERCODE

---СВЕДЕНИЯ О НЕЯВКАХ
CREATE TABLE #NEYAVKI (LINK_EMPL INT, [DAY] TINYINT, DAY_TIP INT, SYMB VARCHAR(4))
INSERT INTO #NEYAVKI (LINK_EMPL, [DAY], DAY_TIP, SYMB)
SELECT D.LINK_EMPL, D.[DAY], D.DAY_TIP, D.SYMB --MAX(D.DAY_TIP), MAX(D.SYMB)
FROM #EMPL_DAYS D INNER JOIN DBO.TYP_DAYS T ON T.WORK_D <> 1 AND T.LINK = D.DAY_TIP
WHERE D.DOP_TAB = 1 AND D.LINK_WORK_TYPE = (SELECT TOP 1 LINK FROM DBO.TABEL_NASTR2 WHERE CODE = 'ОСН')

---
CREATE INDEX #NEYAVKI_LINK_EMPL ON #NEYAVKI (LINK_EMPL ASC)

DELETE FROM DBO.TABELS_N
WHERE LINK_UP IN (SELECT DISTINCT T.LINK FROM DBO.TABELS T INNER JOIN #LOCAL_BUFFER B ON T.LINK_EMPL = B.LINK WHERE T.LINK_DOC = @LINK)

--ЗАПИСАТЬ ВСЕ НЕЯВКИ
INSERT INTO DBO.TABELS_N
(LINK_UP,D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31)
SELECT DISTINCT LINK,
	D1 = D1.DAY_TIP,
	D2 = D2.DAY_TIP,
	D3 = D3.DAY_TIP,
	D4 = D4.DAY_TIP,
	D5 = D5.DAY_TIP,
	D6 = D6.DAY_TIP,
	D7 = D7.DAY_TIP,
	D8 = D8.DAY_TIP,
	D9 = D9.DAY_TIP,
	D10 = D10.DAY_TIP,
	D11 = D11.DAY_TIP,
	D12 = D12.DAY_TIP,
	D13 = D13.DAY_TIP,
	D14 = D14.DAY_TIP,
	D15 = D15.DAY_TIP,
	D16 = D16.DAY_TIP,
	D17 = D17.DAY_TIP,
	D18 = D18.DAY_TIP,
	D19 = D19.DAY_TIP,
	D20 = D20.DAY_TIP,
	D21 = D21.DAY_TIP,
	D22 = D22.DAY_TIP,
	D23 = D23.DAY_TIP,
	D24 = D24.DAY_TIP,
	D25 = D25.DAY_TIP,
	D26 = D26.DAY_TIP,
	D27 = D27.DAY_TIP,
	D28 = D28.DAY_TIP,
	D29 = D29.DAY_TIP,
	D30 = D30.DAY_TIP,
	D31 = D31.DAY_TIP
FROM DBO.TABELS E
	LEFT JOIN #NEYAVKI D1 ON D1.DAY = 1 AND E.LINK_EMPL = D1.LINK_EMPL
	LEFT JOIN #NEYAVKI D2 ON D2.DAY = 2 AND E.LINK_EMPL = D2.LINK_EMPL
	LEFT JOIN #NEYAVKI D3 ON D3.DAY = 3 AND E.LINK_EMPL = D3.LINK_EMPL
	LEFT JOIN #NEYAVKI D4 ON D4.DAY = 4 AND E.LINK_EMPL = D4.LINK_EMPL
	LEFT JOIN #NEYAVKI D5 ON D5.DAY = 5 AND E.LINK_EMPL = D5.LINK_EMPL
	LEFT JOIN #NEYAVKI D6 ON D6.DAY = 6 AND E.LINK_EMPL = D6.LINK_EMPL
	LEFT JOIN #NEYAVKI D7 ON D7.DAY = 7 AND E.LINK_EMPL = D7.LINK_EMPL
	LEFT JOIN #NEYAVKI D8 ON D8.DAY = 8 AND E.LINK_EMPL = D8.LINK_EMPL
	LEFT JOIN #NEYAVKI D9 ON D9.DAY = 9 AND E.LINK_EMPL = D9.LINK_EMPL
	LEFT JOIN #NEYAVKI D10 ON D10.DAY = 10 AND E.LINK_EMPL = D10.LINK_EMPL
	LEFT JOIN #NEYAVKI D11 ON D11.DAY = 11 AND E.LINK_EMPL = D11.LINK_EMPL
	LEFT JOIN #NEYAVKI D12 ON D12.DAY = 12 AND E.LINK_EMPL = D12.LINK_EMPL
	LEFT JOIN #NEYAVKI D13 ON D13.DAY = 13 AND E.LINK_EMPL = D13.LINK_EMPL
	LEFT JOIN #NEYAVKI D14 ON D14.DAY = 14 AND E.LINK_EMPL = D14.LINK_EMPL
	LEFT JOIN #NEYAVKI D15 ON D15.DAY = 15 AND E.LINK_EMPL = D15.LINK_EMPL
	LEFT JOIN #NEYAVKI D16 ON D16.DAY = 16 AND E.LINK_EMPL = D16.LINK_EMPL
	LEFT JOIN #NEYAVKI D17 ON D17.DAY = 17 AND E.LINK_EMPL = D17.LINK_EMPL
	LEFT JOIN #NEYAVKI D18 ON D18.DAY = 18 AND E.LINK_EMPL = D18.LINK_EMPL
	LEFT JOIN #NEYAVKI D19 ON D19.DAY = 19 AND E.LINK_EMPL = D19.LINK_EMPL
	LEFT JOIN #NEYAVKI D20 ON D20.DAY = 20 AND E.LINK_EMPL = D20.LINK_EMPL
	LEFT JOIN #NEYAVKI D21 ON D21.DAY = 21 AND E.LINK_EMPL = D21.LINK_EMPL
	LEFT JOIN #NEYAVKI D22 ON D22.DAY = 22 AND E.LINK_EMPL = D22.LINK_EMPL
	LEFT JOIN #NEYAVKI D23 ON D23.DAY = 23 AND E.LINK_EMPL = D23.LINK_EMPL
	LEFT JOIN #NEYAVKI D24 ON D24.DAY = 24 AND E.LINK_EMPL = D24.LINK_EMPL
	LEFT JOIN #NEYAVKI D25 ON D25.DAY = 25 AND E.LINK_EMPL = D25.LINK_EMPL
	LEFT JOIN #NEYAVKI D26 ON D26.DAY = 26 AND E.LINK_EMPL = D26.LINK_EMPL
	LEFT JOIN #NEYAVKI D27 ON D27.DAY = 27 AND E.LINK_EMPL = D27.LINK_EMPL
	LEFT JOIN #NEYAVKI D28 ON D28.DAY = 28 AND E.LINK_EMPL = D28.LINK_EMPL
	LEFT JOIN #NEYAVKI D29 ON D29.DAY = 29 AND E.LINK_EMPL = D29.LINK_EMPL
	LEFT JOIN #NEYAVKI D30 ON D30.DAY = 30 AND E.LINK_EMPL = D30.LINK_EMPL
	LEFT JOIN #NEYAVKI D31 ON D31.DAY = 31 AND E.LINK_EMPL = D31.LINK_EMPL
WHERE
	LINK_DOC = @LINK
	AND
	NOT EXISTS (SELECT * FROM DBO.TABELS_N N WHERE N.LINK_UP = E.LINK)

---
DROP TABLE #NEYAVKI


---СВЕДЕНИЯ ОБ ОТРАБОТАННОМ ВРЕМЕНИ
CREATE TABLE #WORK (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, [DAY] TINYINT, HOURS NUMERIC(5,2), DAY_TIP INT, DATEACCEPT DATETIME, DATESACK DATETIME, GRAPH_LINK INT, ETS_RAZR TINYINT)
INSERT INTO #WORK (LINK_EMPL, LINK_WORK, LINK_WORK_TYPE, [DAY], HOURS, DAY_TIP, DATEACCEPT, DATESACK, GRAPH_LINK, ETS_RAZR)
SELECT D.LINK_EMPL, LINK_WORK, LINK_WORK_TYPE, D.[DAY], D.HOURS, D.DAY_TIP, DATEACCEPT, DATESACK, GRAPH_LINK, ETS_RAZR
FROM #EMPL_DAYS D INNER JOIN DBO.TYP_DAYS T ON T.WORK_D = 1 AND T.LINK = D.DAY_TIP
---
CREATE INDEX #WORK_LINK_EMPL ON #WORK (LINK_EMPL ASC)

---ОБЕСПЕЧИМ НАЛИЧИЕ ВСЕХ ЧИСЕЛ МЕСЯЦА
DECLARE @I INT
SET @I = 1
WHILE @I <= 31 BEGIN
	INSERT INTO #WORK (LINK_EMPL, [DAY], HOURS, DAY_TIP)
	VALUES (0, @I, 0, 0)
	SET @I = @I + 1
END

--
DECLARE @VARKSTABLE VARCHAR(100)
EXEC X_GET_TABLE_NAME @VARKSTABLE OUTPUT

EXEC DBO.CROSSTAB @TABLE = #WORK, @TABLE2 = @VARKSTABLE, @ONROWS = 'LINK_EMPL,DAY_TIP,LINK_WORK,LINK_WORK_TYPE', @ONCOLS = DAY, @SUMCOL = HOURS

CREATE TABLE #WORK1 (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, DAY_TIP INT, C1 NUMERIC(5,2), C10 NUMERIC(5,2), C11 NUMERIC(5,2), C12 NUMERIC(5,2), C13 NUMERIC(5,2), C14 NUMERIC(5,2), C15 NUMERIC(5,2), C16 NUMERIC(5,2), C17 NUMERIC(5,2), C18 NUMERIC(5,2), C19 NUMERIC(5,2), C2 NUMERIC(5,2), C20 NUMERIC(5,2), C21 NUMERIC(5,2), C22 NUMERIC(5,2), C23 NUMERIC(5,2), C24 NUMERIC(5,2), C25 NUMERIC(5,2), C26 NUMERIC(5,2), C27 NUMERIC(5,2), C28 NUMERIC(5,2), C29 NUMERIC(5,2), C3 NUMERIC(5,2), C30 NUMERIC(5,2), C31 NUMERIC(5,2), C4 NUMERIC(5,2), C5 NUMERIC(5,2), C6 NUMERIC(5,2), C7 NUMERIC(5,2), C8 NUMERIC(5,2), C9  NUMERIC(5,2))

EXEC ( '
INSERT INTO #WORK1 (LINK_EMPL,LINK_WORK,LINK_WORK_TYPE,DAY_TIP,C1,C10,C11,C12,C13,C14,C15,C16,C17,C18,C19,C2,C20,C21,C22,C23,C24,C25,C26,C27,C28,C29,C3,C30,C31,C4,C5,C6,C7,C8,C9)
SELECT LINK_EMPL,LINK_WORK,LINK_WORK_TYPE,DAY_TIP,C1,C10,C11,C12,C13,C14,C15,C16,C17,C18,C19,C2,C20,C21,C22,C23,C24,C25,C26,C27,C28,C29,C3,C30,C31,C4,C5,C6,C7,C8,C9
FROM ' + @VARKSTABLE  + ' WHERE LINK_EMPL > 0')

EXEC ('DROP TABLE ' + @VARKSTABLE)

UPDATE W
	SET W.D27 = W1.C27
FROM 
	dbo.TABELS_W W
	INNER JOIN DBO.TABELS T ON T.LINK = W.LINK_UP
	INNER JOIN #WORK1 W1 ON T.LINK_EMPL = W1.LINK_EMPL AND ISNULL(W.LINK_SOVM,0) = ISNULL(W1.LINK_WORK,0) 
WHERE
	T.LINK_DOC = @LINK
	AND
	W1.DAY_TIP IS NOT NULL
	--AND
	--W.D27 = 0

	
WHILE @@TRANCOUNT > @VARKSTRANCOUNT
	COMMIT TRAN
RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_TABESL_EMPL_FILL_BUFFER_CORRECT] TO PUBLIC

GO


DECLARE @S VARCHAR(15), @V1 VARCHAR(5), @V2 VARCHAR(5), @R VARCHAR(5), @FS varchar(5), @F int, @E INT, @VRS varchar(100) 
EXEC X_GET_PROP 'PROJECT','VERSION_FIX', @FS OUTPUT 
SET @F = convert(int, @FS) 
EXEC X_GET_PROP 'PROJECT','SIGNATURE', @S OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_MAJOR', @V1 OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_MINOR', @V2 OUTPUT 
EXEC X_GET_PROP 'PROJECT','VERSION_RELEASE', @R OUTPUT 
SET @VRS = ISNULL(RTRIM(@V1)+'.'+RTRIM(@V2), '') 

IF @S = 'SMETA' AND @VRS = '12.11' AND @F = 0
BEGIN
	DECLARE @Cur1 CURSOR, @LINK INT, @cWHERE VARCHAR(254)
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT LINK FROM dbo.SA_TABELS WHERE YEAR(DATE) <= 2011 ORDER BY DATE

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @LINK
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			--SELECT DATE, NUMBER, COMMENTARY FROM dbo.SDOC WHERE LINK = @LINK
			
			SET @cWHERE = 'LINK_DOC = ' + CONVERT(VARCHAR(20),@LINK)
			
			EXEC dbo.BufferPushTable 'TABELS', '_E0YR11Q', 'LINK_EMPL', @cWHERE
			
			EXEC dbo.SA_TABESL_EMPL_FILL_BUFFER_CORRECT '_E0YR11Q',@LINK,0		
			
			EXEC dbo.BufferClear '_E0YR11Q'

		END

		FETCH NEXT FROM @Cur1 INTO @LINK
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1
	
END	
	
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_TABESL_EMPL_FILL_BUFFER_CORRECT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_TABESL_EMPL_FILL_BUFFER_CORRECT]

GO


GO
-- Справочник счетов "Расчеты с организациями --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BK_SUBACCOUNTS302_01', 'Справочник счетов "Расчеты с организациями"', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORTS_ACCT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BK_SUBACCOUNTS302_01', NAME = 'Справочник счетов "Расчеты с организациями"', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORTS_ACCT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BK_SUBACCOUNTS302_01'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_SUBACCOUNTS_MARKER20')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_SUBACCOUNTS_MARKER20', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_SUBACCOUNTS_MARKER20', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_SUBACCOUNTS_MARKER20'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_SUBACCOUNTS_CODE20')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_SUBACCOUNTS_CODE20', 'Субсчет', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_SUBACCOUNTS_CODE20', NAME = 'Субсчет', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_SUBACCOUNTS_CODE20'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_SUBACCOUNT_NAME20')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_SUBACCOUNT_NAME20', 'Наименование субсчета', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_SUBACCOUNT_NAME20', NAME = 'Наименование субсчета', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_SUBACCOUNTS302_01'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_SUBACCOUNT_NAME20'
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'SELECT_RECORDS_METHOD', 'SQL.EXEC( "EXEC BK_GET_OTBOR_ACCOUNTS1 ''206, 207, 301, 302'',  '''', ''" + m.cFields + "''", m.cAlias)'
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'SELECT_RECORDS_METHOD_EDIT', ''
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'MSG_SEL_ALL', '[Отобраны все субсчета]'
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'MSG_SEL_ONE', 'CODE + [-] + NAME'
GO
EXEC X_SET_PROP 'BK_SUBACCOUNTS302_01', 'SERVER_TABLE_NAME', 'S_ACCOUNTS'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_MARKER20', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_MARKER20', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_MARKER20', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_CODE20', 'TITLE', 'Субсчет'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_CODE20', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_CODE20', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNTS_CODE20', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNT_NAME20', 'TITLE', 'Наименование субсчета'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNT_NAME20', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNT_NAME20', 'CONTROLSOURCE', 'm.cALias+".NAME"'
GO
EXEC X_SET_PROP 'DICT_SUBACCOUNT_NAME20', 'SHORT_CODE_OBJ', 'NAME'
GO




GO
-- Удаление лишних полей из таблицы МЗ_НДС --
DELETE FROM dbo.S_OBJECTS WHERE CODE = 'DOC_TABLE_MZ_NDS_COUNTRY'
GO

GO
--- Страны мира (ОКСМ) ---
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_COUNTRY', 'Страны мира (ОКСМ)', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASSIF_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_COUNTRY', NAME = 'Страны мира (ОКСМ)', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASSIF_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICTIONARY_COUNTRY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_FULL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_FULL_NAME', 'Полное наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_FULL_NAME', NAME = 'Полное наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_FULL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_CODE2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_CODE2', 'Код2', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_CODE2', NAME = 'Код2', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_CODE2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTION_COUNTRY_CODE3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTION_COUNTRY_CODE3', 'Код3', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTION_COUNTRY_CODE3', NAME = 'Код3', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_COUNTRY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTION_COUNTRY_CODE3'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'TITLE', 'Страны мира'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'INIT_OBJECT_METHOD', 'X_SPISOK(''DICTIONARY_COUNTRY'')'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_COUNTRY", "BK_DELETE_COUNTRY", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BK_UPDATE_KL_COUNTRY'', m.cAlias," CODE, CODE2, CODE3, NAME, FULL_NAME", "DICTIONARY_COUNTRY")'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'EDIT_OBJECT_METHOD', 'X_BROW()'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("DICTIONARY_COUNTRY")'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("DICTIONARY_COUNTRY")'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'SERVER_TABLE_NAME', 'KL_COUNTRY'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'HELP_TOPIC', 'Страны мира'
GO
EXEC X_SET_PROP 'DICTIONARY_COUNTRY', 'OPERATION_MASK', '31'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_MARKER', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'CONTROLSOURCE', 'm.cAlias+".Code"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Code"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'CONTROL_NAME_EDIT', 'ATxt1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'TYPE_FIELD_DICT', 'varchar(150)'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_NAME', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'TITLE', 'Полное наименование'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'CONTROLSOURCE', 'm.cAlias+".FULL_NAME"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'SHORT_CODE_OBJ', 'FULL_NAME'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".FULL_NAME"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_FULL_NAME', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'TITLE', 'Код (альфа-2)'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'CONTROLSOURCE', 'm.cAlias+".Code2"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Code2"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE2', 'CONTROL_NAME_EDIT', 'ATxt4'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'TITLE', 'Код (альфа-3)'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'CONTROLSOURCE', 'm.cAlias+".Code3"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'CONTROLSOURCE_EDIT', 'm.cAlias+".Code3"'
GO
EXEC X_SET_PROP 'DICTION_COUNTRY_CODE3', 'CONTROL_NAME_EDIT', 'ATxt5'
GO




GO
/****** Объект: Корректировочный счет-фактура (полученный)******/
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_INVOICE_COR_IN', 'Корректировочный счет-фактура (полученный)', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_INVOICE_COR_IN', NAME = 'Корректировочный счет-фактура (полученный)', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_INVOICE_COR_IN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_OSN_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_OSN_LINK', 'Ссылка на основание', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_OSN_LINK', NAME = 'Ссылка на основание', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_OSN_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_OSN_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_OSN_NUM', 'Номер документа основания', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_OSN_NUM', NAME = 'Номер документа основания', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_OSN_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_OSN_INFO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_OSN_INFO', 'Вид документа основания', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_OSN_INFO', NAME = 'Вид документа основания', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_OSN_INFO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_SEL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_SEL_LINK', 'Продавец', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_SEL_LINK', NAME = 'Продавец', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_SEL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_SEL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_SEL_CODE', 'Код продавца', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_SEL_CODE', NAME = 'Код продавца', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_SEL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_SEL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_SEL_NAME', 'Наименование продавца', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_SEL_NAME', NAME = 'Наименование продавца', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_SEL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_BY_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_BY_NAME', 'Наименование покупателя', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_BY_NAME', NAME = 'Наименование покупателя', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_BY_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_INBOOKS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_INBOOKS', 'Включать в книгу покупок-продаж', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_INBOOKS', NAME = 'Включать в книгу покупок-продаж', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_INBOOKS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_COMMENT', 'Комментарий', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_COMMENT', NAME = 'Комментарий', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_COR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_COR_NUM', 'Номер исправления', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_COR_NUM', NAME = 'Номер исправления', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_COR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_IN_COR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_IN_COR_DATE', 'Дата исправления', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_IN_COR_DATE', NAME = 'Дата исправления', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_IN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_IN_COR_DATE'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'TITLE', 'Корректировочный счет-фактура (полученный)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOCUMENTS_INVOICE_COR_IN", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BK_SAVE_DOC_INVOICE_COR_IN'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL(OSN_LINK), COR_NUM, SQLNULL (COR_DATE), INBOOK", "DOCUMENTS_INVOICE_COR_IN")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_INVOICE_COR")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BK_INVOICE_COR_IN'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOCUMENTS_INVOICE_COR_IN")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOCUMENTS_INVOICE_COR_IN")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'QUERY_REPORT', 'INVOICE_COR.XLT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_IN', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'REFERENCE_TO_DICT', 'BD_OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'SHORT_CODE_OBJ', 'OSN_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'TITLE', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'EDIT_OBJECT_METHOD', 'BK_VIBOR_OSNOV(oForm.Alias, "LINK, NUMBER, INFO", "OSN_LINK, OSN_NUM, OSN_INFO","", EVALUATE (oForm.Alias + ".DEP_LINK"), oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'CONTROLSOURCE', 'm.cAlias + ".OSN_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'TYPE_FIELD_DICT', 'varchar(25)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'SHORT_CODE_OBJ', 'OSN_NUM'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSN_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'CONTROL_NAME', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_NUM', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'TITLE', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'CONTROLSOURCE', 'm.cAlias + ".OSN_INFO"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'TYPE_FIELD_DICT', 'varchar (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'SHORT_CODE_OBJ', 'OSN_INFO'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSN_INFO"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'CONTROL_NAME', 'ATxtN2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_OSN_INFO', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'SHORT_CODE_OBJ', 'SEL_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'CONTROLSOURCE', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'REFERENCE_TO_DICT', 'DOC_INVOICE_COR_IN_SEL_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'SHORT_CODE_OBJ', 'SEL_CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'CONTROLSOURCE', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'REFERENCE_TO_DICT', 'DOC_INVOICE_COR_IN_SEL_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'SHORT_CODE_OBJ', 'SEL_NAME'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_SEL_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'CONTROLSOURCE', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_BY_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'TITLE', 'Включать в книгу покупок/продаж'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'CONTROLSOURCE', 'm.cAlias + ".INBOOK"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'SHORT_CODE_OBJ', 'INBOOK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".INBOOK"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'CONTROL_NAME', 'CHECK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_INBOOKS', 'CONTROL_NAME_EDIT', 'CHECK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'CONTROLSOURCE', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COMMENT', 'CONTROL_NAME_EDIT', 'txtComment'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'TITLE', 'Исправление №'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'CONTROLSOURCE', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_NUM', 'CONTROL_NAME_EDIT', 'ATXT41'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'TITLE', 'от'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'CONTROLSOURCE', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_IN_COR_DATE', 'CONTROL_NAME_EDIT', 'Aseldate42'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_INVOICE_COR_IN', 'Смета-КС', 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 = 'FACTURA_DOC')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_COR_IN')

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 = 'FACTURA_DOC'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'DOCUMENTS_INVOICE_COR_IN'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'DOCUMENTS_INVOICE_COR_IN', 'Корректировочный счет-фактура (полученный)', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO




GO
/****** Объект: Корректировочный счет-фактура (выданный)******/
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_INVOICE_COR_OUT', 'Корректировочный счет-фактура (выданный)', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_INVOICE_COR_OUT', NAME = 'Корректировочный счет-фактура (выданный)', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_INVOICE_COR_OUT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_OSN_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_OSN_LINK', 'Ссылка на основание', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_OSN_LINK', NAME = 'Ссылка на основание', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_OSN_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_OSN_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_OSN_NUM', 'Номер документа основания', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_OSN_NUM', NAME = 'Номер документа основания', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_OSN_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_OSN_INFO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_OSN_INFO', 'Вид документа основания', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_OSN_INFO', NAME = 'Вид документа основания', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_OSN_INFO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_BUY_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_BUY_LINK', 'Продавец', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_BUY_LINK', NAME = 'Продавец', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_BUY_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_BUY_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_BUY_CODE', 'Код покупателя', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_BUY_CODE', NAME = 'Код покупателя', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_BUY_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_BUY_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_BUY_NAME', 'Наименование покупателя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_BUY_NAME', NAME = 'Наименование покупателя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_BUY_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_SEL_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_SEL_NAME', 'Наименование продавца', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_SEL_NAME', NAME = 'Наименование продавца', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_SEL_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_INBOOKS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_INBOOKS', 'Включать в книгу покупок-продаж', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_INBOOKS', NAME = 'Включать в книгу покупок-продаж', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_INBOOKS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_COMMENT', 'Комментарий', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_COMMENT', NAME = 'Комментарий', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_COR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_COR_NUM', 'Номер исправления', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_COR_NUM', NAME = 'Номер исправления', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_COR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_COR_OUT_COR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_COR_OUT_COR_DATE', 'Дата исправления', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_COR_OUT_COR_DATE', NAME = 'Дата исправления', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_COR_OUT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_COR_OUT_COR_DATE'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'TITLE', 'Корректировочный счет-фактура (выданный)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOCUMENTS_INVOICE_COR_OUT", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BK_SAVE_DOC_INVOICE_COR_OUT'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL(OSN_LINK), COR_NUM, SQLNULL (COR_DATE), INBOOK", "DOCUMENTS_INVOICE_COR_OUT")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_INVOICE_COR")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BK_INVOICE_COR_IN'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOCUMENTS_INVOICE_COR_OUT")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOCUMENTS_INVOICE_COR_OUT")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'QUERY_REPORT', 'INVOICE_COR.XLT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_COR_OUT', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'REFERENCE_TO_DICT', 'BD_OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'SHORT_CODE_OBJ', 'OSN_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'TITLE', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'EDIT_OBJECT_METHOD', 'BK_VIBOR_OSNOV(oForm.Alias, "LINK, NUMBER, INFO", "OSN_LINK, OSN_NUM, OSN_INFO","", EVALUATE (oForm.Alias + ".DEP_LINK"), oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'CONTROLSOURCE', 'm.cAlias + ".OSN_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'TYPE_FIELD_DICT', 'varchar(25)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'SHORT_CODE_OBJ', 'OSN_NUM'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSN_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'CONTROL_NAME', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_NUM', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'TITLE', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'CONTROLSOURCE', 'm.cAlias + ".OSN_INFO"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'TYPE_FIELD_DICT', 'varchar (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'SHORT_CODE_OBJ', 'OSN_INFO'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSN_INFO"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'CONTROL_NAME', 'ATxtN2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_OSN_INFO', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'SHORT_CODE_OBJ', 'BUY_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "BUY_LINK, BUY_CODE, BUY_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'CONTROLSOURCE', 'm.cALIAS+".BUY_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".BUY_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'CONTROLSOURCE', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_BUY_NAME', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_SEL_NAME', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_SEL_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_SEL_NAME', 'CONTROLSOURCE', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_SEL_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_SEL_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'TITLE', 'Включать в книгу покупок/продаж'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'CONTROLSOURCE', 'm.cAlias + ".INBOOK"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'SHORT_CODE_OBJ', 'INBOOK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".INBOOK"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'CONTROL_NAME', 'CHECK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_INBOOKS', 'CONTROL_NAME_EDIT', 'CHECK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'CONTROLSOURCE', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COMMENT', 'CONTROL_NAME_EDIT', 'txtComment'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'TITLE', 'Исправление №'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'CONTROLSOURCE', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_NUM', 'CONTROL_NAME_EDIT', 'ATXT41'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'TITLE', 'от'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'CONTROLSOURCE', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_COR_OUT_COR_DATE', 'CONTROL_NAME_EDIT', 'Aseldate42'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_INVOICE_COR_OUT', 'Смета-КС', 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 = 'FACTURA_DOC')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_COR_OUT')

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 = 'FACTURA_DOC'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'DOCUMENTS_INVOICE_COR_OUT'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'DOCUMENTS_INVOICE_COR_OUT', 'Корректировочный счет-фактура (выданный)', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO




GO
-- Счет-фактура выданный --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_INVOICE_ISSUED', 'Счет-фактура выданный', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_INVOICE_ISSUED', NAME = 'Счет-фактура выданный', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_INVOICE_ISSUED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_LINK', 'Продавец', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_LINK', NAME = 'Продавец', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_CODE', 'Код продавца', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_CODE', NAME = 'Код продавца', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_NAME', 'Наименование продавца', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_NAME', NAME = 'Наименование продавца', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELF_CONSIGNOR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELF_CONSIGNOR', 'Он же грузоотправитель', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELF_CONSIGNOR', NAME = 'Он же грузоотправитель', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELF_CONSIGNOR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNOR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNOR_LINK', 'Грузоотправитель', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNOR_LINK', NAME = 'Грузоотправитель', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNOR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_CODE01')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_CODE01', 'Код грузоотправителя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_CODE01', NAME = 'Код грузоотправителя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_CODE01'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_NAME01')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_NAME01', 'Наименование грузоотправителя', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_NAME01', NAME = 'Наименование грузоотправителя', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_NAME01'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ISSUED_PRODUCER_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ISSUED_PRODUCER_LINK', 'Производитель', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ISSUED_PRODUCER_LINK', NAME = 'Производитель', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ISSUED_PRODUCER_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ISSUED_PRODUCER_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ISSUED_PRODUCER_CODE', 'Код производителя', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ISSUED_PRODUCER_CODE', NAME = 'Код производителя', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ISSUED_PRODUCER_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ISSUED_PRODUCER_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ISSUED_PRODUCER_NAME', 'Наименование производителя', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ISSUED_PRODUCER_NAME', NAME = 'Наименование производителя', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ISSUED_PRODUCER_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_LINK', 'Покупатель', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_LINK', NAME = 'Покупатель', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_CODE', 'Код покупателя', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_CODE', NAME = 'Код покупателя', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_NAME', 'Наименование покупателя', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_NAME', NAME = 'Наименование покупателя', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELF_CONSIGNEE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELF_CONSIGNEE', 'Он же грузополучатель', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELF_CONSIGNEE', NAME = 'Он же грузополучатель', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELF_CONSIGNEE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_LINK', 'Грузополучатель', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_LINK', NAME = 'Грузополучатель', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_CODE', 'Код грузополучателя', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_CODE', NAME = 'Код грузополучателя', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_NAME', 'Наименование грузополучателя', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_NAME', NAME = 'Наименование грузополучателя', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PAYS_LINK_ISSUED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PAYS_LINK_ISSUED', 'Ссылка на платежку', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PAYS_LINK_ISSUED', NAME = 'Ссылка на платежку', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PAYS_LINK_ISSUED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NUMBER_BASE_DOCUMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NUMBER_BASE_DOCUMENT', 'Номер платежно-расчетного документа', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NUMBER_BASE_DOCUMENT', NAME = 'Номер платежно-расчетного документа', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NUMBER_BASE_DOCUMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DATE_BASE_DOCUMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DATE_BASE_DOCUMENT', 'Дата платежно-расчетного документа', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DATE_BASE_DOCUMENT', NAME = 'Дата платежно-расчетного документа', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DATE_BASE_DOCUMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_ISSUED_NALOG_DOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_ISSUED_NALOG_DOC', 'Итоговая сумма налога по документу', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_ISSUED_NALOG_DOC', NAME = 'Итоговая сумма налога по документу', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_ISSUED_NALOG_DOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_ISSUED_DOG_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_ISSUED_DOG_LINK', 'Ссылка на договор', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_ISSUED_DOG_LINK', NAME = 'Ссылка на договор', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_ISSUED_DOG_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_ISSUED_DOG_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_ISSUED_DOG_NUM', 'Номер договора', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_ISSUED_DOG_NUM', NAME = 'Номер договора', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_ISSUED_DOG_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BOOK_SALES_ISSUED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BOOK_SALES_ISSUED', 'Включать в книгу продаж', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BOOK_SALES_ISSUED', NAME = 'Включать в книгу продаж', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BOOK_SALES_ISSUED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_TAX')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_TAX', 'Ставка НДС', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_TAX', NAME = 'Ставка НДС', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_TAX'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_COMMENT', 'Комментарий', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_COMMENT', NAME = 'Комментарий', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_ISSUED_COR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_ISSUED_COR_NUM', 'Номер исправления', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_ISSUED_COR_NUM', NAME = 'Номер исправления', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_ISSUED_COR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_ISSUED_COR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_ISSUED_COR_DATE', 'Дата исправления', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_ISSUED_COR_DATE', NAME = 'Дата исправления', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_ISSUED_COR_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_OPT', 'Настройки счета-фактуры', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_OPT', NAME = 'Настройки счета-фактуры', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_OPT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_REFERENCE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_REFERENCE', 'Междокументные связи', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_REFERENCE', NAME = 'Междокументные связи', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_ISSUED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_REFERENCE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NASTR_INVOICE_REPORT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NASTR_INVOICE_REPORT', 'Бланк документа', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NASTR_INVOICE_REPORT', NAME = 'Бланк документа', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NASTR_INVOICE_REPORT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_LINK_TO1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_LINK_TO1', 'Ссылка на операцию (номенклатура)', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_LINK_TO1', NAME = 'Ссылка на операцию (номенклатура)', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_LINK_TO1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_NAME_TO1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_NAME_TO1', 'Наим тип. опер. (номенклатура)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_NAME_TO1', NAME = 'Наим тип. опер. (номенклатура)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_NAME_TO1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_LINK_TO2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_LINK_TO2', 'Ссылка на операцию (инвентарь)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_LINK_TO2', NAME = 'Ссылка на операцию (инвентарь)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_LINK_TO2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_NAME_TO2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_NAME_TO2', 'Наим тип. опер. (инвентарь)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_NAME_TO2', NAME = 'Наим тип. опер. (инвентарь)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_NAME_TO2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_LINK_TO3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_LINK_TO3', 'Ссылка на операцию (ТМЦ)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_LINK_TO3', NAME = 'Ссылка на операцию (ТМЦ)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_LINK_TO3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_NAME_TO3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_NAME_TO3', 'Наим тип. опер. (ТМЦ)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_NAME_TO3', NAME = 'Наим тип. опер. (ТМЦ)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_NAME_TO3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_LINK_TO4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_LINK_TO4', 'Ссылка на операцию (Услуги)', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_LINK_TO4', NAME = 'Ссылка на операцию (Услуги)', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_LINK_TO4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_NAME_TO4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_ISSUED_NAME_TO4', 'Наим тип. опер. (Услуги)', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_ISSUED_NAME_TO4', NAME = 'Наим тип. опер. (Услуги)', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_ISSUED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_ISSUED_NAME_TO4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REF_INVOICE_OUT_AKT_EXEC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'Связь с\ф с актом вып. работ', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_REFERENCE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REF_INVOICE_OUT_AKT_EXEC', NAME = 'Связь с\ф с актом вып. работ', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_REFERENCE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REF_INVOICE_OUT_AKT_EXEC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REF_INVOICE_OUT_AKT_EXEC_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'Связь с\ф с актом вып. работ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_REFERENCE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', NAME = 'Связь с\ф с актом вып. работ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_REFERENCE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REF_INVOICE_OUT_AKT_EXEC_1'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'TITLE', 'Счет-фактура выданный'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOCUMENTS_INVOICE_ISSUED", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOCUMENTS_INVOICE_ISSUED'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL(SEL_LINK), CONS1_SELF, SQLNULL(CONS1_LINK), SQLNULL(PROD_LINK), SQLNULL(BUY_LINK), CONS2_SELF, SQLNULL(CONS2_LINK), NUM_BASE, SQLNULL(DATE_BASE)"+", NALOG_DOC, SQLNULL(OSNOV), BOOK_SALES, SQLNULL(PAYS_LINK),SQLNULL(TAX_RATE), COR_NUM, SQLNULL (COR_DATE)","DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_INVOICE")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BV_DOC_INVOICE_ISSUED_EDIT'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'SNAME', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'QUERY_REPORT', 'INVOICE.XLT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'OPTIONS_OBJECT_CODE', 'DOC_INVOICE_ISSUED_OPT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'HELP_TOPIC', '47'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'CREATE_PROV_SQL', 'BK_CREATE_PROV_INVOICE_ISSUED#Сформировать акт за вып. услуги!BK_CREATE_RELATION_DOC (m.oForm, "DOCUMENTS_AKT_EXEC_SERVICES",  "BK_SAVE_AKT_EXEC_FROM_INVOICE")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_ISSUED', 'REPORT_EXTERNAL_GENERATOR', '1'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'SHORT_CODE_OBJ', 'SEL_LINK'
GO
EXEC X_SET_PROP 'SELLER_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'EDIT_OBJECT_METHOD', 'IIF(!oObj.Parent.Parent.Check7.Value, XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,LINK,CODE,NAME", "SEL_LINK,SEL_CODE,SEL_NAME,CONS1_LINK,CONS1_CODE,CONS1_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"))'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'CONTROLSOURCE', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'REFERENCE_TO_DICT', 'SELLER_LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'SHORT_CODE_OBJ', 'SEL_CODE'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'CONTROLSOURCE', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'REFERENCE_TO_DICT', 'SELLER_LINK'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'SHORT_CODE_OBJ', 'SEL_NAME'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'TITLE', 'Он же грузоотправитель'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'CONTROLSOURCE', 'm.cAlias + ".CONS1_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'SHORT_CODE_OBJ', 'CONS1_SELF'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CONS1_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNOR', 'CONTROL_NAME_EDIT', 'CHECK7'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'SHORT_CODE_OBJ', 'CONS1_LINK'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'TITLE', 'Грузоотправитель'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "CONS1_LINK, CONS1_CODE, CONS1_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'CONTROLSOURCE', 'm.cAlias+".CONS1_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'REFERENCE_TO_DICT', 'CONSIGNOR_LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'SHORT_CODE_OBJ', 'CONS1_CODE'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS1_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'SELLER_CODE01', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'TITLE', 'Грузоотправитель'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'CONTROLSOURCE', 'm.cAlias+".CONS1_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'REFERENCE_TO_DICT', 'CONSIGNOR_LINK'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'SHORT_CODE_OBJ', 'CONS1_NAME'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS1_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'SELLER_NAME01', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'SHORT_CODE_OBJ', 'PROD_LINK'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "PROD_LINK, PROD_CODE, PROD_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'CONTROLSOURCE', 'm.cALIAS+".PROD_CODE"'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'REFERENCE_TO_DICT', 'DOC_ISSUED_PRODUCER_LINK'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'SHORT_CODE_OBJ', 'PROD_CODE'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".PROD_CODE"'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr21'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'CONTROLSOURCE', 'm.cAlias+".PROD_NAME"'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'REFERENCE_TO_DICT', 'DOC_ISSUED_PRODUCER_LINK'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'SHORT_CODE_OBJ', 'PROD_NAME'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PROD_NAME"'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'CONTROL_NAME_EDIT', 'ATxtN21'
GO
EXEC X_SET_PROP 'DOC_ISSUED_PRODUCER_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'SHORT_CODE_OBJ', 'BUY_LINK'
GO
EXEC X_SET_PROP 'BUYER_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'EDIT_OBJECT_METHOD', 'IIF(!oObj.Parent.Parent.Check8.Value, XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "BUY_LINK, BUY_CODE, BUY_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,LINK,CODE,NAME", "BUY_LINK, BUY_CODE, BUY_NAME, CONS2_LINK, CONS2_CODE, CONS2_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"))'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'CONTROLSOURCE', 'm.cAlias+".BUY_CODE"'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'REFERENCE_TO_DICT', 'BUYER_LINK'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'SHORT_CODE_OBJ', 'BUY_CODE'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_CODE"'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr3'
GO
EXEC X_SET_PROP 'BUYER_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'CONTROLSOURCE', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'REFERENCE_TO_DICT', 'BUYER_LINK'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'SHORT_CODE_OBJ', 'BUY_NAME'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'CONTROL_NAME_EDIT', 'ATxtN3'
GO
EXEC X_SET_PROP 'BUYER_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'TITLE', 'Он же грузополучатель'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'CONTROLSOURCE', 'm.cAlias + ".CONS2_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'SHORT_CODE_OBJ', 'CONS2_SELF'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CONS2_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE', 'CONTROL_NAME_EDIT', 'CHECK8'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'SHORT_CODE_OBJ', 'CONS2_LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "CONS2_LINK, CONS2_CODE, CONS2_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'CONTROLSOURCE', 'm.cAlias+".CONS2_CODE"'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'REFERENCE_TO_DICT', 'CONSIGNEE_LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'SHORT_CODE_OBJ', 'CONS2_CODE'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS2_CODE"'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr4'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'CONTROLSOURCE', 'm.cAlias+".CONS2_NAME"'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'REFERENCE_TO_DICT', 'CONSIGNEE_LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'SHORT_CODE_OBJ', 'CONS2_NAME'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS2_NAME"'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'PAYS_LINK_ISSUED', 'TITLE', 'Ссылка на платежку'
GO
EXEC X_SET_PROP 'PAYS_LINK_ISSUED', 'CONTROLSOURCE', 'm.cAlias+".PAYS_LINK"'
GO
EXEC X_SET_PROP 'PAYS_LINK_ISSUED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PAYS_LINK_ISSUED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'PAYS_LINK_ISSUED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PAYS_LINK"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'TITLE', 'Номер платежно-расчетного документа'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'CONTROLSOURCE', 'm.cAlias + ".NUM_BASE"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'SHORT_CODE_OBJ', 'NUM_BASE'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUM_BASE"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT', 'CONTROL_NAME_EDIT', 'ATxt5'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'TITLE', 'Дата платежно-расчетного документа'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'CONTROLSOURCE', 'm.cAlias + ".DATE_BASE"'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'SHORT_CODE_OBJ', 'DATE_BASE'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_BASE"'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT', 'CONTROL_NAME_EDIT', 'Aseldate6'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'TITLE', 'Итого налога'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'CONTROLSOURCE', 'm.cAlias + ".NALOG_DOC"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'TYPE_FIELD_DICT', 'NUMERIC(13,2)'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'SHORT_CODE_OBJ', 'NALOG_DOC'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NALOG_DOC"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_NALOG_DOC', 'CONTROL_NAME_EDIT', 'ATxtN32'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_LINK', 'STORAGE', 'G_PROV'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_LINK', 'SHORT_CODE_OBJ', 'DOG_LINK'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'TITLE', 'Номер договора'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'EDIT_OBJECT_METHOD', 'BK_VIBOR_OSNOV(oForm.Alias, "LINK, NUMBER", "OSNOV, DOG_CODE","", EVALUATE (oForm.Alias + ".DEP_LINK"), oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'CONTROLSOURCE', 'm.cAlias + ".DOG_CODE"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'STORAGE', 'G_PROV'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'REFERENCE_TO_DICT', 'INVOICE_ISSUED_DOG_LINK'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'TYPE_FIELD_DICT', 'char(25)'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'SHORT_CODE_OBJ', 'DOG_CODE'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DOG_CODE"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'CONTROL_NAME_EDIT', 'ASel_spr25'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_DOG_NUM', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'TITLE', 'Включать в книгу продаж'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'CONTROLSOURCE', 'm.cAlias + ".BOOK_SALES"'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'SHORT_CODE_OBJ', 'BOOK_SALES'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BOOK_SALES"'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'CONTROL_NAME', 'CHECK13'
GO
EXEC X_SET_PROP 'BOOK_SALES_ISSUED', 'CONTROL_NAME_EDIT', 'CHECK13'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'TITLE', 'Ставка НДС (%)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'CONTROLSOURCE', 'm.cAlias + ".TAX_RATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'TYPE_FIELD_DICT', 'NUMERIC (4, 2)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'SHORT_CODE_OBJ', 'TAX_RATE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAX_RATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'CONTROL_NAME_EDIT', 'ATXT30'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_TAX', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_COMMENT', 'CONTROL_NAME_EDIT', 'AEDIT31'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'TITLE', 'Исправление №'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'CONTROLSOURCE', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_NUM', 'CONTROL_NAME_EDIT', 'ATXT41'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'TITLE', 'от'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'CONTROLSOURCE', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'INVOICE_ISSUED_COR_DATE', 'CONTROL_NAME_EDIT', 'Aseldate42'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_OPT', 'TITLE', 'Настройки счета-фактуры'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_OPT', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_OPT', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''DOC_INVOICE_ISSUED_OPT'')'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_OPT', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(''DOC_INVOICE_ISSUED_OPT'', m.cAlias)'
GO
EXEC X_SET_PROP 'DOCUMENTS_REFERENCE', 'TITLE', 'Междокументные связи'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'TITLE', 'Бланк документа'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'SHORT_CODE_OBJ', 'REPORT'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REPORT"'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT', 'CONTROL_NAME_EDIT', 'RADIO1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO1', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO1', 'SHORT_CODE_OBJ', 'TO_LINK1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'TITLE', 'Типовая операция (Материалы)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK1", "TO_NAME1", "DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'REFERENCE_TO_DICT', 'DOC_INVOICE_ISSUED_LINK_TO1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'SHORT_CODE_OBJ', 'TO_NAME1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME1"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO1', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO2', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO2', 'SHORT_CODE_OBJ', 'TO_LINK2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO2', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'TITLE', 'Типовая операция (ОС)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK2", "TO_NAME2", "DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'REFERENCE_TO_DICT', 'DOC_INVOICE_ISSUED_LINK_TO2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'SHORT_CODE_OBJ', 'TO_NAME2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME2"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO2', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO3', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO3', 'SHORT_CODE_OBJ', 'TO_LINK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO3', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'TITLE', 'Типовая операция (ТМЦ)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK3", "TO_NAME3", "DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'REFERENCE_TO_DICT', 'DOC_INVOICE_ISSUED_LINK_TO3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'SHORT_CODE_OBJ', 'TO_NAME3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME3"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'CONTROL_NAME_EDIT', 'Asel_spr4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO3', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO4', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO4', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO4', 'SHORT_CODE_OBJ', 'TO_LINK4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_LINK_TO4', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'TITLE', 'Типовая операция (Услуги)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK4", "TO_NAME4", "DOCUMENTS_INVOICE_ISSUED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'REFERENCE_TO_DICT', 'DOC_INVOICE_ISSUED_LINK_TO4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'SHORT_CODE_OBJ', 'TO_NAME4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME4"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'CONTROL_NAME_EDIT', 'Asel_spr5'
GO
EXEC X_SET_PROP 'DOC_INVOICE_ISSUED_NAME_TO4', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'TITLE', 'Связь с\ф с актом вып. работ'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'STORAGE', 'G_PROV_REF'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'TITLE', 'Связь с\ф с актом вып. работ'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'STORAGE', 'G_PROV_REF'
GO
EXEC X_SET_PROP 'DOC_REF_INVOICE_OUT_AKT_EXEC_1', 'TYPE_FIELD_DICT', 'INT'
GO






GO
-- Счет-фактура полученный --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_INVOICE_RECEIVED', 'Счет-фактура полученный', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_INVOICE_RECEIVED', NAME = 'Счет-фактура полученный', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_INVOICE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_LINK_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_LINK_RECEIVED', 'Продавец', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_LINK_RECEIVED', NAME = 'Продавец', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_LINK_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_CODE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_CODE_RECEIVED', 'Код продавца', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_CODE_RECEIVED', NAME = 'Код продавца', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_CODE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_NAME_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_NAME_RECEIVED', 'Наименование продавца', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_NAME_RECEIVED', NAME = 'Наименование продавца', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_NAME_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELF_CONS1_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELF_CONS1_RECEIVED', 'Он же грузоотправитель', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELF_CONS1_RECEIVED', NAME = 'Он же грузоотправитель', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELF_CONS1_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNOR_LINK_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNOR_LINK_RECEIVED', 'Грузоотправитель', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNOR_LINK_RECEIVED', NAME = 'Грузоотправитель', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNOR_LINK_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_CODE01_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_CODE01_RECEIVED', 'Код грузоотправителя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_CODE01_RECEIVED', NAME = 'Код грузоотправителя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_CODE01_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELLER_NAME01_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELLER_NAME01_RECEIVED', 'Наименование грузоотправителя', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELLER_NAME01_RECEIVED', NAME = 'Наименование грузоотправителя', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELLER_NAME01_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_RECEIVED_PRODUCER_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_RECEIVED_PRODUCER_LINK', 'Производитель', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_RECEIVED_PRODUCER_LINK', NAME = 'Производитель', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_RECEIVED_PRODUCER_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_RECEIVED_PRODUCER_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_RECEIVED_PRODUCER_CODE', 'Код производителя', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_RECEIVED_PRODUCER_CODE', NAME = 'Код производителя', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_RECEIVED_PRODUCER_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_RECEIVED_PRODUCER_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_RECEIVED_PRODUCER_NAME', 'Наименование производителя', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_RECEIVED_PRODUCER_NAME', NAME = 'Наименование производителя', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_RECEIVED_PRODUCER_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_LINK_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_LINK_RECEIVED', 'Покупатель', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_LINK_RECEIVED', NAME = 'Покупатель', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_LINK_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_CODE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_CODE_RECEIVED', 'Код покупателя', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_CODE_RECEIVED', NAME = 'Код покупателя', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_CODE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BUYER_NAME_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BUYER_NAME_RECEIVED', 'Наименование покупателя', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BUYER_NAME_RECEIVED', NAME = 'Наименование покупателя', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BUYER_NAME_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SELF_CONSIGNEE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SELF_CONSIGNEE_RECEIVED', 'Он же грузополучатель', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SELF_CONSIGNEE_RECEIVED', NAME = 'Он же грузополучатель', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SELF_CONSIGNEE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_LINK_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_LINK_RECEIVED', 'Грузополучатель', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_LINK_RECEIVED', NAME = 'Грузополучатель', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_LINK_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_CODE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_CODE_RECEIVED', 'Код грузополучателя', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_CODE_RECEIVED', NAME = 'Код грузополучателя', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_CODE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='CONSIGNEE_NAME_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'CONSIGNEE_NAME_RECEIVED', 'Наименование грузополучателя', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'CONSIGNEE_NAME_RECEIVED', NAME = 'Наименование грузополучателя', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='CONSIGNEE_NAME_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='PAYS_LINK_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'PAYS_LINK_RECEIVED', 'Ссылка на платежку', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'PAYS_LINK_RECEIVED', NAME = 'Ссылка на платежку', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='PAYS_LINK_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NUMBER_BASE_DOCUMENT_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NUMBER_BASE_DOCUMENT_RECEIVED', 'Номер платежно-расчетного документа', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NUMBER_BASE_DOCUMENT_RECEIVED', NAME = 'Номер платежно-расчетного документа', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NUMBER_BASE_DOCUMENT_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DATE_BASE_DOCUMENT_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DATE_BASE_DOCUMENT_RECEIVED', 'Дата платежно-расчетного документа', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DATE_BASE_DOCUMENT_RECEIVED', NAME = 'Дата платежно-расчетного документа', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DATE_BASE_DOCUMENT_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_RECEIVED_DOG_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_RECEIVED_DOG_LINK', 'Ссылка на договор', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_RECEIVED_DOG_LINK', NAME = 'Ссылка на договор', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_RECEIVED_DOG_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_RECEIVED_DOG_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_RECEIVED_DOG_NUM', 'Номер договора', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_RECEIVED_DOG_NUM', NAME = 'Номер договора', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_RECEIVED_DOG_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_RECEIVED_NALOG_DOC_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_RECEIVED_NALOG_DOC_1', 'Итоговая сумма налога по документу', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_RECEIVED_NALOG_DOC_1', NAME = 'Итоговая сумма налога по документу', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_RECEIVED_NALOG_DOC_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BOOK_PURCHASE_RECEIVED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BOOK_PURCHASE_RECEIVED', 'Включать в книгу покупок', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BOOK_PURCHASE_RECEIVED', NAME = 'Включать в книгу покупок', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BOOK_PURCHASE_RECEIVED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECEIVED_TAX')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECEIVED_TAX', 'Ставка НДС', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECEIVED_TAX', NAME = 'Ставка НДС', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECEIVED_TAX'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_RECEIVED_LINK_DOC_OPER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_RECEIVED_LINK_DOC_OPER', 'Ссылка на документ с проводками', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_RECEIVED_LINK_DOC_OPER', NAME = 'Ссылка на документ с проводками', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_RECEIVED_LINK_DOC_OPER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECEIVED_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECEIVED_COMMENT', 'Комментарий', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECEIVED_COMMENT', NAME = 'Комментарий', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECEIVED_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECEIVED_LN_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECEIVED_LN_KBK', 'Ссылка на КБК', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECEIVED_LN_KBK', NAME = 'Ссылка на КБК', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECEIVED_LN_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECEIVED_CD_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECEIVED_CD_KBK', 'Код КБК', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECEIVED_CD_KBK', NAME = 'Код КБК', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECEIVED_CD_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECEIVED_NM_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECEIVED_NM_KBK', 'Наименование КБК', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECEIVED_NM_KBK', NAME = 'Наименование КБК', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECEIVED_NM_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_RECEIVED_COR_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_RECEIVED_COR_NUM', 'Номер исправления', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_RECEIVED_COR_NUM', NAME = 'Номер исправления', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_RECEIVED_COR_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='INVOICE_RECEIVED_COR_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'INVOICE_RECEIVED_COR_DATE', 'Дата исправления', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'INVOICE_RECEIVED_COR_DATE', NAME = 'Дата исправления', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='INVOICE_RECEIVED_COR_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIEVED_OPT', 'Настройки счета-фактуры', 33, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIEVED_OPT', NAME = 'Настройки счета-фактуры', ORDERS = '33', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_RECEIVED'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIEVED_OPT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NASTR_INVOICE_REPORT_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NASTR_INVOICE_REPORT_1', 'Бланк документа', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NASTR_INVOICE_REPORT_1', NAME = 'Бланк документа', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NASTR_INVOICE_REPORT_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_LINK_TO1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_LINK_TO1', 'Ссылка на операцию (номенклатура)', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_LINK_TO1', NAME = 'Ссылка на операцию (номенклатура)', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_LINK_TO1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_NAME_TO1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_NAME_TO1', 'Наим тип. опер. (номенклатура)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_NAME_TO1', NAME = 'Наим тип. опер. (номенклатура)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_NAME_TO1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_LINK_TO2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_LINK_TO2', 'Ссылка на операцию (инвентарь)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_LINK_TO2', NAME = 'Ссылка на операцию (инвентарь)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_LINK_TO2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_NAME_TO2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_NAME_TO2', 'Наим тип. опер. (инвентарь)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_NAME_TO2', NAME = 'Наим тип. опер. (инвентарь)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_NAME_TO2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_LINK_TO3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_LINK_TO3', 'Ссылка на операцию (ТМЦ)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_LINK_TO3', NAME = 'Ссылка на операцию (ТМЦ)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_LINK_TO3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_NAME_TO3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_NAME_TO3', 'Наим тип. опер. (ТМЦ)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_NAME_TO3', NAME = 'Наим тип. опер. (ТМЦ)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_NAME_TO3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_LINK_TO4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_LINK_TO4', 'Ссылка на операцию (Услуги)', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_LINK_TO4', NAME = 'Ссылка на операцию (Услуги)', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_LINK_TO4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_NAME_TO4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_NAME_TO4', 'Наим тип. опер. (Услуги)', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_NAME_TO4', NAME = 'Наим тип. опер. (Услуги)', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_NAME_TO4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_KIND_LN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_KIND_LN', 'Ссылка на вид документа', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_KIND_LN', NAME = 'Ссылка на вид документа', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_KIND_LN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_KIND_CD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_KIND_CD', 'Код вида документа', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_KIND_CD', NAME = 'Код вида документа', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_KIND_CD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_KIND_NM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_KIND_NM', 'Наименование вида документа', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_KIND_NM', NAME = 'Наименование вида документа', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_KIND_NM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_TYPE_NUMDOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'Номерация документа', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_TYPE_NUMDOC', NAME = 'Номерация документа', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_TYPE_NUMDOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIV_OPT_PROV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_RECIV_OPT_PROV', 'Формирование проводок в документе', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_RECIV_OPT_PROV', NAME = 'Формирование проводок в документе', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_RECIEVED_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_RECIV_OPT_PROV'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'TITLE', 'Счет-фактура полученный'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOCUMENTS_INVOICE_RECEIVED", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOCUMENTS_INVOICE_RECEIVED'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL(SEL_LINK), CONS1_SELF, SQLNULL(CONS1_LINK), SQLNULL(PROD_LINK), SQLNULL(BUY_LINK), CONS2_SELF, SQLNULL(CONS2_LINK), NUM_BASE, SQLNULL(DATE_BASE)"+", SQLNULL(OSNOV), NALOG_DOC, BOOK_PUR, SQLNULL(PAYS_LINK), SQLNULL(TAX_RATE), COR_NUM, SQLNULL (COR_DATE)","DOCUMENTS_INVOICE_RECEIVED")
'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_INVOICE")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BV_DOC_INVOICE_RECEIVED_EDIT'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'SNAME', 'Счет-фактура'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'QUERY_REPORT', 'INVOICE.XLT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'OPTIONS_OBJECT_CODE', 'DOC_INVOICE_RECIEVED_OPT'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'HELP_TOPIC', '47'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'CREATE_PROV_SQL', 'Операции!oForm.acmdprovDoc.Click ()#BK_SAVE_DOC_OPER_FROM_INVOICE'
GO
EXEC X_SET_PROP 'DOCUMENTS_INVOICE_RECEIVED', 'REPORT_EXTERNAL_GENERATOR', '1'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'EDIT_OBJECT_METHOD', 'IIF(!oForm.Pages.Page1.Check7.Value, XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,LINK,CODE,NAME", "CONS1_LINK, CONS1_CODE, CONS1_NAME, SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"))'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'SHORT_CODE_OBJ', 'SEL_LINK'
GO
EXEC X_SET_PROP 'SELLER_LINK_RECEIVED', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'EDIT_OBJECT_METHOD', 'IIF(!oForm.Pages.Page1.Check7.Value, XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,LINK,CODE,NAME", "CONS1_LINK, CONS1_CODE, CONS1_NAME, SEL_LINK, SEL_CODE, SEL_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"))'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'CONTROLSOURCE', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'REFERENCE_TO_DICT', 'SELLER_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'SHORT_CODE_OBJ', 'SEL_CODE'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".SEL_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'SELLER_CODE_RECEIVED', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'TITLE', 'Продавец'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'REFERENCE_TO_DICT', 'SELLER_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'SHORT_CODE_OBJ', 'SEL_NAME'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SEL_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'SELLER_NAME_RECEIVED', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'TITLE', 'Он же грузоотправитель'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'CONTROLSOURCE', 'm.cAlias + ".CONS1_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'SHORT_CODE_OBJ', 'CONS1_SELF'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CONS1_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONS1_RECEIVED', 'CONTROL_NAME_EDIT', 'CHECK7'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'SHORT_CODE_OBJ', 'CONS1_LINK'
GO
EXEC X_SET_PROP 'CONSIGNOR_LINK_RECEIVED', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'TITLE', 'Грузоотправитель'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "CONS1_LINK, CONS1_CODE, CONS1_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".CONS1_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'REFERENCE_TO_DICT', 'CONSIGNOR_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'SHORT_CODE_OBJ', 'CONS1_CODE'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS1_CODE"'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'SELLER_CODE01_RECEIVED', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'TITLE', 'Грузоотправитель'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".CONS1_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'REFERENCE_TO_DICT', 'CONSIGNOR_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'SHORT_CODE_OBJ', 'CONS1_NAME'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS1_NAME"'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'SELLER_NAME01_RECEIVED', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'SHORT_CODE_OBJ', 'PROD_LINK'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "PROD_LINK, PROD_CODE, PROD_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'CONTROLSOURCE', 'm.cALIAS+".PROD_CODE"'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'REFERENCE_TO_DICT', 'DOC_RECEIVED_PRODUCER_LINK'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'SHORT_CODE_OBJ', 'PROD_CODE'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".PROD_CODE"'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr21'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'TITLE', 'Производитель'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'CONTROLSOURCE', 'm.cAlias+".PROD_NAME"'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'REFERENCE_TO_DICT', 'DOC_RECEIVED_PRODUCER_LINK'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'SHORT_CODE_OBJ', 'PROD_NAME'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PROD_NAME"'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'CONTROL_NAME_EDIT', 'ATxtN21'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_PRODUCER_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'SHORT_CODE_OBJ', 'BUY_LINK'
GO
EXEC X_SET_PROP 'BUYER_LINK_RECEIVED', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'EDIT_OBJECT_METHOD', 'IIF(!oForm.Pages.Page1.Check8.Value, XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "BUY_LINK, BUY_CODE, BUY_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,LINK,CODE,NAME", "BUY_LINK, BUY_CODE, BUY_NAME, CONS2_LINK, CONS2_CODE, CONS2_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"))'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".BUY_CODE"'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'REFERENCE_TO_DICT', 'BUYER_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'SHORT_CODE_OBJ', 'BUY_CODE'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_CODE"'
GO
EXEC X_SET_PROP 'BUYER_CODE_RECEIVED', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'TITLE', 'Покупатель'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'REFERENCE_TO_DICT', 'BUYER_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'SHORT_CODE_OBJ', 'BUY_NAME'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BUY_NAME"'
GO
EXEC X_SET_PROP 'BUYER_NAME_RECEIVED', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'TITLE', 'Он же грузополучатель'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'CONTROLSOURCE', 'm.cAlias + ".CONS2_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'SHORT_CODE_OBJ', 'CONS2_SELF'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CONS2_SELF"'
GO
EXEC X_SET_PROP 'SELF_CONSIGNEE_RECEIVED', 'CONTROL_NAME_EDIT', 'CHECK8'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'SHORT_CODE_OBJ', 'CONS2_LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_LINK_RECEIVED', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "CONS2_LINK, CONS2_CODE, CONS2_NAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".CONS2_CODE"'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'REFERENCE_TO_DICT', 'CONSIGNEE_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'SHORT_CODE_OBJ', 'CONS2_CODE'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS2_CODE"'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'CONTROL_NAME_EDIT', 'ASel_Spr4'
GO
EXEC X_SET_PROP 'CONSIGNEE_CODE_RECEIVED', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'TITLE', 'Грузополучатель'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".CONS2_NAME"'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'REFERENCE_TO_DICT', 'CONSIGNEE_LINK_RECEIVED'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'SHORT_CODE_OBJ', 'CONS2_NAME'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CONS2_NAME"'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'CONSIGNEE_NAME_RECEIVED', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'PAYS_LINK_RECEIVED', 'TITLE', 'Ссылка на платежку'
GO
EXEC X_SET_PROP 'PAYS_LINK_RECEIVED', 'CONTROLSOURCE', 'm.cAlias+".PAYS_LINK"'
GO
EXEC X_SET_PROP 'PAYS_LINK_RECEIVED', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'PAYS_LINK_RECEIVED', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'PAYS_LINK_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PAYS_LINK"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'TITLE', 'Номер платежно-расчетного документа'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'CONTROLSOURCE', 'm.cAlias + ".NUM_BASE"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'SHORT_CODE_OBJ', 'NUM_BASE'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUM_BASE"'
GO
EXEC X_SET_PROP 'NUMBER_BASE_DOCUMENT_RECEIVED', 'CONTROL_NAME_EDIT', 'ATxt5'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'TITLE', 'Дата платежно-расчетного документа'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'CONTROLSOURCE', 'm.cAlias + ".DATE_BASE"'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'SHORT_CODE_OBJ', 'DATE_BASE'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_BASE"'
GO
EXEC X_SET_PROP 'DATE_BASE_DOCUMENT_RECEIVED', 'CONTROL_NAME_EDIT', 'Aseldate6'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_LINK', 'STORAGE', 'G_PROV'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_LINK', 'SHORT_CODE_OBJ', 'DOG_LINK'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'TITLE', 'Номер договора'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'EDIT_OBJECT_METHOD', 'BK_VIBOR_OSNOV(oForm.Alias, "LINK, NUMBER", "OSNOV, DOG_CODE","", EVALUATE (oForm.Alias + ".DEP_LINK"), oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'VISIBLE', '7'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'CONTROLSOURCE', 'm.cAlias + ".DOG_CODE"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'STORAGE', 'G_PROV'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'REFERENCE_TO_DICT', 'INVOICE_RECEIVED_DOG_LINK'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'TYPE_FIELD_DICT', 'char(25)'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'SHORT_CODE_OBJ', 'DOG_CODE'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DOG_CODE"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'CONTROL_NAME_EDIT', 'ASel_spr25'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_DOG_NUM', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'TITLE', 'Итого налога'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'CONTROLSOURCE', 'm.cAlias + ".NALOG_DOC"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'TYPE_FIELD_DICT', 'NUMERIC(13,2)'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'SHORT_CODE_OBJ', 'NALOG_DOC'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NALOG_DOC"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_NALOG_DOC_1', 'CONTROL_NAME_EDIT', 'ATxtN10'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'TITLE', 'Включать в книгу покупок'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'CONTROLSOURCE', 'm.cAlias + ".BOOK_PUR"'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'SHORT_CODE_OBJ', 'BOOK_PUR'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BOOK_PUR"'
GO
EXEC X_SET_PROP 'BOOK_PURCHASE_RECEIVED', 'CONTROL_NAME_EDIT', 'CHECK13'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'TITLE', 'Ставка НДС (%)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'CONTROLSOURCE', 'm.cAlias + ".TAX_RATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'TYPE_FIELD_DICT', 'NUMERIC (4, 2)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'SHORT_CODE_OBJ', 'TAX_RATE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAX_RATE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'CONTROL_NAME_EDIT', 'ATXT30'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_TAX', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_LINK_DOC_OPER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_LINK_DOC_OPER', 'STORAGE', 'CALCULATE'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_LINK_DOC_OPER', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_LINK_DOC_OPER', 'SHORT_CODE_OBJ', 'DOC_PROV'
GO
EXEC X_SET_PROP 'DOC_RECEIVED_LINK_DOC_OPER', 'CONTROL_NAME_EDIT', 'DOC_PROV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_COMMENT', 'CONTROL_NAME_EDIT', 'AEDIT31'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'TITLE', 'Ссылка на КБК'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'REFERENCE_TO_DICT', 'BI_DICTION_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'SHORT_CODE_OBJ', 'KBK_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_LN_KBK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'EDIT_OBJECT_METHOD', 'a_vibor_01("BI_DICTION_KBK", oForm.Alias, "LINK,CODE,NAME", "KBK_LINK,KBK_CODE,KBK_NAME", "", "","",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECEIVED_LN_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'TYPE_FIELD_DICT', 'VARCHAR (20)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'CONTROL_NAME', 'ASEL_SPR35'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'CONTROL_NAME_EDIT', 'ASEL_SPR35'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_CD_KBK', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'EDIT_OBJECT_METHOD', 'a_vibor_01("BI_DICTION_KBK", oForm.Alias, "LINK,CODE,NAME", "KBK_LINK,KBK_CODE,KBK_NAME", "", "","",  .T., 1, oForm, oObj,''lg_prov_notsbs()'')'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'CONTROLSOURCE', 'm.cAlias + ".KBK_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECEIVED_LN_KBK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'SHORT_CODE_OBJ', 'KBK_NAME'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'CONTROL_NAME', 'ATXTN35'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'CONTROL_NAME_EDIT', 'ATXTN35'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECEIVED_NM_KBK', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'TITLE', 'Исправление №'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'CONTROLSOURCE', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_NUM"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_NUM', 'CONTROL_NAME_EDIT', 'ATXT41'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'TITLE', 'от'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'CONTROLSOURCE', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COR_DATE"'
GO
EXEC X_SET_PROP 'INVOICE_RECEIVED_COR_DATE', 'CONTROL_NAME_EDIT', 'Aseldate42'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIEVED_OPT', 'TITLE', 'Настройки счета-фактуры'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIEVED_OPT', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIEVED_OPT', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''DOC_INVOICE_OPTIONS'')'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIEVED_OPT', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(''DOC_INVOICE_RECIEVED_OPT'', m.cAlias)'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'TITLE', 'Бланк документа'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'SHORT_CODE_OBJ', 'REPORT'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REPORT"'
GO
EXEC X_SET_PROP 'NASTR_INVOICE_REPORT_1', 'CONTROL_NAME_EDIT', 'RADIO1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO1', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO1', 'SHORT_CODE_OBJ', 'TO_LINK1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'TITLE', 'Типовая операция (Материалы)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK1", "TO_NAME1", "DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_LINK_TO1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'SHORT_CODE_OBJ', 'TO_NAME1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME1"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO1', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO2', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO2', 'SHORT_CODE_OBJ', 'TO_LINK2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO2', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'TITLE', 'Типовая операция (ОС)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK2", "TO_NAME2", "DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_LINK_TO2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'SHORT_CODE_OBJ', 'TO_NAME2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME2"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO2', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO3', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO3', 'SHORT_CODE_OBJ', 'TO_LINK3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO3', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'TITLE', 'Типовая операция (ТМЦ)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK3", "TO_NAME3", "DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_LINK_TO3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'SHORT_CODE_OBJ', 'TO_NAME3'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME3"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'CONTROL_NAME_EDIT', 'Asel_spr4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO3', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO4', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO4', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO4', 'SHORT_CODE_OBJ', 'TO_LINK4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_LINK_TO4', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'TITLE', 'Типовая операция (Услуги)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TO_LINK4", "TO_NAME4", "DOCUMENTS_INVOICE_RECEIVED")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_LINK_TO4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'SHORT_CODE_OBJ', 'TO_NAME4'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TO_NAME4"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'CONTROL_NAME_EDIT', 'Asel_spr5'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_NAME_TO4', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'TITLE', 'Вид документа'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'REFERENCE_TO_DICT', 'DICTIONARY_DOC_TYPES'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'SHORT_CODE_OBJ', 'KIND_LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_LN', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'TITLE', 'Вид документа'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01("DICTIONARY_DOC_TYPES", oForm.Alias, "LINK,CODE,NAME", "KIND_LINK,KIND_CODE,KIND_NAME", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'CONTROLSOURCE', 'm.cAlias+".KIND_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_KIND_LN'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'TYPE_FIELD_DICT', 'VARCHAR(2)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'SHORT_CODE_OBJ', 'KIND_CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KIND_CODE"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'CONTROL_NAME_EDIT', 'Asel_spr6'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_CD', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'TITLE', 'Вид документа'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'CONTROLSOURCE', 'm.cAlias+".KIND_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'REFERENCE_TO_DICT', 'DOC_INVOICE_RECIV_KIND_LN'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'SHORT_CODE_OBJ', 'KIND_NAME'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KIND_NAME"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'CONTROL_NAME', 'ATxtN6'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'CONTROL_NAME_EDIT', 'ATxtN6'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_KIND_NM', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'TITLE', 'Номер документа равен номеру счет-фактуры'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'SHORT_CODE_OBJ', 'TYPE_NUM'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYPE_NUM"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_TYPE_NUMDOC', 'CONTROL_NAME_EDIT', 'Chk_NumDoc'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'TITLE', 'Формировать проводки в счет-фактуре'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'SHORT_CODE_OBJ', 'OPT_PROV'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OPT_PROV"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_RECIV_OPT_PROV', 'CONTROL_NAME_EDIT', 'Chk_OPT_PROV'
GO






GO
--- DOC_INVOICE_PAY_OPTIONS ---
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_PAY_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_PAY_OPTIONS', 'Настройки счета на оплату', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_PAY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_PAY_OPTIONS', NAME = 'Настройки счета на оплату', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_INVOICE_PAY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_PAY_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_INVOICE_PAY_OPT_SALER_FMT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'Формат наименования получателя', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_PAY_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_INVOICE_PAY_OPT_SALER_FMT', NAME = 'Формат наименования получателя', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_INVOICE_PAY_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_INVOICE_PAY_OPT_SALER_FMT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPTIONS', 'TITLE', 'Настройки счета на оплату'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPTIONS', 'EDIT_OBJECT_METHOD', 'X_BROW ()'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(''DOC_INVOICE_PAY_OPTIONS'', m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'TITLE', 'Формат получателя для плат. поручения'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'EDIT_OBJECT_METHOD', 'BB_VIBOR_SHABLON (oForm.Alias, "SALER_FMT", "DEP_NAME")'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'SHORT_CODE_OBJ', 'SALER_FMT'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SALER_FMT"'
GO
EXEC X_SET_PROP 'DOC_INVOICE_PAY_OPT_SALER_FMT', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOC_INVOICE_PAY_OPTIONS', 'Смета-КС', 63,0
GO


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_COR_INVOICE', 'Табличная часть корректировочного счет-фактуры', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_COR_INVOICE', NAME = 'Табличная часть корректировочного счет-фактуры', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_COR_INVOICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_INV_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_INV_TYPE', 'Тип материальных запасов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_INV_TYPE', NAME = 'Тип материальных запасов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_INV_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_INV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_INV_LINK', 'Материал (ссылка)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_INV_LINK', NAME = 'Материал (ссылка)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_INV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_INV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_INV_CODE', 'Материал (код)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_INV_CODE', NAME = 'Материал (код)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_INV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_INV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_INV_NAME', 'Наименование материала', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_INV_NAME', NAME = 'Наименование материала', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_INV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_UM_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_UM_LINK', 'Единица измерения(ссылка)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_UM_LINK', NAME = 'Единица измерения(ссылка)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_UM_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_UM_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_UM_CODE', 'Единица измерения (Код)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_UM_CODE', NAME = 'Единица измерения (Код)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_UM_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_UM_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_UM_NAME', 'Наименование единицы измерения', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_UM_NAME', NAME = 'Наименование единицы измерения', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_UM_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_QTY', 'Количество (До)', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_QTY', NAME = 'Количество (До)', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_QTY_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_QTY_NEW', 'Количество (После)', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_QTY_NEW', NAME = 'Количество (После)', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_QTY_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_PRICE', 'Цена (тариф) за единицу измерения (До)', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_PRICE', NAME = 'Цена (тариф) за единицу измерения (До)', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_PRICE_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'Цена (тариф) за единицу измерения (После)', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_PRICE_NEW', NAME = 'Цена (тариф) за единицу измерения (После)', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_PRICE_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_SUMMA', 'Стоимость товаров (работ, услуг), всего без налога', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_SUMMA', NAME = 'Стоимость товаров (работ, услуг), всего без налога', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_SUM_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_SUM_NEW', 'Стоимость товаров (После)', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_SUM_NEW', NAME = 'Стоимость товаров (После)', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_SUM_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_AKCIZ')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_AKCIZ', 'В том числе акциз (До)', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_AKCIZ', NAME = 'В том числе акциз (До)', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_AKCIZ'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_AKC_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_AKC_NEW', 'В том числе акциз (После)', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_AKC_NEW', NAME = 'В том числе акциз (После)', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_AKC_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_STAVKA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'Налоговая ставка', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_STAVKA_NDS', NAME = 'Налоговая ставка', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_STAVKA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_ST_NDS_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'Налоговая ставка (После)', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', NAME = 'Налоговая ставка (После)', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_ST_NDS_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_NO_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_NO_NDS', 'Не облагается НДС (До)', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_NO_NDS', NAME = 'Не облагается НДС (До)', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_NO_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_NO_NDS_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'Не облагается НДС (После)', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', NAME = 'Не облагается НДС (После)', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_NO_NDS_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_SUMMA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_SUMMA_NDS', 'Сумма налога (До)', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_SUMMA_NDS', NAME = 'Сумма налога (До)', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_SUMMA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_S_NDS_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'Сумма налога (После)', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_S_NDS_NEW', NAME = 'Сумма налога (После)', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_S_NDS_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_SUMMA_ALL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_SUMMA_ALL', 'Стоимость товаров (работ, услуг) всего с учетом налога', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_SUMMA_ALL', NAME = 'Стоимость товаров (работ, услуг) всего с учетом налога', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_SUMMA_ALL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_S_ALL_NEW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'Стоимость полная (После)', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_S_ALL_NEW', NAME = 'Стоимость полная (После)', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_S_ALL_NEW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_COUNTRY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_COUNTRY', 'Страна происхождения', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_COUNTRY', NAME = 'Страна происхождения', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_COUNTRY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_NUM_DEC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_NUM_DEC', 'Номер грузовой таможенной декларации', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_NUM_DEC', NAME = 'Номер грузовой таможенной декларации', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_NUM_DEC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_EKR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_EKR_LINK', 'Ссылка на ЭКР', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_EKR_LINK', NAME = 'Ссылка на ЭКР', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_EKR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_EKR_CODE', 'Код ЭКР', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_SFIN_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_SFIN_NAME', 'Источник финансирования', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_SFIN_NAME', NAME = 'Источник финансирования', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_SFIN_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TAB_COR_INVOICE_TNDS_CODE2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'Вид НДС', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TAB_COR_INVOICE_TNDS_CODE2', NAME = 'Вид НДС', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_COR_INVOICE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TAB_COR_INVOICE_TNDS_CODE2'
GO
EXEC X_SET_PROP 'DOC_TABLE_COR_INVOICE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''dbo.BK_UPDATE_OUT_TABLE_INVOICE_COR'', m.cAlias,''SQLNULL(LINK_UP), SQLNULL (ROW_LINK), QTY_NEW, PRICE_NEW, SUM_NEW, AKC_NEW, S_NDS_NEW, S_ALL_NEW, ST_NDS_NEW, NO_NDS_NEW, SQLNULL(TNDS_LINK2)'', "DOC_TABLE_COR_INVOICE")'
GO
EXEC X_SET_PROP 'DOC_TABLE_COR_INVOICE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BK_DOC_TAB_INVOICE_COR_FN (''+STR(NVL (m.nLINK, 0)) + '')'',m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_TABLE_COR_INVOICE', 'SERVER_TABLE_NAME', 'OUT_TABLE_INVOICE_COR'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_TYPE', 'TITLE', 'Тип'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.INV_TYPE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'TITLE', 'Номен.\Инв. №'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'EDIT_OBJECT_METHOD', 'bk_vibor_doc_table_mz_nds()'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_NAME', 'CONTROLSOURCE', 'm.cAlias+''.INV_NAME'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_INV_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_LINK', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'TITLE', 'ЕИ (Код)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DIGIT", oObj.parent.Parent.RECORDSOURCE, "LINK, CODE, NAME", "UM_LINK, UM_CODE, UM_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'CONTROLSOURCE', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_NAME', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_NAME', 'CONTROLSOURCE', 'm.cAlias+''.UM_NAME'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_UM_NAME', 'TYPE_FIELD_DICT', 'varchar(15)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY', 'TITLE', 'Количество (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY', 'CONTROLSOURCE', 'm.cAlias+''.QTY'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY', 'TYPE_FIELD_DICT', 'NUMERIC(13,4)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY_NEW', 'TITLE', 'Количество (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY_NEW', 'CONTROLSOURCE', 'm.cAlias+''.QTY_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_QTY_NEW', 'TYPE_FIELD_DICT', 'NUMERIC(13,4)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE', 'TITLE', 'Цена (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.PRICE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(18,4)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'TITLE', 'Цена (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'CONTROLSOURCE', 'm.cAlias+''.PRICE_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_PRICE_NEW', 'TYPE_FIELD_DICT', 'NUMERIC(18,4)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA', 'TITLE', 'Стоимость (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ''.SUMMA'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA', 'TYPE_FIELD_DICT', 'NUMERIC(17,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUM_NEW', 'TITLE', 'Стоимость (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUM_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUM_NEW', 'CONTROLSOURCE', 'm.cAlias + ''.SUM_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUM_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUM_NEW', 'TYPE_FIELD_DICT', 'NUMERIC(17,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKCIZ', 'TITLE', 'Акциз (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKCIZ', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKCIZ', 'CONTROLSOURCE', 'm.cAlias + ''.AKCIZ'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKCIZ', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKCIZ', 'AUTO_FILL_CONTEXT', '999.99'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'TITLE', 'Акциз (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'CONTROLSOURCE', 'm.cAlias + ''.AKC_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_AKC_NEW', 'AUTO_FILL_CONTEXT', '999.99'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'TITLE', 'Налоговая ставка (До)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.STAVKA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_STAVKA_NDS', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'TITLE', 'Налоговая ставка (После)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'CONTROLSOURCE', 'm.cAlias + ''.ST_NDS_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_ST_NDS_NEW', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS', 'TITLE', 'Без НДС (До)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.NO_NDS'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'TITLE', 'Без НДС (После)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'CONTROLSOURCE', 'm.cAlias + ''.NO_NDS_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NO_NDS_NEW', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_NDS', 'TITLE', 'Сумма налога (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_NDS', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_NDS', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'TITLE', 'Сумма налога (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'CONTROLSOURCE', 'm.cAlias+''.S_NDS_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_NDS_NEW', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_ALL', 'TITLE', 'Полная стоимость (До изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_ALL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_ALL', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_ALL'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SUMMA_ALL', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'TITLE', 'Полная стоимость (После изм.)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'CONTROLSOURCE', 'm.cAlias+''.S_ALL_NEW'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_S_ALL_NEW', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_COUNTRY', 'TITLE', 'Страна'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_COUNTRY', 'CONTROLSOURCE', 'm.cAlias+''.COUNTRY'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_COUNTRY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_COUNTRY', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NUM_DEC', 'TITLE', 'Номер ГТД'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NUM_DEC', 'CONTROLSOURCE', 'm.cAlias+''.NUM_TD'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NUM_DEC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_NUM_DEC', 'TYPE_FIELD_DICT', 'varchar(5)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_LINK', 'TITLE', 'Ссылка на ЭКР'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_LINK', 'CONTROLSOURCE', 'm.cAlias+''.EKR_LINK'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_LINK', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "EKR_LINK, EKR_CODE", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias+''.EKR_CODE'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_KOSGU", EVALUATE(m.cAliasOperate+''.EKR_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_EKR_CODE', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SFIN_NAME', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SFIN_NAME', 'CONTROLSOURCE', 'm.cAlias+''.SFIN_NAME'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SFIN_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_SFIN_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'TITLE', 'Вид НДС'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_TYPE_OPER_NDS", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "TNDS_LINK2, TNDS_CODE2", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'CONTROLSOURCE', 'm.cAlias+''.TNDS_CODE2'''
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_TYPE_OPER_NDS",EVALUATE(m.cAliasOperate+''.TNDS_LINK2''))
'
GO
EXEC X_SET_PROP 'DOC_TAB_COR_INVOICE_TNDS_CODE2', 'TYPE_FIELD_DICT', 'VARCHAR(2)'
GO




GO
--- DOC_TABLE_MZ_NDS ---
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS', 'Табличная часть документов МЗ с НДС', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS', NAME = 'Табличная часть документов МЗ с НДС', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_TYPE', 'Тип материальных запасов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_TYPE', NAME = 'Тип материальных запасов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_LINK', 'Материал (ссылка)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_LINK', NAME = 'Материал (ссылка)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_CODE', 'Материал (код)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_CODE', NAME = 'Материал (код)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_NAME', 'Наименование материала', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_NAME', NAME = 'Наименование материала', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_LINK', 'Единица измерения(ссылка)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_LINK', NAME = 'Единица измерения(ссылка)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_CODE', 'Единица измерения (Код)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_CODE', NAME = 'Единица измерения (Код)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_NAME', 'Наименование единицы измерения', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_NAME', NAME = 'Наименование единицы измерения', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_QTY', 'Количество', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_QTY', NAME = 'Количество', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_PRICE', 'Цена (тариф) за единицу измерения', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_PRICE', NAME = 'Цена (тариф) за единицу измерения', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA', 'Стоимость товаров (работ, услуг), всего без налога', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA', NAME = 'Стоимость товаров (работ, услуг), всего без налога', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_AKCIZ')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_AKCIZ', 'В том числе акциз', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_AKCIZ', NAME = 'В том числе акциз', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_AKCIZ'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STAVKA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'Налоговая ставка', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STAVKA_NDS', NAME = 'Налоговая ставка', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STAVKA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_NO_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_NO_NDS', 'Не облагается НДС', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_NO_NDS', NAME = 'Не облагается НДС', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_NO_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'Сумма налога', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA_NDS', NAME = 'Сумма налога', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA_ALL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'Стоимость товаров (работ, услуг) всего с учетом налога', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA_ALL', NAME = 'Стоимость товаров (работ, услуг) всего с учетом налога', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA_ALL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STATE_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STATE_CODE', 'Страна происхождения (код)', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STATE_CODE', NAME = 'Страна происхождения (код)', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STATE_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STATE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STATE_NAME', 'Страна происхождения (наименование)', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STATE_NAME', NAME = 'Страна происхождения (наименование)', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STATE_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_NUM_DEC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_NUM_DEC', 'Номер грузовой таможенной декларации', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_NUM_DEC', NAME = 'Номер грузовой таможенной декларации', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_NUM_DEC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_EKR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_EKR_LINK', 'Ссылка на ЭКР', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_EKR_LINK', NAME = 'Ссылка на ЭКР', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_EKR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_EKR_CODE', 'Код ЭКР', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SFIN_SOURCE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'Источник финансирования', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', NAME = 'Источник финансирования', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SFIN_SOURCE'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SAVE_OBJECT_METHOD', 'X_SAVE(''dbo.BK_SAVE_DOC_TABLE_MZ_NDS'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, INV_TYPE, SQLNULL(INV_LINK),  PRICE, AKCIZ, NUM_TD, QTY, SUMMA, STAVKA_NDS, SUMMA_NDS, SUMMA_ALL, SQLNULL(EKR_LINK), SFIN_CODE, NO_NDS, SQLNULL (STATE_LINK)'',"DOC_TABLE_MZ_NDS")'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (''+STR(NVL (m.nLINK, 0)) + '')'',m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'TITLE', 'Тип'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.INV_TYPE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'TITLE', 'Номен.\Инв. №'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'EDIT_OBJECT_METHOD', 'bk_vibor_doc_table_mz_nds()'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'CONTROLSOURCE', 'm.cAlias+''.INV_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_LINK', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'TITLE', 'ЕИ (Код)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DIGIT", oObj.parent.Parent.RECORDSOURCE, "LINK, CODE, NAME", "UM_LINK, UM_CODE, UM_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'CONTROLSOURCE', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'CONTROLSOURCE', 'm.cAlias+''.UM_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'TYPE_FIELD_DICT', 'varchar(15)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'TITLE', 'Количество'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'CONTROLSOURCE', 'm.cAlias+''.QTY'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'TYPE_FIELD_DICT', 'NUMERIC(13,4)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'TITLE', 'Цена'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.PRICE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(18,4)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'TITLE', 'Стоимость'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ''.SUMMA'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'TYPE_FIELD_DICT', 'NUMERIC(17,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'TITLE', 'Акциз'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'CONTROLSOURCE', 'm.cAlias + ''.AKCIZ'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'AUTO_FILL_CONTEXT', '999.99'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'TITLE', 'Налоговая ставка'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.STAVKA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'TITLE', 'Без НДС'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.NO_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'TITLE', 'Сумма налога'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'TITLE', 'Полная стоимость'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_ALL'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'TITLE', 'Код страны'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01("DICTIONARY_COUNTRY", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "STATE_LINK, STATE_CODE, STATE_NAME", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'CONTROLSOURCE', 'm.cAlias+''.STATE_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'TITLE', 'Наименование страны'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'CONTROLSOURCE', 'm.cAlias+''.STATE_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'TITLE', 'Номер ГТД'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'CONTROLSOURCE', 'm.cAlias+''.NUM_TD'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'TYPE_FIELD_DICT', 'varchar(5)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'TITLE', 'Ссылка на ЭКР'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'CONTROLSOURCE', 'm.cAlias+''.EKR_LINK'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "EKR_LINK, EKR_CODE", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias+''.EKR_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_KOSGU", EVALUATE(m.cAliasOperate+''.EKR_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'CONTROLSOURCE', 'm.cAlias+''.SFIN_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO




GO
/****** Объект: Запрещать удалять ЭЦП отчета******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RS_REP_OPTIONS_NOTDEL')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RS_REP_OPTIONS_NOTDEL')
	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 = 'RS_REP_OPTIONS_NOTDEL')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RS_REP_OPTIONS_NOTDEL')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RS_REP_OPTIONS_NOTDEL'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RS_REP_OPTIONS_NOTDEL')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RS_REP_OPTIONS_NOTDEL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RS_REP_OPTIONS_NOTDEL', 'Запрещать удалять ЭЦП отчета', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RS_REP_OPTIONS_NOTDEL', NAME = 'Запрещать удалять ЭЦП отчета', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_REP_OPTIONS_ECP_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RS_REP_OPTIONS_NOTDEL'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'TITLE', 'Запрещать удалять ЭЦП отчета'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'CONTROLSOURCE', 'm.cAlias + ''.NotDel'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'TYPE_FIELD_DICT', 'CHAR(20)'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'SHORT_CODE_OBJ', 'NotDel'
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.NotDel'''
GO
EXEC X_SET_PROP 'RS_REP_OPTIONS_NOTDEL', 'CONTROL_NAME_EDIT', 'achkNotDel'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/****** Объект: Возможность всегда менять статусы у нижележащих отчетов******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ACCESS_STATUS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_COM_ACCESS_STATUS')
	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 = 'REP_OPTIONS_COM_ACCESS_STATUS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_COM_ACCESS_STATUS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ACCESS_STATUS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ACCESS_STATUS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REP_OPTIONS_COM_ACCESS_STATUS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REP_OPTIONS_COM_ACCESS_STATUS', 'Возможность всегда менять статусы у нижележащих отчетов', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REP_OPTIONS_COM_ACCESS_STATUS', NAME = 'Возможность всегда менять статусы у нижележащих отчетов', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REP_OPTIONS_COM_ACCESS_STATUS'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'TITLE', 'Разрешение смены статусов отчетов подведомственных организаций после сдачи сводного отчета'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'CONTROLSOURCE', 'm.cAlias + ''.ACCESS_STATUS'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'SHORT_CODE_OBJ', 'ACCESS_STATUS'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ACCESS_STATUS'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ACCESS_STATUS', 'CONTROL_NAME_EDIT', 'achkACCESS_STATUS'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
exec RN_SAVE_REPORT_KBK 0,'86n',0,'Справочники для 86н','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_ATR_DATE',0,'(86н) Справочник дат для атрибута дата модификации','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86n_SEND_ORG',0,'Список организаций которые размещаются на сайте','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_OGS',0,'Справочники ОГС','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_002',0,'(86н) Раздел 002','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_pril',0,'Приложения','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_001',0,'(86н) Раздел 001','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_004',0,'(86н) Раздел 004','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_005',0,'(86н) Раздел 005','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS',0,'Справочник ОГС для 86н','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_OKVED',0,'Справочник ОГС, ОКВЭД','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_CHIEF',0,'Руководители','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_RBS',0,'РБС, ГРБС','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_FOUNDER',0,'Учредитель','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_ADD_INFO',0,'ОГС, дополнительная информация','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_OKEI',0,'(86н) ОКЕИ','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'86n_SERVICE',0,'Справочник Услуг','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_KACH',0,'Показатели качества услуг','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_OB',0,'Показатели объема услуг','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_FO',0,'(86н) Справочник муницип.образований','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_IIS',0,'(86н) используемая информационная система для формир.гос.(мун.) заданий','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSE',0,'(86н) код сведений о корректировке ЕГРЮЛ на дату','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSY',0,'(86н) Код сведений о подтверждении деятельности учреждения','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_SO',0,'(86н) Выбор значения','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSK',0,'(86н) Код сведений о необходимости корректировки ЕГРЮЛ','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_P_VSR',0,'(86н) Вариант способа размещения информации на официальном сайте','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_TYPE_FILIAL',0,'(86н) Справочник типов филиалов','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_KAT_OBJ',0,'(86н) Справочник категорий объектов','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_CELEV_SUBS',0,'(86н) Справочник целевых субсидий','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'R_86N_BUDGET',0,'(86н)Справочник бюджетов','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_Service',0,'Справочник услуг, работ','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_2',0,'Справочник услуг часть2','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_3',0,'Справочник услуг, часть3','HEADER'
GO
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_4',0,'Справочник услуг часть4','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n',@link_self,'Справочники для 86н','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_ATR_DATE',@link_self,'(86н) Справочник дат для атрибута дата модификации','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86n_SEND_ORG',@link_self,'Список организаций которые размещаются на сайте','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_OGS',@link_self,'Справочники ОГС','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_002',@link_self,'(86н) Раздел 002','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_pril',@link_self,'Приложения','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_001',@link_self,'(86н) Раздел 001','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_004',@link_self,'(86н) Раздел 004','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_005',@link_self,'(86н) Раздел 005','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS',@link_self,'Справочник ОГС для 86н','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_OKVED',@link_self,'Справочник ОГС, ОКВЭД','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_CHIEF',@link_self,'Руководители','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_RBS',@link_self,'РБС, ГРБС','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_FOUNDER',@link_self,'Учредитель','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS_ADD_INFO',@link_self,'ОГС, дополнительная информация','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_OKEI',@link_self,'(86н) ОКЕИ','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'86n_SERVICE',@link_self,'Справочник Услуг','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_KACH',@link_self,'Показатели качества услуг','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_OB',@link_self,'Показатели объема услуг','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_FO',@link_self,'(86н) Справочник муницип.образований','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_IIS',@link_self,'(86н) используемая информационная система для формир.гос.(мун.) заданий','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSE',@link_self,'(86н) код сведений о корректировке ЕГРЮЛ на дату','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSY',@link_self,'(86н) Код сведений о подтверждении деятельности учреждения','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_SO',@link_self,'(86н) Выбор значения','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_KSK',@link_self,'(86н) Код сведений о необходимости корректировки ЕГРЮЛ','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_pril' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_P_VSR',@link_self,'(86н) Вариант способа размещения информации на официальном сайте','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_001' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_TYPE_FILIAL',@link_self,'(86н) Справочник типов филиалов','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_004' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_KAT_OBJ',@link_self,'(86н) Справочник категорий объектов','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_004' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_CELEV_SUBS',@link_self,'(86н) Справочник целевых субсидий','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_005' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86N_BUDGET',@link_self,'(86н)Справочник бюджетов','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_SERVICE' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_Service',@link_self,'Справочник услуг, работ','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_SERVICE' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_2',@link_self,'Справочник услуг часть2','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_SERVICE' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_3',@link_self,'Справочник услуг, часть3','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_SERVICE' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_SERVICE_4',@link_self,'Справочник услуг часть4','HEADER'
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111114',@link_self,'14.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111115',@link_self,'15.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111116',@link_self,'16.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111117',@link_self,'17.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111118',@link_self,'18.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111119',@link_self,'19.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111120',@link_self,'20.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111121',@link_self,'21.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111122',@link_self,'22.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111123',@link_self,'23.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111124',@link_self,'24.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111125',@link_self,'25.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111126',@link_self,'26.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111127',@link_self,'27.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111128',@link_self,'28.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111129',@link_self,'29.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111130',@link_self,'30.11.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111201',@link_self,'01.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111202',@link_self,'02.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111203',@link_self,'03.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111204',@link_self,'04.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111205',@link_self,'05.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111206',@link_self,'06.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111207',@link_self,'07.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111208',@link_self,'08.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111209',@link_self,'09.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111210',@link_self,'10.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111211',@link_self,'11.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111212',@link_self,'12.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111213',@link_self,'13.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111214',@link_self,'14.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111215',@link_self,'15.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111216',@link_self,'16.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111217',@link_self,'17.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111218',@link_self,'18.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111219',@link_self,'19.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111220',@link_self,'20.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111221',@link_self,'21.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111222',@link_self,'22.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111223',@link_self,'23.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111224',@link_self,'24.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111225',@link_self,'25.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111226',@link_self,'26.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111227',@link_self,'27.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111228',@link_self,'28.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111229',@link_self,'29.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111230',@link_self,'30.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20111231',@link_self,'31.12.2011','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120101',@link_self,'01.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120102',@link_self,'02.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120103',@link_self,'03.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120104',@link_self,'04.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120105',@link_self,'05.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120106',@link_self,'06.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120107',@link_self,'07.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120108',@link_self,'08.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120109',@link_self,'09.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120110',@link_self,'10.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120111',@link_self,'11.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120112',@link_self,'12.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120113',@link_self,'13.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120114',@link_self,'14.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120115',@link_self,'15.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120116',@link_self,'16.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120117',@link_self,'17.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120118',@link_self,'18.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120119',@link_self,'19.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120120',@link_self,'20.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120121',@link_self,'21.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120122',@link_self,'22.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120123',@link_self,'23.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120124',@link_self,'24.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120125',@link_self,'25.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120126',@link_self,'26.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120127',@link_self,'27.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120128',@link_self,'28.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120129',@link_self,'29.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120130',@link_self,'30.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120131',@link_self,'31.01.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120201',@link_self,'01.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120202',@link_self,'02.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120203',@link_self,'03.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120204',@link_self,'04.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120205',@link_self,'05.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120206',@link_self,'06.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120207',@link_self,'07.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120208',@link_self,'08.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120209',@link_self,'09.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120210',@link_self,'10.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120211',@link_self,'11.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120212',@link_self,'12.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120213',@link_self,'13.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120214',@link_self,'14.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120215',@link_self,'15.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120216',@link_self,'16.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120217',@link_self,'17.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120218',@link_self,'18.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120219',@link_self,'19.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120220',@link_self,'20.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120221',@link_self,'21.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120222',@link_self,'22.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120223',@link_self,'23.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120224',@link_self,'24.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120225',@link_self,'25.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120226',@link_self,'26.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120227',@link_self,'27.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120228',@link_self,'28.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120229',@link_self,'29.02.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120301',@link_self,'01.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120302',@link_self,'02.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120303',@link_self,'03.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120304',@link_self,'04.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120305',@link_self,'05.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120306',@link_self,'06.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120307',@link_self,'07.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120308',@link_self,'08.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120309',@link_self,'09.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120310',@link_self,'10.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120311',@link_self,'11.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120312',@link_self,'12.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120313',@link_self,'13.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120314',@link_self,'14.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120315',@link_self,'15.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120316',@link_self,'16.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120317',@link_self,'17.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120318',@link_self,'18.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120319',@link_self,'19.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120320',@link_self,'20.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120321',@link_self,'21.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120322',@link_self,'22.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120323',@link_self,'23.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120324',@link_self,'24.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120325',@link_self,'25.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120326',@link_self,'26.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120327',@link_self,'27.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120328',@link_self,'28.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120329',@link_self,'29.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120330',@link_self,'30.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120331',@link_self,'31.03.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120401',@link_self,'01.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120402',@link_self,'02.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120403',@link_self,'03.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120404',@link_self,'04.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120405',@link_self,'05.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120406',@link_self,'06.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120407',@link_self,'07.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120408',@link_self,'08.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120409',@link_self,'09.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120410',@link_self,'10.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120411',@link_self,'11.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120412',@link_self,'12.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120413',@link_self,'13.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120414',@link_self,'14.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120415',@link_self,'15.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120416',@link_self,'16.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120417',@link_self,'17.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120418',@link_self,'18.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120419',@link_self,'19.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120420',@link_self,'20.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120421',@link_self,'21.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120422',@link_self,'22.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120423',@link_self,'23.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120424',@link_self,'24.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120425',@link_self,'25.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120426',@link_self,'26.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120427',@link_self,'27.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120428',@link_self,'28.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120429',@link_self,'29.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120430',@link_self,'30.04.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120501',@link_self,'01.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120502',@link_self,'02.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120503',@link_self,'03.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120504',@link_self,'04.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120505',@link_self,'05.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120506',@link_self,'06.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120507',@link_self,'07.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120508',@link_self,'08.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120509',@link_self,'09.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120510',@link_self,'10.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120511',@link_self,'11.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120512',@link_self,'12.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120513',@link_self,'13.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120514',@link_self,'14.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120515',@link_self,'15.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120516',@link_self,'16.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120517',@link_self,'17.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120518',@link_self,'18.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120519',@link_self,'19.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120520',@link_self,'20.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120521',@link_self,'21.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120522',@link_self,'22.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120523',@link_self,'23.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120524',@link_self,'24.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120525',@link_self,'25.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120526',@link_self,'26.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120527',@link_self,'27.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120528',@link_self,'28.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120529',@link_self,'29.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120530',@link_self,'30.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120531',@link_self,'31.05.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120601',@link_self,'01.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120602',@link_self,'02.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120603',@link_self,'03.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120604',@link_self,'04.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120605',@link_self,'05.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120606',@link_self,'06.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120607',@link_self,'07.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120608',@link_self,'08.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120609',@link_self,'09.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120610',@link_self,'10.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120611',@link_self,'11.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120612',@link_self,'12.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120613',@link_self,'13.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120614',@link_self,'14.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120615',@link_self,'15.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120616',@link_self,'16.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120617',@link_self,'17.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120618',@link_self,'18.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120619',@link_self,'19.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120620',@link_self,'20.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120621',@link_self,'21.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120622',@link_self,'22.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120623',@link_self,'23.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120624',@link_self,'24.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120625',@link_self,'25.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120626',@link_self,'26.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120627',@link_self,'27.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120628',@link_self,'28.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120629',@link_self,'29.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120630',@link_self,'30.06.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120701',@link_self,'01.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120702',@link_self,'02.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120703',@link_self,'03.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120704',@link_self,'04.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120705',@link_self,'05.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120706',@link_self,'06.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120707',@link_self,'07.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120708',@link_self,'08.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120709',@link_self,'09.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120710',@link_self,'10.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120711',@link_self,'11.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120712',@link_self,'12.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120713',@link_self,'13.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120714',@link_self,'14.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120715',@link_self,'15.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120716',@link_self,'16.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120717',@link_self,'17.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120718',@link_self,'18.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120719',@link_self,'19.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120720',@link_self,'20.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120721',@link_self,'21.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120722',@link_self,'22.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120723',@link_self,'23.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120724',@link_self,'24.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120725',@link_self,'25.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120726',@link_self,'26.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120727',@link_self,'27.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120728',@link_self,'28.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120729',@link_self,'29.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120730',@link_self,'30.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120731',@link_self,'31.07.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120801',@link_self,'01.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120802',@link_self,'02.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120803',@link_self,'03.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120804',@link_self,'04.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120805',@link_self,'05.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120806',@link_self,'06.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120807',@link_self,'07.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120808',@link_self,'08.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120809',@link_self,'09.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120810',@link_self,'10.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120811',@link_self,'11.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120812',@link_self,'12.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120813',@link_self,'13.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120814',@link_self,'14.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120815',@link_self,'15.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120816',@link_self,'16.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120817',@link_self,'17.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120818',@link_self,'18.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120819',@link_self,'19.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120820',@link_self,'20.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120821',@link_self,'21.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120822',@link_self,'22.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120823',@link_self,'23.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120824',@link_self,'24.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120825',@link_self,'25.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120826',@link_self,'26.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120827',@link_self,'27.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120828',@link_self,'28.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120829',@link_self,'29.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120830',@link_self,'30.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120831',@link_self,'31.08.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120901',@link_self,'01.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120902',@link_self,'02.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120903',@link_self,'03.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120904',@link_self,'04.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120905',@link_self,'05.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120906',@link_self,'06.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120907',@link_self,'07.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120908',@link_self,'08.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120909',@link_self,'09.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120910',@link_self,'10.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120911',@link_self,'11.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120912',@link_self,'12.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120913',@link_self,'13.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120914',@link_self,'14.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120915',@link_self,'15.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120916',@link_self,'16.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120917',@link_self,'17.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120918',@link_self,'18.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120919',@link_self,'19.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120920',@link_self,'20.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120921',@link_self,'21.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120922',@link_self,'22.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120923',@link_self,'23.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120924',@link_self,'24.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120925',@link_self,'25.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120926',@link_self,'26.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120927',@link_self,'27.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120928',@link_self,'28.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120929',@link_self,'29.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20120930',@link_self,'30.09.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121001',@link_self,'01.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121002',@link_self,'02.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121003',@link_self,'03.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121004',@link_self,'04.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121005',@link_self,'05.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121006',@link_self,'06.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121007',@link_self,'07.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121008',@link_self,'08.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121009',@link_self,'09.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121010',@link_self,'10.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121011',@link_self,'11.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121012',@link_self,'12.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121013',@link_self,'13.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121014',@link_self,'14.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121015',@link_self,'15.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121016',@link_self,'16.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121017',@link_self,'17.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121018',@link_self,'18.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121019',@link_self,'19.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121020',@link_self,'20.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121021',@link_self,'21.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121022',@link_self,'22.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121023',@link_self,'23.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121024',@link_self,'24.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121025',@link_self,'25.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121026',@link_self,'26.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121027',@link_self,'27.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121028',@link_self,'28.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121029',@link_self,'29.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121030',@link_self,'30.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121031',@link_self,'31.10.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121101',@link_self,'01.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121102',@link_self,'02.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121103',@link_self,'03.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121104',@link_self,'04.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121105',@link_self,'05.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121106',@link_self,'06.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121107',@link_self,'07.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121108',@link_self,'08.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121109',@link_self,'09.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121110',@link_self,'10.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121111',@link_self,'11.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121112',@link_self,'12.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121113',@link_self,'13.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121114',@link_self,'14.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121115',@link_self,'15.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121116',@link_self,'16.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121117',@link_self,'17.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121118',@link_self,'18.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121119',@link_self,'19.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121120',@link_self,'20.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121121',@link_self,'21.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121122',@link_self,'22.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121123',@link_self,'23.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121124',@link_self,'24.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121125',@link_self,'25.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121126',@link_self,'26.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121127',@link_self,'27.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121128',@link_self,'28.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121129',@link_self,'29.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121130',@link_self,'30.11.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121201',@link_self,'01.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121202',@link_self,'02.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121203',@link_self,'03.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121204',@link_self,'04.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121205',@link_self,'05.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121206',@link_self,'06.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121207',@link_self,'07.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121208',@link_self,'08.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121209',@link_self,'09.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121210',@link_self,'10.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121211',@link_self,'11.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121212',@link_self,'12.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121213',@link_self,'13.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121214',@link_self,'14.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121215',@link_self,'15.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121216',@link_self,'16.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'20121217',@link_self,'17.12.2012','R_86N_ATR_DATE',0,'',0,'','',NULL,NULL
GO

GO


GO


GO


GO


GO


GO


GO


GO


GO


GO


GO


GO


GO


GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'100 ЛИСТ',@link_self,'Сто листов','R_86n_OKEI',0,'626',0,'100 л.','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'100 УПАК',@link_self,'Сто упаковок','R_86n_OKEI',0,'781',0,'100 упак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'100 ШТ',@link_self,'Сто штук','R_86n_OKEI',0,'797',0,'100 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'100 ЯЩ',@link_self,'Сто ящиков','R_86n_OKEI',0,'683',0,'100 ящ.','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'2 ДЕС',@link_self,'Два десятка','R_86n_OKEI',0,'730',0,'20','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'А',@link_self,'Ампер','R_86n_OKEI',0,'260',0,'А','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'А.Ч',@link_self,'Ампер-час (3,6 кКл)','R_86n_OKEI',0,'263',0,'А.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АВТО Т',@link_self,'Автотонна','R_86n_OKEI',0,'513',0,'авто т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АВТОМОБ.ДН',@link_self,'Автомобиле-день','R_86n_OKEI',0,'959',0,'автомоб.дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АМПУЛ',@link_self,'Ампула','R_86n_OKEI',0,'870',0,'ампул','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АР',@link_self,'Ар (100 м2)','R_86n_OKEI',0,'109',0,'а','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АТМ',@link_self,'Физическая атмосфера (101325 Па)','R_86n_OKEI',0,'300',0,'атм','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'АТТ',@link_self,'Техническая атмосфера (98066,5 Па)','R_86n_OKEI',0,'301',0,'ат','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БАЙТ',@link_self,'Байт','R_86n_OKEI',0,'255',0,'бай','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БАР',@link_self,'Бар','R_86n_OKEI',0,'309',0,'бар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БИЛЛ ШТ (ЕВР); ТРИЛЛ ШТ',@link_self,'Биллион штук (Европа); триллион штук','R_86n_OKEI',0,'801',0,'10^12 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БИТ',@link_self,'Бит','R_86n_OKEI',0,'254',0,'бит','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БК',@link_self,'Беккерель','R_86n_OKEI',0,'323',0,'Бк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БОБ',@link_self,'Бобина','R_86n_OKEI',0,'616',0,'боб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БОД',@link_self,'Бод','R_86n_OKEI',0,'258',0,'бод','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БРУТТ. РЕГИСТР Т',@link_self,'Брутто-регистровая тонна (2,8316 м3)','R_86n_OKEI',0,'181',0,'БРТ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'БУТ',@link_self,'Бутылка','R_86n_OKEI',0,'868',0,'бут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'В',@link_self,'Вольт','R_86n_OKEI',0,'222',0,'В','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'В.А',@link_self,'Вольт-ампер','R_86n_OKEI',0,'226',0,'В.А','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ВАГ (МАШ).ДН',@link_self,'Вагоно(машино)-день','R_86n_OKEI',0,'950',0,'ваг (маш).дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ВАГ.СУТ',@link_self,'Вагоно-сутки','R_86n_OKEI',0,'954',0,'ваг.сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ВБ',@link_self,'Вебер','R_86n_OKEI',0,'324',0,'Вб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ВТ',@link_self,'Ватт','R_86n_OKEI',0,'212',0,'Вт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ВТ.Ч',@link_self,'Ватт-час','R_86n_OKEI',0,'243',0,'Вт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Г',@link_self,'Грамм','R_86n_OKEI',0,'163',0,'г','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Г ДЕЛЯЩ ИЗОТОП',@link_self,'Грамм делящихся изотопов','R_86n_OKEI',0,'306',0,'г Д/И','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Г/КВТ.Ч',@link_self,'Грамм на киловатт-час','R_86n_OKEI',0,'510',0,'г/кВт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГА',@link_self,'Гектар','R_86n_OKEI',0,'059',0,'га','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГБАР',@link_self,'Гектобар','R_86n_OKEI',0,'310',0,'гб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГГ',@link_self,'Гектограмм','R_86n_OKEI',0,'160',0,'гг','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГИГАБК',@link_self,'Гигабеккерель','R_86n_OKEI',0,'302',0,'ГБк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГИГАВТ.Ч',@link_self,'Гигаватт-час (миллион киловатт-часов)','R_86n_OKEI',0,'247',0,'ГВт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГИГАКАЛ',@link_self,'Гигакалория','R_86n_OKEI',0,'233',0,'Гкал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГИГАКАЛ/Ч',@link_self,'Гигакалория в час','R_86n_OKEI',0,'238',0,'Гкал/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГЛ',@link_self,'Гектолитр','R_86n_OKEI',0,'122',0,'гл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГЛ ЧИСТ СПИРТ',@link_self,'Гектолитр чистого (100%) спирта','R_86n_OKEI',0,'833',0,'Гл 100% спирта','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГН',@link_self,'Генри','R_86n_OKEI',0,'287',0,'Гн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГОД; ЛЕТ',@link_self,'Год','R_86n_OKEI',0,'366',0,'г; лет','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГОЛ',@link_self,'Голова','R_86n_OKEI',0,'836',0,'гол','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГРАД ФАРЕНГ',@link_self,'Градус Фаренгейта','R_86n_OKEI',0,'281',0,'град. F','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГРАД ЦЕЛЬС',@link_self,'Градус Цельсия','R_86n_OKEI',0,'280',0,'град. C','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ГЦ',@link_self,'Герц','R_86n_OKEI',0,'290',0,'Гц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЕДВЕЙТ.Т',@link_self,'Дедвейт-тонна','R_86n_OKEI',0,'515',0,'дедвейт.т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЕК',@link_self,'Декада','R_86n_OKEI',0,'361',0,'дек','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЕС ПАР',@link_self,'Десять пар','R_86n_OKEI',0,'732',0,'10 пар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЕСЛЕТ',@link_self,'Десятилетие','R_86n_OKEI',0,'368',0,'деслет','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЖ',@link_self,'Джоуль','R_86n_OKEI',0,'271',0,'Дж','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДКЛ',@link_self,'Декалитр','R_86n_OKEI',0,'116',0,'дкл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЛ',@link_self,'Децилитр','R_86n_OKEI',0,'118',0,'дл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДМ',@link_self,'Дециметр','R_86n_OKEI',0,'005',0,'дм','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДМ2',@link_self,'Квадратный дециметр','R_86n_OKEI',0,'053',0,'дм2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДОЗ',@link_self,'Доза','R_86n_OKEI',0,'639',0,'доз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДОМХОЗ',@link_self,'Домохозяйство','R_86n_OKEI',0,'899',0,'домхоз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЖИНА',@link_self,'Дюжина (12 шт.)','R_86n_OKEI',0,'641',0,'дюжина','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЖИНА ПАР',@link_self,'Дюжина пар','R_86n_OKEI',0,'733',0,'дюжина пар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЖИНА РУЛ',@link_self,'Дюжина рулонов','R_86n_OKEI',0,'737',0,'дюжина рул','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЖИНА УПАК',@link_self,'Дюжина упаковок','R_86n_OKEI',0,'780',0,'дюжина упак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЖИНА ШТ',@link_self,'Дюжина штук','R_86n_OKEI',0,'740',0,'дюжина шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЙМ',@link_self,'Дюйм (25,4 мм)','R_86n_OKEI',0,'039',0,'дюйм','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЙМ2',@link_self,'Квадратный дюйм (645,16 мм2)','R_86n_OKEI',0,'071',0,'дюйм2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ДЮЙМ3',@link_self,'Кубический дюйм (16387,1 мм3)','R_86n_OKEI',0,'131',0,'дюйм3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЕД',@link_self,'Единица','R_86n_OKEI',0,'642',0,'ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЗНАК',@link_self,'Знак','R_86n_OKEI',0,'922',0,'знак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ИЗД',@link_self,'Изделие','R_86n_OKEI',0,'657',0,'изд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'К',@link_self,'Кельвин','R_86n_OKEI',0,'288',0,'K','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КАЛ/Ч',@link_self,'Калория в час','R_86n_OKEI',0,'236',0,'кал/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КАНАЛ',@link_self,'Канал','R_86n_OKEI',0,'661',0,'канал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КАНАЛ. КМ',@link_self,'Канало-километр','R_86n_OKEI',0,'977',0,'канал. км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КАНАЛ. КОНЦ',@link_self,'Канало-концы','R_86n_OKEI',0,'978',0,'канал. конц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КАР',@link_self,'Метрический карат','R_86n_OKEI',0,'162',0,'кар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КБАЙТ',@link_self,'Килобайт','R_86n_OKEI',0,'256',0,'кбайт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КБАР',@link_self,'Килобар','R_86n_OKEI',0,'312',0,'кб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВ',@link_self,'Киловольт','R_86n_OKEI',0,'223',0,'кВ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВ.А',@link_self,'Киловольт-ампер','R_86n_OKEI',0,'227',0,'кВ.А','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВ.А Р',@link_self,'Киловольт-ампер реактивный','R_86n_OKEI',0,'248',0,'кВ.А Р','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВАДР РУБ',@link_self,'Квадрильон рублей','R_86n_OKEI',0,'388',0,'10^15 руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВАР',@link_self,'Киловар','R_86n_OKEI',0,'230',0,'квар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВАРТ',@link_self,'Квартал','R_86n_OKEI',0,'364',0,'кварт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВАРТ',@link_self,'Квартира','R_86n_OKEI',0,'909',0,'кварт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВИНТ ШТ',@link_self,'Квинтильон штук (Европа)','R_86n_OKEI',0,'802',0,'10^18 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВТ',@link_self,'Киловатт','R_86n_OKEI',0,'214',0,'кВт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КВТ.Ч',@link_self,'Киловатт-час','R_86n_OKEI',0,'245',0,'кВт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ',@link_self,'Килограмм','R_86n_OKEI',0,'166',0,'кг','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ 90 ПРОЦ СУХ ВЕЩ',@link_self,'Килограмм 90%-го сухого вещества','R_86n_OKEI',0,'845',0,'кг 90% с/в','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ АЗОТ',@link_self,'Килограмм азота','R_86n_OKEI',0,'861',0,'кг N','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ ГИДРОКСИД КАЛИЯ',@link_self,'Килограмм гидроксида калия','R_86n_OKEI',0,'859',0,'кг КОН','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ ГИДРОКСИД НАТРИЯ',@link_self,'Килограмм гидроксида натрия','R_86n_OKEI',0,'863',0,'кг NaOH','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ ОКСИД КАЛИЯ',@link_self,'Килограмм оксида калия','R_86n_OKEI',0,'852',0,'кг К2О','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ ПЕРОКСИД ВОДОРОДА',@link_self,'Килограмм пероксида водорода','R_86n_OKEI',0,'841',0,'кг H2О2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ ПЯТИОКИСЬ ФОСФОРА',@link_self,'Килограмм пятиокиси фосфора','R_86n_OKEI',0,'865',0,'кг Р2О5','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ УРАН',@link_self,'Килограмм урана','R_86n_OKEI',0,'867',0,'кг U','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ/ГИГАКАЛ',@link_self,'Килограмм на гигакалорию','R_86n_OKEI',0,'511',0,'кг/Гкал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ/М3',@link_self,'Килограмм на кубический метр','R_86n_OKEI',0,'316',0,'кг/м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ/С',@link_self,'Килограмм в секунду','R_86n_OKEI',0,'499',0,'кг/с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГ/СМ2',@link_self,'Килограмм на квадратный сантиметр','R_86n_OKEI',0,'317',0,'кг/см^2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КГЦ',@link_self,'Килогерц','R_86n_OKEI',0,'291',0,'кГц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КД',@link_self,'Кандела','R_86n_OKEI',0,'282',0,'кд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КДЖ',@link_self,'Килоджоуль','R_86n_OKEI',0,'273',0,'кДж','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КИ',@link_self,'Кюри','R_86n_OKEI',0,'305',0,'Ки','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ККАЛ',@link_self,'Килокалория','R_86n_OKEI',0,'232',0,'ккал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ККАЛ/Ч',@link_self,'Килокалория в час','R_86n_OKEI',0,'237',0,'ккал/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КЛ',@link_self,'Кулон','R_86n_OKEI',0,'270',0,'Кл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КЛ/КГ',@link_self,'Кулон на килограмм','R_86n_OKEI',0,'349',0,'Кл/кг','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КМ УСЛ ТРУБ',@link_self,'Километр условных труб','R_86n_OKEI',0,'049',0,'км усл. труб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КМ/Ч',@link_self,'Километр в час','R_86n_OKEI',0,'333',0,'км/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КМ; ТЫС М',@link_self,'Километр; тысяча метров','R_86n_OKEI',0,'008',0,'км; 10^3 м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КМ2',@link_self,'Квадратный километр','R_86n_OKEI',0,'061',0,'км2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КОЕК',@link_self,'Койка','R_86n_OKEI',0,'911',0,'коек','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КОМПЛ',@link_self,'Комплект','R_86n_OKEI',0,'839',0,'компл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КОРМ. ДН',@link_self,'Кормо-день','R_86n_OKEI',0,'971',0,'корм. дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КПА',@link_self,'Килопаскаль','R_86n_OKEI',0,'297',0,'кПа','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КРЕП СПИРТ ПО МАССЕ',@link_self,'Крепость спирта по массе','R_86n_OKEI',0,'820',0,'креп. спирта по массе','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КРЕП СПИРТ ПО ОБЪЕМ',@link_self,'Крепость спирта по объему','R_86n_OKEI',0,'821',0,'креп. спирта по объему','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'КТ',@link_self,'Килотонна','R_86n_OKEI',0,'170',0,'10^3 т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Л ЧИСТ СПИРТ',@link_self,'Литр чистого (100%) спирта','R_86n_OKEI',0,'831',0,'л 100% спирта','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Л; ДМ3',@link_self,'Литр; кубический дециметр','R_86n_OKEI',0,'112',0,'л; дм3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛИСТ',@link_self,'Лист','R_86n_OKEI',0,'625',0,'л.','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛИСТ АВТ',@link_self,'Лист авторский','R_86n_OKEI',0,'918',0,'л. авт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛИСТ ПЕЧ',@link_self,'Лист печатный','R_86n_OKEI',0,'920',0,'л. печ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛИСТ УЧ.ИЗД',@link_self,'Лист учетно-издательский','R_86n_OKEI',0,'921',0,'л. уч.-изд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛК',@link_self,'Люкс','R_86n_OKEI',0,'283',0,'лк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛМ',@link_self,'Люмен','R_86n_OKEI',0,'284',0,'лм','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЛС',@link_self,'Лошадиная сила','R_86n_OKEI',0,'251',0,'л. с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М',@link_self,'Метр','R_86n_OKEI',0,'006',0,'м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М/С',@link_self,'Метр в секунду','R_86n_OKEI',0,'328',0,'м/с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М/С2',@link_self,'Метр на секунду в квадрате','R_86n_OKEI',0,'335',0,'м/с2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М/Ч',@link_self,'Метр в час','R_86n_OKEI',0,'231',0,'м/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М2',@link_self,'Квадратный метр','R_86n_OKEI',0,'055',0,'м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М2 ЖИЛ ПЛ',@link_self,'Квадратный метр жилой площади','R_86n_OKEI',0,'084',0,'м2 жил. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М2 ОБЩ ПЛ',@link_self,'Квадратный метр общей площади','R_86n_OKEI',0,'081',0,'м2 общ. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М2 УЧ.ЛАБ ЗДАН',@link_self,'Квадратный метр учебно-лабораторных зданий','R_86n_OKEI',0,'087',0,'м2 уч. лаб. здан','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М3',@link_self,'Кубический метр','R_86n_OKEI',0,'113',0,'м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М3/С',@link_self,'Кубический метр в секунду','R_86n_OKEI',0,'596',0,'м3/с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'М3/Ч',@link_self,'Кубический метр в час','R_86n_OKEI',0,'598',0,'м3/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МБАЙТ',@link_self,'Мегабайт','R_86n_OKEI',0,'257',0,'Мбайт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МБАР',@link_self,'Миллибар','R_86n_OKEI',0,'308',0,'мб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МГ',@link_self,'Миллиграмм','R_86n_OKEI',0,'161',0,'мг','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАВ.А',@link_self,'Мегавольт-ампер (тысяча киловольт-ампер)','R_86n_OKEI',0,'228',0,'МВ.А','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАВТ.Ч; ТЫС КВТ.Ч',@link_self,'Мегаватт-час; 1000 киловатт-часов','R_86n_OKEI',0,'246',0,'МВт.ч; 10^3 кВт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАВТ; ТЫС КВТ',@link_self,'Мегаватт; тысяча киловатт','R_86n_OKEI',0,'215',0,'МВт; 10^3 кВт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАГЦ',@link_self,'Мегагерц','R_86n_OKEI',0,'292',0,'МГц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАЛ',@link_self,'Мегалитр','R_86n_OKEI',0,'126',0,'Мл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАМ; МЛН М',@link_self,'Мегаметр; миллион метров','R_86n_OKEI',0,'009',0,'Мм; 10^6 м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕГАПА',@link_self,'Мегапаскаль','R_86n_OKEI',0,'298',0,'МПа','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕС',@link_self,'Месяц','R_86n_OKEI',0,'362',0,'мес','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЕСТ',@link_self,'Место','R_86n_OKEI',0,'698',0,'мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МИЛЬ',@link_self,'Морская миля (1852 м)','R_86n_OKEI',0,'047',0,'миля','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МИН',@link_self,'Минута','R_86n_OKEI',0,'355',0,'мин','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МИН ЗАРАБОТН ПЛАТ',@link_self,'Минимальная заработная плата','R_86n_OKEI',0,'560',0,'мин. заработн. плат','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МКИ',@link_self,'Милликюри','R_86n_OKEI',0,'304',0,'мКи','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МКС',@link_self,'Микросекунда','R_86n_OKEI',0,'352',0,'мкс','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН А.Ч',@link_self,'Миллион ампер-часов','R_86n_OKEI',0,'241',0,'10^6 А.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ГИГАКАЛ',@link_self,'Миллион гигакалорий','R_86n_OKEI',0,'235',0,'10^6 Гкал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ГОЛ/ГОД',@link_self,'Миллион голов в год','R_86n_OKEI',0,'557',0,'10^6 гол/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ДКЛ',@link_self,'Миллион декалитров','R_86n_OKEI',0,'120',0,'10^6 дкл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ДМ2',@link_self,'Миллион квадратных дециметров','R_86n_OKEI',0,'056',0,'10^6 дм2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ДОЗ',@link_self,'Миллион доз','R_86n_OKEI',0,'937',0,'10^6 доз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ДОМХОЗ',@link_self,'Миллион домохозяйств','R_86n_OKEI',0,'901',0,'10^6 домхоз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЕД',@link_self,'Миллион единиц','R_86n_OKEI',0,'644',0,'10^6 ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЕД/ГОД',@link_self,'Миллион единиц в год','R_86n_OKEI',0,'544',0,'10^6 ед/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН КАР',@link_self,'Миллион каратов метрических','R_86n_OKEI',0,'167',0,'10^6 кар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН КВ.А',@link_self,'Миллион киловольт-ампер','R_86n_OKEI',0,'242',0,'10^6 кВ.А','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЛИСТ.ОТТИСК',@link_self,'Миллион листов-оттисков','R_86n_OKEI',0,'949',0,'10^6 лист.оттиск','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЛС',@link_self,'Миллион лошадиных сил','R_86n_OKEI',0,'253',0,'10^6 л. с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М2',@link_self,'Миллион квадратных метров','R_86n_OKEI',0,'057',0,'10^6 м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М2 2ММ ИСЧ',@link_self,'Миллион квадратных метров в двухмиллиметровом исчислении','R_86n_OKEI',0,'089',0,'10^6 м2 2 мм исч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М2 ЖИЛ ПЛ',@link_self,'Миллион квадратных метров жилой площади','R_86n_OKEI',0,'086',0,'10^6 м2 жил. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М2. ОБЩ ПЛ',@link_self,'Миллион квадратных метров общей площади','R_86n_OKEI',0,'083',0,'10^6 м2 общ. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М3',@link_self,'Миллион кубических метров','R_86n_OKEI',0,'159',0,'10^6 м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН М3 ПЕРЕРАБ ГАЗА',@link_self,'Миллион кубических метров переработки газа','R_86n_OKEI',0,'125',0,'10^6 м3 перераб. газа','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ПАР',@link_self,'Миллион пар','R_86n_OKEI',0,'838',0,'10^6 пар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ПАСС. МЕСТ. МИЛЬ',@link_self,'Миллион пассажиро-место-миль','R_86n_OKEI',0,'970',0,'10^6 пасс. мест. миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ПАСС. МИЛЬ',@link_self,'Миллион пассажиро-миль','R_86n_OKEI',0,'968',0,'10^6 пасс. миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ПАСС.КМ',@link_self,'Миллион пассажиро-километров','R_86n_OKEI',0,'424',0,'10^6 пасс. км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ПОЛ Л',@link_self,'Миллион полулитров','R_86n_OKEI',0,'129',0,'10^6 пол. л','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН РУБ',@link_self,'Миллион рублей','R_86n_OKEI',0,'385',0,'10^6 руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН СЕМЕЙ',@link_self,'Миллион семей','R_86n_OKEI',0,'898',0,'10^6 семей','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т',@link_self,'Миллион тонн','R_86n_OKEI',0,'171',0,'10^6 т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т КОРМ ЕД',@link_self,'Миллион тонн кормовых единиц','R_86n_OKEI',0,'982',0,'10^6 корм ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т УСЛ ТОПЛ',@link_self,'Миллион тонн условного топлива','R_86n_OKEI',0,'176',0,'10^6 т усл. топл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т. МИЛЬ',@link_self,'Миллион тонно-миль','R_86n_OKEI',0,'967',0,'10^6 т. миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т.КМ',@link_self,'Миллион тонно-километров','R_86n_OKEI',0,'451',0,'10^6 т. км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН Т/ГОД',@link_self,'Миллион тонн в год','R_86n_OKEI',0,'550',0,'10^6 т/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ТОННАЖ. МИЛЬ',@link_self,'Миллион тоннаже-миль','R_86n_OKEI',0,'969',0,'10^6 тоннаж. миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УПАК',@link_self,'Миллион упаковок','R_86n_OKEI',0,'779',0,'10^6 упак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УСЛ БАНК',@link_self,'Миллион условных банок','R_86n_OKEI',0,'883',0,'10^6 усл. банк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УСЛ ЕД',@link_self,'Миллион условных единиц','R_86n_OKEI',0,'878',0,'10^6 усл. ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УСЛ КИРП',@link_self,'Миллион условных кирпичей','R_86n_OKEI',0,'895',0,'10^6 усл. кирп','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УСЛ КУС',@link_self,'Миллион условных кусков','R_86n_OKEI',0,'886',0,'10^6 усл. кус','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН УСЛ М2',@link_self,'Миллион условных квадратных метров','R_86n_OKEI',0,'064',0,'10^6 усл. м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЧЕЛ',@link_self,'Миллион человек','R_86n_OKEI',0,'794',0,'10^6 чел','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ШТ',@link_self,'Миллион штук','R_86n_OKEI',0,'799',0,'10^6 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛН ЭКЗ',@link_self,'Миллион экземпляров','R_86n_OKEI',0,'808',0,'10^6 экз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛРД КВТ.Ч',@link_self,'Миллиард киловатт-часов','R_86n_OKEI',0,'249',0,'10^9 кВт.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛРД М3',@link_self,'Миллиард кубических метров','R_86n_OKEI',0,'115',0,'10^9 м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛРД РУБ',@link_self,'Миллиард рублей','R_86n_OKEI',0,'386',0,'10^9 руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛРД ШТ',@link_self,'Миллиард штук','R_86n_OKEI',0,'800',0,'10^9 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'МЛС',@link_self,'Миллисекунда','R_86n_OKEI',0,'353',0,'млс','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ММ',@link_self,'Миллиметр','R_86n_OKEI',0,'003',0,'мм','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ММ ВОД СТ',@link_self,'Миллиметр водяного столба','R_86n_OKEI',0,'337',0,'мм вод. ст','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ММ РТ СТ',@link_self,'Миллиметр ртутного столба','R_86n_OKEI',0,'338',0,'мм рт. ст','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ММ2',@link_self,'Квадратный миллиметр','R_86n_OKEI',0,'050',0,'мм2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ММ3',@link_self,'Кубический миллиметр','R_86n_OKEI',0,'110',0,'мм3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Н',@link_self,'Ньютон','R_86n_OKEI',0,'289',0,'Н','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'НАБОР',@link_self,'Набор','R_86n_OKEI',0,'704',0,'набор','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'НЕД',@link_self,'Неделя','R_86n_OKEI',0,'360',0,'нед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'НОМ',@link_self,'Номер','R_86n_OKEI',0,'908',0,'ном','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ОБ/МИН',@link_self,'Оборот в минуту','R_86n_OKEI',0,'331',0,'об/мин','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ОБ/С',@link_self,'Оборот в секунду','R_86n_OKEI',0,'330',0,'об/с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ОМ',@link_self,'Ом','R_86n_OKEI',0,'274',0,'Ом','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПА',@link_self,'Паскаль','R_86n_OKEI',0,'294',0,'Па','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПАР',@link_self,'Пара (2 шт.)','R_86n_OKEI',0,'715',0,'пар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПАР/СМЕН',@link_self,'Пара в смену','R_86n_OKEI',0,'547',0,'пар/смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПАСС МЕСТ',@link_self,'Пассажирское место (пассажирских мест)','R_86n_OKEI',0,'421',0,'пасс. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПАСС.КМ',@link_self,'Пассажиро-километр','R_86n_OKEI',0,'414',0,'пасс.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПАСС.ПОТОК',@link_self,'Пассажиропоток','R_86n_OKEI',0,'427',0,'пасс.поток','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПЛОТН М3',@link_self,'Плотный кубический метр','R_86n_OKEI',0,'121',0,'плотн. м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПОГ М',@link_self,'Погонный метр','R_86n_OKEI',0,'018',0,'пог. м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПОЛГОД',@link_self,'Полугодие','R_86n_OKEI',0,'365',0,'полгода','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПОСАД МЕСТ',@link_self,'Посадочное место','R_86n_OKEI',0,'906',0,'посад. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПОСЕЩ/СМЕН',@link_self,'Посещение в смену','R_86n_OKEI',0,'545',0,'посещ/смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПОСЫЛ',@link_self,'Посылка','R_86n_OKEI',0,'734',0,'посыл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПРИВЕД.Ч',@link_self,'Приведенный час','R_86n_OKEI',0,'963',0,'привед.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПРОМИЛЛЕ',@link_self,'Промилле (0,1 процента)','R_86n_OKEI',0,'746',0,'промилле','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ПРОЦ',@link_self,'Процент','R_86n_OKEI',0,'744',0,'%','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'РАБ МЕСТ',@link_self,'Рабочее место','R_86n_OKEI',0,'904',0,'раб. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'РУБ',@link_self,'Рубль','R_86n_OKEI',0,'383',0,'руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'РУЛ',@link_self,'Рулон','R_86n_OKEI',0,'736',0,'рул','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'С',@link_self,'Секунда','R_86n_OKEI',0,'354',0,'с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'САМОЛЕТ.КМ',@link_self,'Самолето-километр','R_86n_OKEI',0,'964',0,'самолет.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СГ',@link_self,'Сантиграмм','R_86n_OKEI',0,'173',0,'сг','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СЕКЦ',@link_self,'Секция','R_86n_OKEI',0,'840',0,'секц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СЕМЕЙ',@link_self,'Семья','R_86n_OKEI',0,'896',0,'семей','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СИ',@link_self,'Сименс','R_86n_OKEI',0,'296',0,'См','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СИМВОЛ',@link_self,'Символ','R_86n_OKEI',0,'924',0,'символ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СЛОВО',@link_self,'Слово','R_86n_OKEI',0,'923',0,'слово','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СМ',@link_self,'Сантиметр','R_86n_OKEI',0,'004',0,'см','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СМ ВОД СТ',@link_self,'Сантиметр водяного столба','R_86n_OKEI',0,'339',0,'см вод. ст','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СМ2',@link_self,'Квадратный сантиметр','R_86n_OKEI',0,'051',0,'см2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СМ3; МЛ',@link_self,'Кубический сантиметр; миллилитр','R_86n_OKEI',0,'111',0,'см3; мл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СМЕН',@link_self,'Смена','R_86n_OKEI',0,'917',0,'смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СТАНЦ',@link_self,'Станция','R_86n_OKEI',0,'762',0,'станц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СУГО. СУТ',@link_self,'Суго-сутки','R_86n_OKEI',0,'975',0,'суго. сут.','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СУД.СУТ',@link_self,'Судо-сутки','R_86n_OKEI',0,'983',0,'суд.сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'СУТ; ДН',@link_self,'Сутки','R_86n_OKEI',0,'359',0,'сут; дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т',@link_self,'Тонна; метрическая тонна (1000 кг)','R_86n_OKEI',0,'168',0,'т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т 90 ПРОЦ СУХ ВЕЩ',@link_self,'Тонна 90%-го сухого вещества','R_86n_OKEI',0,'847',0,'т 90% с/в','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т ГРУЗОПОД',@link_self,'Грузоподъемность в метрических тоннах','R_86n_OKEI',0,'185',0,'т грп','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т ПАР/Ч',@link_self,'Тонна пара в час','R_86n_OKEI',0,'533',0,'т пар/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т ПЕРЕРАБ/СУТ',@link_self,'Тонна переработки в сутки','R_86n_OKEI',0,'552',0,'т перераб/сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т ТЯГИ',@link_self,'Тонна тяги','R_86n_OKEI',0,'514',0,'т.тяги','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т УСЛ ТОПЛ',@link_self,'Тонна условного топлива','R_86n_OKEI',0,'172',0,'т усл. топл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т.КМ',@link_self,'Тонно-километр','R_86n_OKEI',0,'449',0,'т.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т.НОМ',@link_self,'Тонно-номер','R_86n_OKEI',0,'512',0,'т.ном','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т.ТАНИД',@link_self,'Тонно-танид','R_86n_OKEI',0,'516',0,'т.танид','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т/СМЕН',@link_self,'Тонна в смену','R_86n_OKEI',0,'536',0,'т/смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т/СУТ',@link_self,'Тонна в сутки','R_86n_OKEI',0,'535',0,'т/сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Т/Ч',@link_self,'Тонна в час','R_86n_OKEI',0,'534',0,'т/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЛ',@link_self,'Тесла','R_86n_OKEI',0,'313',0,'Тл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТОМ КНИЖН ФОНД',@link_self,'Том книжного фонда','R_86n_OKEI',0,'913',0,'том книжн. фонд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТРИЛЛ РУБ',@link_self,'Триллион рублей','R_86n_OKEI',0,'387',0,'10^12 руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС А.Ч',@link_self,'Тысяча ампер-часов','R_86n_OKEI',0,'264',0,'10^3 А.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС АВТОМОБ. КМ',@link_self,'Тысяча автомобиле-километров','R_86n_OKEI',0,'973',0,'10^3 автомоб. км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС АВТОМОБ.МЕСТ. ДН',@link_self,'Тысяча автомобиле-место-дней','R_86n_OKEI',0,'962',0,'10^3 автомоб.мест. дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС АВТОМОБ.Т.ДН',@link_self,'Тысяча автомобиле-тонно-дней','R_86n_OKEI',0,'960',0,'10^3 автомоб.т.дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС АВТОМОБ.Ч',@link_self,'Тысяча автомобиле-часов','R_86n_OKEI',0,'961',0,'10^3 автомоб.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС АМПУЛ',@link_self,'Тысяча ампул','R_86n_OKEI',0,'871',0,'10^3 ампул','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС БУТ',@link_self,'Тысяча бутылок','R_86n_OKEI',0,'869',0,'10^3 бут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ВАГ (МАШ).КМ',@link_self,'Тысяча вагоно-(машино)-километров','R_86n_OKEI',0,'952',0,'10^3 ваг (маш).км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ВАГ (МАШ).Ч',@link_self,'Тысяча вагоно-(машино)-часов','R_86n_OKEI',0,'951',0,'10^3 ваг (маш).ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ГА',@link_self,'Тысяча гектаров','R_86n_OKEI',0,'060',0,'10^3 га','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ГА ПОРЦ',@link_self,'Тысяча гектаров порций','R_86n_OKEI',0,'724',0,'10^3 га порц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ГИГАКАЛ',@link_self,'Тысяча гигакалорий','R_86n_OKEI',0,'234',0,'10^3 Гкал','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ГИГАКАЛ/Ч',@link_self,'Тысяча гигакалорий в час','R_86n_OKEI',0,'239',0,'10^3 Гкал/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ГОЛ/ГОД',@link_self,'Тысяча голов в год','R_86n_OKEI',0,'556',0,'10^3 гол/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ДКЛ',@link_self,'Тысяча декалитров','R_86n_OKEI',0,'119',0,'10^3 дкл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ДМ2',@link_self,'Тысяча квадратных дециметров','R_86n_OKEI',0,'054',0,'10^3 дм2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ДОЗ',@link_self,'Тысяча доз','R_86n_OKEI',0,'640',0,'10^3 доз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ДОЛЛАР',@link_self,'Тысяча долларов','R_86n_OKEI',0,'980',0,'10^3 доллар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ДОМХОЗ',@link_self,'Тысяча домохозяйств','R_86n_OKEI',0,'900',0,'10^3 домхоз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЕД',@link_self,'Тысяча единиц','R_86n_OKEI',0,'643',0,'10^3 ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КАР',@link_self,'Тысяча каратов метрических','R_86n_OKEI',0,'165',0,'10^3 кар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КВ.А Р',@link_self,'Тысяча киловольт-ампер реактивных','R_86n_OKEI',0,'250',0,'10^3 кВ.А Р','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КВАРТ',@link_self,'Тысяча квартир','R_86n_OKEI',0,'910',0,'10^3 кварт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КМ',@link_self,'Тысяча километров','R_86n_OKEI',0,'965',0,'10^3 км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КОЕК',@link_self,'Тысяча коек','R_86n_OKEI',0,'912',0,'10^3 коек','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КОМПЛ',@link_self,'Тысяча комплектов','R_86n_OKEI',0,'673',0,'10^3 компл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КОР',@link_self,'Тысяча коробок','R_86n_OKEI',0,'875',0,'10^3 кор','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС КУР. НЕСУШ',@link_self,'Тысяча кур-несушек','R_86n_OKEI',0,'559',0,'10^3 кур. несуш','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Л',@link_self,'Тысяча литров; 1000 литров','R_86n_OKEI',0,'130',0,'10^3 л; 1000 л','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЛС',@link_self,'Тысяча лошадиных сил','R_86n_OKEI',0,'252',0,'10^3 л. с','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М2',@link_self,'Тысяча квадратных метров','R_86n_OKEI',0,'058',0,'10^3 м^2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М2 ЖИЛ ПЛ',@link_self,'Тысяча квадратных метров жилой площади','R_86n_OKEI',0,'085',0,'10^3 м2 жил. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М2 ОБЩ ПЛ',@link_self,'Тысяча квадратных метров общей площади','R_86n_OKEI',0,'082',0,'10^3 м2 общ. пл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М2 УЧ. ЛАБ ЗДАН',@link_self,'Тысяча квадратных метров учебно-лабораторных зданий','R_86n_OKEI',0,'088',0,'10^3 м2 уч. лаб. здан','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М3',@link_self,'Тысяча кубических метров','R_86n_OKEI',0,'114',0,'10^3 м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС М3/СУТ',@link_self,'Тысяча кубических метров в сутки','R_86n_OKEI',0,'599',0,'10^3 м3/сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС МЕСТ',@link_self,'Тысяча мест','R_86n_OKEI',0,'699',0,'10^3 мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС МЕСТ.КМ',@link_self,'Тысяча место-километров','R_86n_OKEI',0,'953',0,'10 ^3мест.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС НАБОР',@link_self,'Тысяча наборов','R_86n_OKEI',0,'479',0,'10^3 набор','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС НОМ',@link_self,'Тысяча номеров','R_86n_OKEI',0,'709',0,'10^3 ном','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПАР',@link_self,'Тысяча пар','R_86n_OKEI',0,'837',0,'10^3 пар','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПАР/СМЕН',@link_self,'Тысяча пар в смену','R_86n_OKEI',0,'548',0,'10^3 пар/смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПАСС.КМ',@link_self,'Тысяча пассажиро-километров','R_86n_OKEI',0,'423',0,'10^3 пасс.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПАСС.МИЛЬ',@link_self,'Тысяча пассажиро-миль','R_86n_OKEI',0,'958',0,'10^3 пасс.миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПАЧ',@link_self,'Тысяча пачек','R_86n_OKEI',0,'729',0,'10^3 пач','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПЛАСТ',@link_self,'Тысяча пластин','R_86n_OKEI',0,'930',0,'10^3 пласт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПЛОТН М3',@link_self,'Тысяча плотных кубических метров','R_86n_OKEI',0,'127',0,'10^3 плотн. м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОГ М',@link_self,'Тысяча погонных метров','R_86n_OKEI',0,'019',0,'10^3 пог. м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОЕЗД.КМ',@link_self,'Тысяча поездо-километров','R_86n_OKEI',0,'956',0,'10^3 поезд.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОЕЗД.Ч',@link_self,'Тысяча поездо-часов','R_86n_OKEI',0,'955',0,'10^3 поезд.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОЛ Л',@link_self,'Тысяча полулитров','R_86n_OKEI',0,'128',0,'10^3 пол. л','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОСАД МЕСТ',@link_self,'Тысяча посадочных мест','R_86n_OKEI',0,'907',0,'10^3 посад. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПОСЕЩ/ СМЕН',@link_self,'Тысяча посещений в смену','R_86n_OKEI',0,'546',0,'10^3 посещ/смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПРЯД ВЕРЕТ',@link_self,'Тысяча прядильных веретен','R_86n_OKEI',0,'562',0,'10^3 пряд.верет','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПРЯД МЕСТ',@link_self,'Тысяча прядильных мест','R_86n_OKEI',0,'563',0,'10^3 пряд.мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ПТИЦЕМЕСТ',@link_self,'Тысяча птицемест','R_86n_OKEI',0,'558',0,'10^3 птицемест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС РАБ МЕСТ',@link_self,'Тысяча рабочих мест','R_86n_OKEI',0,'905',0,'10^3 раб. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС РУБ',@link_self,'Тысяча рублей','R_86n_OKEI',0,'384',0,'10^3 руб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС РУЛ',@link_self,'Тысяча рулонов','R_86n_OKEI',0,'751',0,'10^3 рул','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС СЕМЕЙ',@link_self,'Тысяча семей','R_86n_OKEI',0,'897',0,'10^3 семей','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС СТАН',@link_self,'Тысяча станов','R_86n_OKEI',0,'761',0,'10^3 стан','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС СТАНД УСЛ КИРП',@link_self,'Тысяча стандартных условных кирпичей','R_86n_OKEI',0,'630',0,'тыс станд. усл. кирп','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т',@link_self,'Тысяча тонн','R_86n_OKEI',0,'169',0,'10^3 т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т ЕДИНОВР ХРАН',@link_self,'Тысяча тонн единовременного хранения','R_86n_OKEI',0,'177',0,'10^3 т единовр. хран','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т КОРМ ЕД',@link_self,'Тысяча тонн кормовых единиц','R_86n_OKEI',0,'981',0,'10^3 корм ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т ПАР/Ч',@link_self,'Тысяча тонн пара в час','R_86n_OKEI',0,'561',0,'10^3 т пар/ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т ПЕРЕРАБ',@link_self,'Тысяча тонн переработки','R_86n_OKEI',0,'178',0,'10^3 т перераб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т ПЕРЕРАБ/СУТ',@link_self,'Тысяча тонн переработки в сутки','R_86n_OKEI',0,'553',0,'10^3 т перераб/ сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т УСЛ ТОПЛ',@link_self,'Тысяча тонн условного топлива','R_86n_OKEI',0,'175',0,'10^3 т усл. топл','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т.КМ',@link_self,'Тысяча тонно-километров','R_86n_OKEI',0,'450',0,'10^3 т.км','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т.МИЛЬ',@link_self,'Тысяча тонно-миль','R_86n_OKEI',0,'957',0,'10^3 т.миль','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т/ГОД',@link_self,'Тысяча тонн в год','R_86n_OKEI',0,'538',0,'10^3 т/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Т/СЕЗ',@link_self,'Тысяча тонн в сезон','R_86n_OKEI',0,'537',0,'10^3 т/сез','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ТОМ КНИЖН ФОНД',@link_self,'Тысяча томов книжного фонда','R_86n_OKEI',0,'914',0,'10^3 том. книжн. фонд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ТОННАЖ. РЕЙС',@link_self,'Тысяча тоннаже-рейсов','R_86n_OKEI',0,'966',0,'10^3 тоннаж. рейс','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ТОННАЖ. СУТ',@link_self,'Тысяча тоннаже-сут','R_86n_OKEI',0,'974',0,'10^3 тоннаж. сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ТУБ',@link_self,'Тысяча тубов','R_86n_OKEI',0,'874',0,'10^3 туб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ТЮБИК',@link_self,'Тысяча тюбиков','R_86n_OKEI',0,'775',0,'10^3 тюбик','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УПАК',@link_self,'Тысяча упаковок','R_86n_OKEI',0,'782',0,'10^3 упак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ БАНК',@link_self,'Тысяча условных банок','R_86n_OKEI',0,'882',0,'10^3 усл. банк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ БАНК/СМЕН',@link_self,'Тысяча условных банок в смену','R_86n_OKEI',0,'543',0,'10^3 усл. банк/ смен','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ ЕД',@link_self,'Тысяча условных единиц','R_86n_OKEI',0,'877',0,'10^3 усл. ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ КАТ',@link_self,'Тысяча условных катушек','R_86n_OKEI',0,'890',0,'10^3 усл. кат','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ КИРП',@link_self,'Тысяча условных кирпичей','R_86n_OKEI',0,'894',0,'10^3 усл. кирп','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ КУС',@link_self,'Тысяча условных кусков','R_86n_OKEI',0,'885',0,'10^3 усл. кус','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ М',@link_self,'Тысяча условных метров','R_86n_OKEI',0,'048',0,'10^3 усл. м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ М2',@link_self,'Тысяча условных квадратных метров','R_86n_OKEI',0,'063',0,'10^3 усл. м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ М3',@link_self,'Тысяча условных кубических метров','R_86n_OKEI',0,'124',0,'10^3 усл. м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ ПЛИТ',@link_self,'Тысяча условных плиток','R_86n_OKEI',0,'892',0,'10^3 усл. плит','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ ТУБ',@link_self,'Тысяча условных тубов','R_86n_OKEI',0,'776',0,'10^3 усл.туб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ ШТ',@link_self,'Тысяча условных штук','R_86n_OKEI',0,'880',0,'10^3 усл. шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УСЛ ЯЩ',@link_self,'Тысяча условных ящиков','R_86n_OKEI',0,'888',0,'10^3 усл. ящ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС УЧЕН МЕСТ',@link_self,'Тысяча ученических мест','R_86n_OKEI',0,'903',0,'10^3 учен. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ФЛАК',@link_self,'Тысяча флаконов','R_86n_OKEI',0,'873',0,'10^3 флак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Ц',@link_self,'Тысяча центнеров','R_86n_OKEI',0,'207',0,'10^3 ц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС Ц ПЕРЕРАБ/СУТ',@link_self,'Тысяча центнеров переработки в сутки','R_86n_OKEI',0,'555',0,'10^3 ц перераб/ сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЧЕЛ',@link_self,'Тысяча человек','R_86n_OKEI',0,'793',0,'10^3 чел','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЧЕЛ.ДН',@link_self,'Тысяча человеко-дней','R_86n_OKEI',0,'541',0,'10^3 чел.дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЧЕЛ.Ч',@link_self,'Тысяча человеко-часов','R_86n_OKEI',0,'542',0,'10^3 чел.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ШТ',@link_self,'Тысяча штук','R_86n_OKEI',0,'798',0,'тыс. шт; 1000 шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ТЫС ЭКЗ',@link_self,'Тысяча экземпляров','R_86n_OKEI',0,'979',0,'10^3 экз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УЗ',@link_self,'Узел (миля/ч)','R_86n_OKEI',0,'327',0,'уз','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УПАК',@link_self,'Упаковка','R_86n_OKEI',0,'778',0,'упак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ БАНК',@link_self,'Условная банка','R_86n_OKEI',0,'881',0,'усл. банк','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ ЕД',@link_self,'Условная единица','R_86n_OKEI',0,'876',0,'усл. ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ КАТ',@link_self,'Условная катушка','R_86n_OKEI',0,'889',0,'усл. кат','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ КИРП',@link_self,'Условный кирпич','R_86n_OKEI',0,'893',0,'усл. кирп','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ КУС',@link_self,'Условный кусок','R_86n_OKEI',0,'884',0,'усл. кус','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ М',@link_self,'Условный метр','R_86n_OKEI',0,'020',0,'усл. м','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ М2',@link_self,'Условный квадратный метр','R_86n_OKEI',0,'062',0,'усл. м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ М3',@link_self,'Условный кубический метр','R_86n_OKEI',0,'123',0,'усл. м3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ ПЛИТ',@link_self,'Условная плитка','R_86n_OKEI',0,'891',0,'усл. плит','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ РЕМ',@link_self,'Условный ремонт','R_86n_OKEI',0,'915',0,'усл. рем','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ РЕМ/ГОД',@link_self,'Условный ремонт в год','R_86n_OKEI',0,'916',0,'усл. рем/год','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ Т',@link_self,'Условная тонна','R_86n_OKEI',0,'179',0,'усл. т','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ ТРУБ',@link_self,'Условная труба','R_86n_OKEI',0,'925',0,'усл. труб','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ ШТ',@link_self,'Условная штука','R_86n_OKEI',0,'879',0,'усл. шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УСЛ ЯЩ',@link_self,'Условный ящик','R_86n_OKEI',0,'887',0,'усл. ящ','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'УЧЕН МЕСТ',@link_self,'Ученическое место','R_86n_OKEI',0,'902',0,'учен. мест','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Ф',@link_self,'Фарад','R_86n_OKEI',0,'314',0,'Ф','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ФЛАК',@link_self,'Флакон','R_86n_OKEI',0,'872',0,'флак','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ФУТ',@link_self,'Фут (0,3048 м)','R_86n_OKEI',0,'041',0,'фут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ФУТ2',@link_self,'Квадратный фут (0,092903 м2)','R_86n_OKEI',0,'073',0,'фут2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ФУТ3',@link_self,'Кубический фут (0,02831685 м3)','R_86n_OKEI',0,'132',0,'фут3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Ц',@link_self,'Центнер (метрический) (100 кг); гектокилограмм; квинтал1 (метрический); децитонна','R_86n_OKEI',0,'206',0,'ц','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Ц КОРМ ЕД',@link_self,'Центнер кормовых единиц','R_86n_OKEI',0,'972',0,'ц корм ед','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Ц ПЕРЕРАБ/СУТ',@link_self,'Центнер переработки в сутки','R_86n_OKEI',0,'554',0,'ц перераб/сут','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'Ч',@link_self,'Час','R_86n_OKEI',0,'356',0,'ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧАСТЬ',@link_self,'Часть','R_86n_OKEI',0,'735',0,'часть','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧЕЛ',@link_self,'Человек','R_86n_OKEI',0,'792',0,'чел','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧЕЛ.ДН',@link_self,'Человеко-день','R_86n_OKEI',0,'540',0,'чел.дн','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧЕЛ.Ч',@link_self,'Человеко-час','R_86n_OKEI',0,'539',0,'чел.ч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧЕЛ/КМ2',@link_self,'Человек на квадратный километр','R_86n_OKEI',0,'522',0,'чел/км2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЧЕЛ/М2',@link_self,'Человек на квадратный метр','R_86n_OKEI',0,'521',0,'чел/м2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ШТ',@link_self,'Штука','R_86n_OKEI',0,'796',0,'шт','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ШТ В 20 ФУТ ЭКВИВ',@link_self,'Штук в 20-футовом эквиваленте (ДФЭ)','R_86n_OKEI',0,'976',0,'штук в 20-футовом эквиваленте','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЭЛЕМ',@link_self,'Элемент','R_86n_OKEI',0,'745',0,'элем','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЯРД',@link_self,'Ярд (0,9144 м)','R_86n_OKEI',0,'043',0,'ярд','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЯРД2',@link_self,'Квадратный ярд (0,8361274 м2)','R_86n_OKEI',0,'075',0,'ярд2','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЯРД3',@link_self,'Кубический ярд (0,764555 м3)','R_86n_OKEI',0,'133',0,'ярд3','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЯЧ',@link_self,'Ячейка','R_86n_OKEI',0,'810',0,'яч','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'ЯЩ',@link_self,'Ящик','R_86n_OKEI',0,'812',0,'ящ','',NULL,NULL
GO

GO


GO


GO


GO


GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'Программные комплексы «Государственное (муниципальное) задание», «Бюджет-КС», «Бюджет-WEB», «SMART-Бюджет» (разработчик ООО «Кейсистемс», г. Чебоксары).','R_86N_P_IIS',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'актуализировано','R_86N_P_KSE',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'2',@link_self,'документы переданы в ФНС','R_86N_P_KSE',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'3',@link_self,'не актуализировано','R_86N_P_KSE',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'действует','R_86N_P_KSY',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'2',@link_self,'деятельность приостановлена','R_86N_P_KSY',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'3',@link_self,'ликвидировано или в стадии ликвидации','R_86N_P_KSY',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'4',@link_self,'не является гос. или муницип.учреждением','R_86N_P_KSY',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'не утвержден',@link_self,'2','R_86N_P_SO',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'утвержден',@link_self,'1','R_86N_P_SO',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'требуется','R_86N_P_KSK',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'2',@link_self,'не требуется','R_86N_P_KSK',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'Ввод информации в региональную систему «Свод-WEB» (разработчик ООО «Кейсистемс», г. Чебоксары) с последующим централизованным экспортом на официальный сайт','R_86N_P_VSR',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'01',@link_self,'филиал','R_86N_TYPE_FILIAL',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'02',@link_self,'обособленное структурное подразделение','R_86N_TYPE_FILIAL',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'03',@link_self,'представительство','R_86N_TYPE_FILIAL',0,'',0,'','','19000101',NULL
GO

GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'006',@link_self,'Объекты капитального строительства','R_86N_KAT_OBJ',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'007',@link_self,'Объекты недвижимого имущества','R_86N_KAT_OBJ',0,'',0,'','','19000101',NULL
GO

GO


GO

declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08020001',@link_self,'Республиканский бюджет Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08020182',@link_self,'Республиканский бюджет Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030002',@link_self,'Бюджет городского округа "Город Волжск"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030003',@link_self,'Бюджет муниципального образования "Волжский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030004',@link_self,'Бюджет муниципального образования "Городское поселение Приволжский"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030005',@link_self,'Бюджет муниципального образования "Большепаратское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030006',@link_self,'Бюджет муниципального образования "Карамасское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030007',@link_self,'Бюджет муниципального образования "Обшиярское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030008',@link_self,'Бюджет муниципального образования "Петъяльское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030009',@link_self,'Бюджет муниципального образования "Помарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030010',@link_self,'Бюджет муниципального образования "Сотнурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030011',@link_self,'Бюджет муниципального образования "Эмековское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030012',@link_self,'Бюджет муниципального образования "Городской округ "Город Козьмодемьянск"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030013',@link_self,'Бюджет муниципального образования "Горномарийский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030014',@link_self,'Бюджет муниципального образования "Виловатовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030015',@link_self,'Бюджет муниципального образования "Еласовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030016',@link_self,'Бюджет муниципального образования "Емешевское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030017',@link_self,'Бюджет муниципального образования "Картуковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030018',@link_self,'Бюджет муниципального образования "Красноволжское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030019',@link_self,'Бюджет муниципального образования "Кузнецовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030020',@link_self,'Бюджет муниципального образования "Микряковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030021',@link_self,'Бюджет муниципального образования "Озеркинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030022',@link_self,'Бюджет муниципального образования "Пайгусовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030023',@link_self,'Бюджет муниципального образования "Сурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030024',@link_self,'Бюджет муниципального образования "Троицко-Посадское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030025',@link_self,'Бюджет муниципального образования "Усолинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030026',@link_self,'Бюджет муниципального образования "Звениговский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030027',@link_self,'Бюджет муниципального образования "Городское поселение Звенигово"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030028',@link_self,'Бюджет муниципального образования "Городское поселение Красногорский"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030029',@link_self,'Бюджет муниципального образования "Городское поселение Суслонгер"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030030',@link_self,'Бюджет муниципального образования "Исменецкое сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030031',@link_self,'Бюджет муниципального образования "Кокшамарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030032',@link_self,'Бюджет муниципального образования "Кокшайское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030033',@link_self,'Бюджет муниципального образования "Красноярское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030034',@link_self,'Бюджет муниципального образования "Кужмарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030035',@link_self,'Бюджет муниципального образования "Черноозерское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030036',@link_self,'Бюджет муниципального образования "Шелангерское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030037',@link_self,'Бюджет муниципального образования "Килемарский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030038',@link_self,'Бюджет муниципального образования "Килемарское городское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030039',@link_self,'Бюджет муниципального образования "Ардинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030040',@link_self,'Бюджет муниципального образования "Большекибеевское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030041',@link_self,'Бюджет муниципального образования "Визимьярское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030042',@link_self,'Бюджет муниципального образования "Красномостовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030043',@link_self,'Бюджет муниципального образования "Кумьинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030044',@link_self,'Бюджет муниципального образования "Нежнурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030045',@link_self,'Бюджет муниципального образования "Широкундышское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030046',@link_self,'Бюджет муниципального образования "Юксарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030047',@link_self,'Бюджет муниципального образования "Куженерский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030048',@link_self,'Бюджет муниципального образования "Городское поселение Куженер"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030049',@link_self,'Бюджет муниципального образования "Иштымбальское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030050',@link_self,'Бюджет муниципального образования "Русскошойское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030051',@link_self,'Бюджет муниципального образования "Салтакъяльское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030052',@link_self,'Бюджет муниципального образования "Токтайбелякское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030053',@link_self,'Бюджет муниципального образования "Тумьюмучашское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030054',@link_self,'Бюджет муниципального образования "Шорсолинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030055',@link_self,'Бюджет муниципального образования "Шудумарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030056',@link_self,'Бюджет муниципального образования "Юледурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030057',@link_self,'Бюджет муниципального образования "Мари-Турекский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030058',@link_self,'Бюджет муниципального образования "Городское поселение Мари-Турек"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030059',@link_self,'Бюджет муниципального образования "Карлыганское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030060',@link_self,'Бюджет муниципального образования "Косолаповское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030061',@link_self,'Бюджет муниципального образования "Мари-Биляморское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030062',@link_self,'Бюджет муниципального образования "Марийское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030063',@link_self,'Бюджет муниципального образования "Хлебниковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030064',@link_self,'Бюджет муниципального образования "Медведевский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030065',@link_self,'Бюджет муниципального образования "Азановское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030066',@link_self,'Бюджет муниципального образования "Азяковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030067',@link_self,'Бюджет муниципального образования "Ежовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030068',@link_self,'Бюджет муниципального образования "Знаменское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030069',@link_self,'Бюджет муниципального образования "Кундышское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030070',@link_self,'Бюджет муниципального образования "Куярское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030071',@link_self,'Бюджет муниципального образования "Люльпанское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030072',@link_self,'Бюджет муниципального образования "Нужъяльское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030073',@link_self,'Бюджет муниципального образования "Нурминское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030074',@link_self,'Бюджет муниципального образования "Пекшиксолинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030075',@link_self,'Бюджет муниципального образования "Пижменское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030076',@link_self,'Бюджет муниципального образования "Русско-Кукморское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030077',@link_self,'Бюджет муниципального образования "Руэмское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030078',@link_self,'Бюджет муниципального образования "Сенькинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030079',@link_self,'Бюджет муниципального образования "Сидоровское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030080',@link_self,'Бюджет муниципального образования "Туршинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030081',@link_self,'Бюджет муниципального образования "Шойбулакское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030082',@link_self,'Бюджет муниципального образования "Юбилейное сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030083',@link_self,'Бюджет муниципального образования "Краснооктябрьское городское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030084',@link_self,'Бюджет муниципального образования "Медведевское городское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030085',@link_self,'Бюджет муниципального образования "Моркинский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030087',@link_self,'Бюджет муниципального образования "Весьшургинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030088',@link_self,'Бюджет муниципального образования "Зеленогорское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030089',@link_self,'Бюджет муниципального образования "Коркатовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030090',@link_self,'Бюджет муниципального образования "Красностекловарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030091',@link_self,'Бюджет муниципального образования "Кумужъяльское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030092',@link_self,'Бюджет муниципального образования "Кучко-Памашское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030093',@link_self,'Бюджет муниципального образования "Мари-Кужерское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030094',@link_self,'Бюджет муниципального образования "Нуж-Ключинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030095',@link_self,'Бюджет муниципального образования "Нуръяльское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030096',@link_self,'Бюджет муниципального образования "Октябрьское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030097',@link_self,'Бюджет муниципального образования "Себеусадское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030098',@link_self,'Бюджет муниципального образования "Семисолинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030099',@link_self,'Бюджет муниципального образования "Шалинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030100',@link_self,'Бюджет муниципального образования "Шерегановское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030101',@link_self,'Бюджет муниципального образования "Шиньшинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030102',@link_self,'Бюджет муниципального образования "Шордурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030103',@link_self,'Бюджет муниципального образования "Шоруньжинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030104',@link_self,'Бюджет муниципального образования "Городское поселение Морки"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030105',@link_self,'Бюджет муниципального образования "Новоторъяльский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030106',@link_self,'Бюджет муниципального образования "Городское поселение Новый Торъял"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030107',@link_self,'Бюджет муниципального образования "Большелумарское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030108',@link_self,'Бюджет муниципального образования "Елембаевское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030109',@link_self,'Бюджет муниципального образования "Куанпамашское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030110',@link_self,'Бюджет муниципального образования "Масканурское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030111',@link_self,'Бюджет муниципального образования "Немдинское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030112',@link_self,'Бюджет муниципального образования "Пектубаевское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030113',@link_self,'Бюджет муниципального образования "Старокрещенское сельское поселение" (МО Новый Торъял)','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030114',@link_self,'Бюджет муниципального образования "Староторъяльское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030115',@link_self,'Бюджет муниципального образования "Токтарсолинское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030116',@link_self,'Бюджет муниципального образования "Чуксолинское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030117',@link_self,'Бюджет муниципального образования "Шуринское сельское поселение "','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030118',@link_self,'Бюджет муниципального образования "Оршанский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030119',@link_self,'Бюджет муниципального образования "Городское поселение Оршанка"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030120',@link_self,'Бюджет муниципального образования "Большеоршинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030121',@link_self,'Бюджет муниципального образования "Великопольское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030122',@link_self,'Бюджет муниципального образования "Каракшинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030123',@link_self,'Бюджет муниципального образования "Лужбелякское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030124',@link_self,'Бюджет муниципального образования "Марковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030125',@link_self,'Бюджет муниципального образования "Старокрещенское сельское поселение" (МО Оршанка)','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030126',@link_self,'Бюджет муниципального образования "Табашинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030127',@link_self,'Бюджет муниципального образования "Упшинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030128',@link_self,'Бюджет муниципального образования "Чирковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030129',@link_self,'Бюджет муниципального образования "Шулкинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030130',@link_self,'Бюджет муниципального образования "Параньгинский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030131',@link_self,'Бюджет Городского поселения Параньга','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030132',@link_self,'Бюджет Алашайского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030133',@link_self,'Бюджет Елеевского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030134',@link_self,'Бюджет Илетского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030135',@link_self,'Бюджет Ильпанурского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030136',@link_self,'Бюджет Куракинского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030137',@link_self,'Бюджет Портянурского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030138',@link_self,'Бюджет Русско-Ляжмаринского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030139',@link_self,'Бюджет Усолинского сельского поселения','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030140',@link_self,'Бюджет муниципального образования "Сернурский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030141',@link_self,'Бюджет муниципального образования "Городское поселение Сернур"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030142',@link_self,'Бюджет муниципального образования "Верхнекугенерское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030143',@link_self,'Бюджет муниципального образования "Зашижемское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030144',@link_self,'Бюджет муниципального образования "Казанское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030145',@link_self,'Бюджет муниципального образования "Кукнурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030146',@link_self,'Бюджет муниципального образования "Марисолинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030147',@link_self,'Бюджет муниципального образования "Сердежское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030148',@link_self,'Бюджет муниципального образования "Чендемеровское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030149',@link_self,'Бюджет муниципального образования "Советский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030150',@link_self,'Бюджет муниципального образования "Алексеевское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030151',@link_self,'Бюджет муниципального образования "Верх-Ушнурское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030152',@link_self,'Бюджет муниципального образования "Вятское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030155',@link_self,'Бюджет муниципального образования "Кужмаринское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030157',@link_self,'Бюджет муниципального образования "Михайловское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030159',@link_self,'Бюджет муниципального образования "Ронгинское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030160',@link_self,'Бюджет муниципального образования "Солнечное сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030162',@link_self,'Бюджет муниципального образования "Городское поселение Советский"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030163',@link_self,'Бюджет муниципального образования "Юринский муниципальный район"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030164',@link_self,'Бюджет муниципального образования "Быковское сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030165',@link_self,'Бюджет муниципального образования "Васильевское сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030166',@link_self,'Бюджет муниципального образования "Горношумецкое сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030167',@link_self,'Бюджет муниципального образования "Городское поселение Юрино" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030168',@link_self,'Бюджет муниципального образования "Козиковское сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030169',@link_self,'Бюджет муниципального образования "Марьинское сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030170',@link_self,'Бюджет муниципального образования "Юркинское сельское поселение" Юринского муниципального района Республики Марий Эл','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030171',@link_self,'Бюджет городского округа "Город Йошкар-Ола"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030172',@link_self,'Бюджет муниципального образования "Кузнецовское сельское поселение" (МО Медведевский район)','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030177',@link_self,'Бюджет муниципального образования "Березовское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08030178',@link_self,'Бюджет муниципального образования "Дубниковское сельское поселение"','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'08050176',@link_self,'Бюджет Республиканского фонда обязательного медицинского страхования','R_86N_BUDGET',0,'',0,'','',NULL,NULL
GO

GO


GO


GO


GO


GO


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_173_VB_1',0,'План счетов для 0503173_ВБ таблица 1','HEADER'
GO

declare @link_self int
select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_173_VB_1',@link_self,'План счетов для 0503173_ВБ таблица 1','HEADER'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_173_VB_1',0,'',0,'','','19000101','19000101'
GO

GO


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_173_VB_2',0,'План счетов для 0503173_ВБ таблица 2','HEADER'
GO

declare @link_self int
select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_173_VB_2',@link_self,'План счетов для 0503173_ВБ таблица 2','HEADER'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'220113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','','19000101','19000101'
GO
declare @link_self int
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'720113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_173_VB_2',0,'',0,'','','19000101','19000101'
GO

GO


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_CHET_710',0,'План счетов для 0503710 формы','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_CHET_710',@link_self,'План счетов для 0503710 формы','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230404000',@link_self,'Внутриведомственные расчеты','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','R_SPR_CHET_710',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230406000',@link_self,' Расчеты, связанные с изменением типа бюджетных учреждений','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110110',@link_self,'Налоговые доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110120',@link_self,'Доходы от собственности','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110171',@link_self,'Доходы от переоценки активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110172',@link_self,'Доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110180',@link_self,'Прочие доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120211',@link_self,'Расходы по заработной плате','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120212',@link_self,'Расходы по прочим выплатам','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120221',@link_self,'Расходы на услуги связи','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120222',@link_self,'Расходы на транспортные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120223',@link_self,'Расходы на коммунальные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120272',@link_self,'Расходование материальных запасов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120290',@link_self,'Прочие расходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430404000',@link_self,'Внутриведомственные расчеты','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','R_SPR_CHET_710',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'430406000',@link_self,'Расчеты, связанные с изменением типа бюджетных учреждений','R_SPR_CHET_710',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110110',@link_self,'Налоговые доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110120',@link_self,'Доходы от собственности','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110171',@link_self,'Доходы от переоценки активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110172',@link_self,'Доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440110180',@link_self,'Прочие доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120211',@link_self,'Расходы по заработной плате','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120212',@link_self,'Расходы по прочим выплатам','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120221',@link_self,'Расходы на услуги связи','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120222',@link_self,'Расходы на транспортные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120223',@link_self,'Расходы на коммунальные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120272',@link_self,'Расходование материальных запасов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'440120290',@link_self,'Прочие расходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'530404000',@link_self,'Внутриведомственные расчеты','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110110',@link_self,'Налоговые доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110120',@link_self,'Доходы от собственности','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110171',@link_self,'Доходы от переоценки активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110172',@link_self,'Доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540110180',@link_self,'Прочие доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120211',@link_self,'Расходы по заработной плате','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120212',@link_self,'Расходы по прочим выплатам','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120221',@link_self,'Расходы на услуги связи','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120222',@link_self,'Расходы на транспортные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120223',@link_self,'Расходы на коммунальные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120272',@link_self,'Расходование материальных запасов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'540120290',@link_self,'Прочие расходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'630404000',@link_self,'Внутриведомственные расчеты','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110110',@link_self,'Налоговые доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110120',@link_self,'Доходы от собственности','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110171',@link_self,'Доходы от переоценки активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110172',@link_self,'Доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640110180',@link_self,'Прочие доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120211',@link_self,'Расходы по заработной плате','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120212',@link_self,'Расходы по прочим выплатам','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120221',@link_self,'Расходы на услуги связи','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120222',@link_self,'Расходы на транспортные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120223',@link_self,'Расходы на коммунальные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120272',@link_self,'Расходование материальных запасов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'640120290',@link_self,'Прочие расходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730404000',@link_self,'Внутриведомственные расчеты','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730405000',@link_self,'Расчеты по платежам из бюджета с финансовым органом','R_SPR_CHET_710',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'730406000',@link_self,' Расчеты, связанные с изменением типа бюджетных учреждений','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110110',@link_self,'Налоговые доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110120',@link_self,'Доходы от собственности','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110171',@link_self,'Доходы от переоценки активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110172',@link_self,'Доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110180',@link_self,'Прочие доходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120211',@link_self,'Расходы по заработной плате','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120212',@link_self,'Расходы по прочим выплатам','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120221',@link_self,'Расходы на услуги связи','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120222',@link_self,'Расходы на транспортные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120223',@link_self,'Расходы на коммунальные услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120272',@link_self,'Расходование материальных запасов','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120290',@link_self,'Прочие расходы','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'888888888',@link_self,'Итого','R_SPR_CHET_710',0,'',0,'','','19000101',NULL
GO

GO


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_769_DK',0,'План счетов для 0503769_Кредит','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_ACC_769_DK',@link_self,'План счетов для 0503769_Кредит','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30200000',@link_self,'Расчеты по принятым обязательствам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30211000',@link_self,'Расчеты по заработной плате','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30212000',@link_self,'Расчеты по прочим выплатам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30213000',@link_self,'Расчеты по начислениям на выплаты по оплате труда','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30221000',@link_self,'Расчеты по услугам связи','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30222000',@link_self,'Расчеты по транспортным услугам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30223000',@link_self,'Расчеты по коммунальным услугам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30224000',@link_self,'Расчеты по арендной плате за пользование имуществом','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30225000',@link_self,'Расчеты по работам, услугам по содержанию имущества','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30226000',@link_self,'Расчеты по прочим работам, услугам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30231000',@link_self,'Расчеты по приобретению основных средств','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30232000',@link_self,'Расчеты по приобретению нематериальных активов','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30233000',@link_self,'Расчеты по приобретению непроизведенных активов','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30234000',@link_self,'Расчеты по приобретению материальных запасов','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30241000',@link_self,'Расчеты по безвозмездным перечислениям государственным и муниципальным организациям','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30242000',@link_self,'Расчеты по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30251000',@link_self,'Расчеты по перечислениям другим бюджетам бюджетной системы Российской Федерации','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30252000',@link_self,'Расчеты по перечислениям наднациональным организациям и правительствам иностранных государств','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30253000',@link_self,'Расчеты по перечислениям международным организациям','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30261000',@link_self,'Расчеты по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30262000',@link_self,'Расчеты по пособиям по социальной помощи населению','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30263000',@link_self,'Расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30272000',@link_self,'Расчеты по приобретению ценных бумаг, кроме акций','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30273000',@link_self,'Расчеты по приобретению акций и по иным формам  участия в капитале','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30275000',@link_self,'Расчеты по приобретению иных финансовых активов','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30291000',@link_self,'Расчеты по прочим расходам','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30300000',@link_self,'Расчеты по платежам в бюджеты','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30301000',@link_self,'Расчеты по налогу на доходы физических лиц','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30302000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование на случай временной нетрудоспособности и в связи с материнством','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30303000',@link_self,'Расчеты по налогу на прибыль организаций','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30304000',@link_self,'Расчеты по налогу на добавленную стоимость','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30305000',@link_self,'Расчеты по прочим платежам в бюджет','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30306000',@link_self,'Расчеты по страховым взносам на обязательное социальное страхование от несчастных случаев на производстве и профессиональных заболеваний','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30307000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в Федеральный ФОМС','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30308000',@link_self,'Расчеты по страховым взносам на обязательное медицинское страхование в территориальный ФОМС','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30309000',@link_self,'Расчеты по дополнительным страховым взносам на пенсионное страхование','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30310000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату страховой части трудовой пенсии','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30311000',@link_self,'Расчеты по страховым взносам на обязательное пенсионное страхование на выплату накопительной части трудовой пенсии','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30312000',@link_self,'Расчеты по налогу на имущество организаций','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30313000',@link_self,'Расчеты по земельному налогу','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30400000',@link_self,'Прочие расчеты с кредиторами','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30402000',@link_self,'Расчеты с депонентами','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30403000',@link_self,'Расчеты по удержаниям из выплат  по оплате труда','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30404000',@link_self,'Внутриведомственные расчеты','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'30406000',@link_self,'Расчеты с прочими кредиторами','R_SPR_ACC_769_DK',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'88888888',@link_self,'','R_SPR_ACC_769_DK',0,'',0,'','','19000101','19000101'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: ADM_FED_2010_and_itog С КОДОМ ADM_FED_2010_and_itog------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''АДМ_2010'' and code like ''___''')

declare @link int
select @link = link from report_spr where code = 'ADM_FED_2010_and_itog'
exec dbo.RO_SPR_SAVE @link, 'ADM_FED_2010_and_itog', 'ADM_FED_2010_and_itog', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ADM_FED_2010_and_itog]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[ADM_FED_2010_and_itog]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 13.01.2012

	справочник [dbo].ADM_FED_2010_and_itog (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[ADM_FED_2010_and_itog]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM REPORT_KBK WHERE Code_Form = 'АДМ_2010' and code like '___' GROUP BY Code

	UNION

	select -1 as Link, 0 as Link_Self,'888' as CODE,'ВСЕГО:' as NAME

GO


GRANT SELECT ON dbo.[ADM_FED_2010_and_itog] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ADM_FED_2010_and_itog')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ADM_FED_2010_and_itog'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2010_and_itog', 'ADM_FED_2010_and_itog', 282, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2010_and_itog', NAME = 'ADM_FED_2010_and_itog', ORDERS = '282', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2010_and_itog'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2010_and_itog_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2010_and_itog_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2010_and_itog_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2010_and_itog_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2010_and_itog_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2010_and_itog_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2010_and_itog_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2010_and_itog_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2010_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2010_and_itog_Name'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog', 'TITLE', 'ADM_FED_2010_and_itog'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog', 'INIT_OBJECT_METHOD', 'x_spisok(''ADM_FED_2010_and_itog'')'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''ADM_FED_2010_and_itog'')'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog', 'SERVER_TABLE_NAME', 'ADM_FED_2010_and_itog'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''ADM_FED_2010_and_itog'''
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'ADM_FED_2010_and_itog_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'ADM_FED_2010_and_itog', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'ADM_FED_2010_and_itog', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'ADM_FED_2010_and_itog', 'Свод-КС - получатель', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: ADM_FED_2011_and_itog С КОДОМ ADM_FED_2011_and_itog------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''АДМ_2011'' and code like ''___''')

declare @link int
select @link = link from report_spr where code = 'ADM_FED_2011_and_itog'
exec dbo.RO_SPR_SAVE @link, 'ADM_FED_2011_and_itog', 'ADM_FED_2011_and_itog', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ADM_FED_2011_and_itog]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[ADM_FED_2011_and_itog]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 13.01.2012

	справочник [dbo].ADM_FED_2011_and_itog (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[ADM_FED_2011_and_itog]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM REPORT_KBK WHERE Code_Form = 'АДМ_2011' and code like '___' GROUP BY Code

	UNION

	select -1 as Link, 0 as Link_Self,'888' as CODE,'ВСЕГО:' as NAME

GO


GRANT SELECT ON dbo.[ADM_FED_2011_and_itog] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'ADM_FED_2011_and_itog')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ADM_FED_2011_and_itog'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2011_and_itog', 'ADM_FED_2011_and_itog', 281, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2011_and_itog', NAME = 'ADM_FED_2011_and_itog', ORDERS = '281', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2011_and_itog'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2011_and_itog_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2011_and_itog_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2011_and_itog_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2011_and_itog_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2011_and_itog_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2011_and_itog_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADM_FED_2011_and_itog_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADM_FED_2011_and_itog_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ADM_FED_2011_and_itog'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADM_FED_2011_and_itog_Name'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog', 'TITLE', 'ADM_FED_2011_and_itog'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog', 'INIT_OBJECT_METHOD', 'x_spisok(''ADM_FED_2011_and_itog'')'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''ADM_FED_2011_and_itog'')'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog', 'SERVER_TABLE_NAME', 'ADM_FED_2011_and_itog'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''ADM_FED_2011_and_itog'''
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'ADM_FED_2011_and_itog_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'ADM_FED_2011_and_itog', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'ADM_FED_2011_and_itog', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'ADM_FED_2011_and_itog', 'Свод-КС - получатель', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
/****** Объект: Справочник ежедекадных дат на 2010 год******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DATA_DECADA')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DATA_DECADA')
	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 = 'DATA_DECADA')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DATA_DECADA')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DATA_DECADA'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DATA_DECADA')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DATA_DECADA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DATA_DECADA', 'Справочник ежедекадных дат на 2010 год', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DATA_DECADA', NAME = 'Справочник ежедекадных дат на 2010 год', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DATA_DECADA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DATA_DECADA_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DATA_DECADA_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DATA_DECADA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DATA_DECADA_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DATA_DECADA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DATA_DECADA_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DATA_DECADA_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DATA_DECADA_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DATA_DECADA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DATA_DECADA_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DATA_DECADA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DATA_DECADA_CODE'
GO
EXEC X_SET_PROP 'DATA_DECADA', 'TITLE', 'Справочник ежедекадных дат на 2010 год'
GO
EXEC X_SET_PROP 'DATA_DECADA', 'INIT_OBJECT_METHOD', 'x_spisok(''DATA_DECADA'')'
GO
EXEC X_SET_PROP 'DATA_DECADA', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DATA_DECADA'')'
GO
EXEC X_SET_PROP 'DATA_DECADA', 'SERVER_TABLE_NAME', 'DATA_DECADA'
GO
EXEC X_SET_PROP 'DATA_DECADA', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''DATA_DECADA'''
GO
EXEC X_SET_PROP 'DATA_DECADA_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DATA_DECADA_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'DATA_DECADA_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'DATA_DECADA_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'DATA_DECADA_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DATA_DECADA_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'DATA_DECADA_CODE', 'FIELD_DATA', 'CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DATA_DECADA', 'Свод-КС - получатель', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DATA_DECADA', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DATA_DECADA', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[DATA_DECADA]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[DATA_DECADA]

GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 21.06.2010

	справочник Справочник ежедекадных дат на 2010 год (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[DATA_DECADA]

AS

SELECT distinct LINK, Code as [CODE] FROM [REPORT_KBK] WHERE CODE_FORM = 'DATA_DECADA'


GO


GRANT SELECT ON dbo.[DATA_DECADA] TO PUBLIC

GO


--Расширенные свойства--
--Свойство:NOSCRIPT значение: 1


GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_AUTO_110_01_2011',0,'Cправочник счетов для формы 0503110. Таблица 1.','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='0503110' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_AUTO_110_01_2011',@link_self,'Cправочник счетов для формы 0503110. Таблица 1.','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'000000850',@link_self,'','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121100000',@link_self,'Внутренние расчеты по поступлениям в бюджет','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130800000',@link_self,'Внутренние расчеты по поступлениям','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210110',@link_self,'Поступления в бюджет по налоговым доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210120',@link_self,'Поступления в бюджет по доходам от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210153',@link_self,'Поступления в бюджет от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210180',@link_self,'Поступления в бюджет по прочим доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210410',@link_self,'Поступления в бюджет от реализации основных средств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210440',@link_self,'Поступления в бюджет от реализации материальных запасов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221100000',@link_self,'Внутренние расчеты по поступлениям в бюджет','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230800000',@link_self,'Внутренние расчеты по поступлениям','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210110',@link_self,'Поступления в бюджет по налоговым доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210120',@link_self,'Поступления в бюджет по доходам от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210153',@link_self,'Поступления в бюджет от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210180',@link_self,'Поступления в бюджет по прочим доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210410',@link_self,'Поступления в бюджет от реализации основных средств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210440',@link_self,'Поступления в бюджет от реализации материальных запасов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник администраторов С КОДОМ RO_ADM_324_2010------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''АДМ_2010''')

declare @link int
select @link = link from report_spr where code = 'RO_ADM_324_2010'
exec dbo.RO_SPR_SAVE @link, 'RO_ADM_324_2010', 'Справочник администраторов', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RO_ADM_324_2010]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[RO_ADM_324_2010]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 30.06.2010

	справочник Справочник администраторов (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[RO_ADM_324_2010]

AS

SELECT max(LINK) as Link, Code as [CODE],max(Name) as [Name] FROM [REPORT_KBK] WHERE Code_Form = 'АДМ_2010' GROUP BY Code

	UNION

	select -1 as Link,'qwerty' as CODE,'asdf' as Name

	UNION

	select -2 as Link,'111' as CODE,'222' as Name

GO


GRANT SELECT ON dbo.[RO_ADM_324_2010] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RO_ADM_324_2010')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RO_ADM_324_2010'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_ADM_324_2010', 'Справочник администраторов', 46, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_ADM_324_2010', NAME = 'Справочник администраторов', ORDERS = '46', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_ADM_324_2010'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_ADM_324_2010_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_ADM_324_2010_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_ADM_324_2010_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_ADM_324_2010_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_ADM_324_2010_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_ADM_324_2010_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_ADM_324_2010_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_ADM_324_2010_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_ADM_324_2010'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_ADM_324_2010_Name'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010', 'SERVER_TABLE_NAME', 'RO_ADM_324_2010'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''RO_ADM_324_2010'''
GO
EXEC X_SET_PROP 'RO_ADM_324_2010', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''RO_ADM_324_2010'')'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010', 'INIT_OBJECT_METHOD', 'x_spisok(''RO_ADM_324_2010'')'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010', 'TITLE', 'Справочник администраторов'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'RO_ADM_324_2010_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'RO_ADM_324_2010', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'RO_ADM_324_2010', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'RO_ADM_324_2010', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Список организаций которые размещаются на сайте С КОДОМ R_86n_SEND_ORG------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'КОД', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('inn', 3, 'Code_str', 'ИНН', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LINK_SITE', 5, 'LEFT(add_info,3)', 'Привязка', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('OGS', 4, 'long_name', 'ОГС', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('end', 6, 'SUBSTRING(add_info,5,3)', 'Закрытая организация', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_86n_SEND_ORG'
exec dbo.RO_SPR_SAVE @link, 'R_86n_SEND_ORG', 'Список организаций которые размещаются на сайте', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_86n_SEND_ORG]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_86n_SEND_ORG]


GO



/*******************************************************************************



	© Кейсистемс (Keysystems), 27.02.2012



	справочник Список организаций которые размещаются на сайте (сгенерировано Редактором справочников)



*******************************************************************************/



CREATE     VIEW dbo.[R_86n_SEND_ORG]



AS



SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [INN],LEFT(add_info,3) as [LINK_SITE],SUBSTRING(add_info,5,3) as [END],max(Name) as [NAME],max(long_name) as [OGS], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_86n_SEND_ORG' GROUP BY Code,Code_str,LEFT(add_info,3),SUBSTRING(add_info,5,3), begin_date, end_date




GO


GRANT SELECT ON dbo.[R_86n_SEND_ORG] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_86n_SEND_ORG')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_86n_SEND_ORG'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG', 'Список организаций которые размещаются на сайте', 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_86n_SEND_ORG', 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_86n_SEND_ORG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_CODE', 'КОД', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_CODE', NAME = 'КОД', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_inn')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_inn', 'ИНН', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_inn', NAME = 'ИНН', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_inn'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_OGS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_OGS', 'ОГС', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_OGS', NAME = 'ОГС', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_OGS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_LINK_SITE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_LINK_SITE', 'Привязка', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_LINK_SITE', NAME = 'Привязка', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_LINK_SITE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG_end')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_86n_SEND_ORG_end', 'Закрытая организация', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_86n_SEND_ORG_end', NAME = 'Закрытая организация', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_86n_SEND_ORG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_86n_SEND_ORG_end'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG', 'SERVER_TABLE_NAME', 'R_86n_SEND_ORG'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_86n_SEND_ORG'''
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_86n_SEND_ORG'')'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG', 'INIT_OBJECT_METHOD', 'x_spisok(''R_86n_SEND_ORG'')'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG', 'TITLE', 'Список организаций которые размещаются на сайте'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_CODE', 'TITLE', 'КОД'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_inn', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_inn', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_inn', 'CONTROLSOURCE', 'm.cAlias + ".inn"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_inn', 'FIELD_DATA', 'inn'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_OGS', 'TITLE', 'ОГС'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_OGS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_OGS', 'CONTROLSOURCE', 'm.cAlias + ".OGS"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_OGS', 'FIELD_DATA', 'OGS'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_LINK_SITE', 'TITLE', 'Привязка'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_LINK_SITE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_LINK_SITE', 'CONTROLSOURCE', 'm.cAlias + ".LINK_SITE"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_LINK_SITE', 'FIELD_DATA', 'LINK_SITE'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_end', 'TITLE', 'Закрытая организация'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_end', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_end', 'CONTROLSOURCE', 'm.cAlias + ".end"'
GO
EXEC X_SET_PROP 'R_86n_SEND_ORG_end', 'FIELD_DATA', 'end'
GO
EXEC DBO.W_SPERM_WRITE 'R_86n_SEND_ORG', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_86n_SEND_ORG', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_86n_SEND_ORG', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_86n_SEND_ORG',0,'Список организаций которые размещаются на сайте','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_86n_SEND_ORG',@link_self,'Список организаций которые размещаются на сайте','HEADER'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА:  Справочник для фломы 0503171, ограничение 0204000 С КОДОМ R_SPR_0503171_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', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ПлСчет_Каз_2011'' AND SUBSTRING(code, 2, 3) IN (''204'',''215'') and LEFT(CODE,1) <>''0'' and RIGHT(CODE,3)=''000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503171_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503171_2011', ' Справочник для фломы 0503171, ограничение 0204000', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_0503171_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_0503171_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 08.02.2012

	справочник  Справочник для фломы 0503171, ограничение 0204000 (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_0503171_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ПлСчет_Каз_2011' AND SUBSTRING(code, 2, 3) IN ('204','215') and LEFT(CODE,1) <>'0' and RIGHT(CODE,3)='000' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503171_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503171_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503171_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503171_2011', ' Справочник для фломы 0503171, ограничение 0204000', 233, (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_0503171_2011', NAME = ' Справочник для фломы 0503171, ограничение 0204000', ORDERS = '233', 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_0503171_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503171_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503171_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503171_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503171_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503171_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503171_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503171_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503171_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503171_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503171_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011', 'TITLE', ' Справочник для фломы 0503171, ограничение 0204000'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503171_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503171_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011', 'SERVER_TABLE_NAME', 'R_SPR_0503171_2011'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503171_2011'''
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503171_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503171_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503171_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503171_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник кодов расходов 0503324М С КОДОМ R_SPR_0503324_2------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503324_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503324_2', 'Справочник кодов расходов 0503324М', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_0503324_2]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_0503324_2]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 03.02.2011

	справочник Справочник кодов расходов 0503324М (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_0503324_2]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503324_2' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_0503324_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503324_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503324_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503324_2', 'Справочник кодов расходов 0503324М', 16, (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_0503324_2', NAME = 'Справочник кодов расходов 0503324М', ORDERS = '16', 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_0503324_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503324_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503324_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503324_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503324_2_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503324_2_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503324_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503324_2_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503324_2_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503324_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503324_2_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2', 'TITLE', 'Справочник кодов расходов 0503324М'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503324_2'')'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503324_2'')'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2', 'SERVER_TABLE_NAME', 'R_SPR_0503324_2'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503324_2'''
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503324_2_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503324_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503324_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503324_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503324_2',0,'Справочник кодов расходов 0503324М','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_0503324_2',@link_self,'Справочник кодов расходов 0503324М','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'00011050010200000000',@link_self,'Неизвестное ведомство','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'00088888888888888888',@link_self,'Неизвестное ведомство','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'05802070010400000212',@link_self,'Прочие выплаты','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'05888888888888888888',@link_self,'Федеральное агентство по культуре и кинематографии','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'05902070010400000212',@link_self,'Прочие выплаты','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'05988888888888888888',@link_self,'Федеральная служба по надзору за соблюдением законодательства в сфере массовых коммуникаций и охране культурного наследия','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'10904010010400000211',@link_self,'Заработная плата','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'10988888888888888888',@link_self,'Федеральное агентство железнодорожного транспорта','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'49411050010400000212',@link_self,'Прочие выплаты','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'49811050010200000000',@link_self,'Федеральная служба по экологическому, технологическому и атомному надзору','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'49888888888888888888',@link_self,'Федеральная служба по экологическому, технологическому и атомному надзору','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'57311050010200000000',@link_self,'Российская академия образования','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'57388888888888888888',@link_self,'Российская академия образования','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'58702060010200000212',@link_self,'Прочие выплаты','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'58702070010600000212',@link_self,'Прочие выплаты','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'58788888888888888888',@link_self,'Федеральная служба по техническому и экспортному контролю','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'58988888888888888888',@link_self,'Российский гуманитарный научный фонд','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'72108060010500000213',@link_self,'Начисления на выплаты по оплате труда','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'88888888888888888888',@link_self,'Расходы целевых средств, всего','R_SPR_0503324_2',0,'',0,'','',NULL,NULL
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Cправочник счетов для формы 0503110. Таблица 2. С КОДОМ R_SPR_110_02_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', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_110_02_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_110_02_2011', 'Cправочник счетов для формы 0503110. Таблица 2.', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_110_02_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_110_02_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 06.09.2011

	справочник Cправочник счетов для формы 0503110. Таблица 2. (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_110_02_2011]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_110_02_2011' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_110_02_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_02_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_02_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011', 'Cправочник счетов для формы 0503110. Таблица 2.', 86, (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_110_02_2011', NAME = 'Cправочник счетов для формы 0503110. Таблица 2.', ORDERS = '86', 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_110_02_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'TITLE', 'Cправочник счетов для формы 0503110. Таблица 2.'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_110_02_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_110_02_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SERVER_TABLE_NAME', 'R_SPR_110_02_2011'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_110_02_2011'''
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_02_2011',0,'Cправочник счетов для формы 0503110. Таблица 2.','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='0503110' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_02_2011',@link_self,'Cправочник счетов для формы 0503110. Таблица 2.','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'000000960',@link_self,'','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121200000',@link_self,'Внутренние расчеты по выбытиям из бюджета','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130900000',@link_self,'Внутренние расчеты по выбытиям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120211',@link_self,'Расходы по заработной плате','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120212',@link_self,'Расходы по прочим выплатам','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120221',@link_self,'Расходы на услуги связи','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120222',@link_self,'Расходы на транспортные услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120223',@link_self,'Расходы на коммунальные услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120272',@link_self,'Расходование материальных запасов','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140120290',@link_self,'Прочие расходы','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220211',@link_self,'Выбытия средств бюджета по заработной плате','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220212',@link_self,'Выбытия средств бюджета по прочим выплатам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220221',@link_self,'Выбытия средств бюджета по услугам связи','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220222',@link_self,'Выбытия средств бюджета по транспортным услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220290',@link_self,'Выбытия средств бюджета по прочим расходам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221200000',@link_self,'Внутренние расчеты по выбытиям из бюджета','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120211',@link_self,'Расходы по заработной плате','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120212',@link_self,'Расходы по прочим выплатам','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120221',@link_self,'Расходы на услуги связи','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120222',@link_self,'Расходы на транспортные услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120223',@link_self,'Расходы на коммунальные услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120272',@link_self,'Расходование материальных запасов','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240120290',@link_self,'Прочие расходы','R_SPR_110_02_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220211',@link_self,'Выбытия средств бюджета по заработной плате','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220212',@link_self,'Выбытия средств бюджета по прочим выплатам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220213',@link_self,'Выбытия средств бюджета по начислениям на выплаты по оплате труда','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220221',@link_self,'Выбытия средств бюджета по услугам связи','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220222',@link_self,'Выбытия средств бюджета по транспортным услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220223',@link_self,'Выбытия средств бюджета по коммунальным услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220224',@link_self,'Выбытия средств бюджета по арендной плате за пользование имуществом','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220225',@link_self,'Выбытия средств бюджета по работам, услугам по содержанию имущества','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220226',@link_self,'Выбытия средств бюджета по прочим работам, услугам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220231',@link_self,'Выбытия средств бюджета по обслуживанию внутреннего долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220232',@link_self,'Выбытия средств бюджета по обслуживанию внешнего государственного долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220241',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям государственным и муниципальным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220242',@link_self,'Выбытия средств бюджета по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220251',@link_self,'Выбытия средств бюджета по перечислениям другим бюджетам бюджетной системы Российской Федерации','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220252',@link_self,'Выбытия средств бюджета по перечислениям наднациональным организациям и правительствам иностранных государств','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220253',@link_self,'Выбытия средств бюджета по перечислениям международным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220261',@link_self,'Выбытия средств бюджета по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220262',@link_self,'Выбытия средств бюджета по пособиям по социальной помощи населению','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220263',@link_self,'Выбытия средств бюджета по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220273',@link_self,'Выбытия средств бюджета по чрезвычайным расходам по операциям с активами','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220290',@link_self,'Выбытия средств бюджета по прочим расходам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220310',@link_self,'Выбытия средств бюджета по приобретению основных средств','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220320',@link_self,'Выбытия средств бюджета по приобретению нематериальных активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220330',@link_self,'Выбытия средств бюджета по приобретению непроизведенных активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220340',@link_self,'Выбытия средств бюджета по приобретению материальных запасов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220520',@link_self,'Выбытия средств бюджета по приобретению ценных бумаг, кроме акций','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220530',@link_self,'Выбытия средств бюджета по приобретению акций и иных форм участия в капитале','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220540',@link_self,'Выбытия средств бюджета по предоставлению бюджетных кредитов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220550',@link_self,'Выбытия средств бюджета по поступлению иных финансовых активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220810',@link_self,'Выбытия средств бюджета по погашению задолженности по внутреннему долгу','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240220820',@link_self,'Выбытия средств бюджета по погашению задолженности по внешнему государственному долгу','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120211',@link_self,'Расходы по заработной плате','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120212',@link_self,'Расходы по прочим выплатам','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120213',@link_self,'Расходы на начисления на выплаты по оплате труда','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120221',@link_self,'Расходы на услуги связи','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120222',@link_self,'Расходы на транспортные услуги','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120223',@link_self,'Расходы на коммунальные услуги','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120224',@link_self,'Расходы на арендную плату за пользование имуществом','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120225',@link_self,'Расходы на работы, услуги по содержанию имущества','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120226',@link_self,'Расходы на прочие работы, услуги','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120231',@link_self,'Расходы на обслуживание внутреннего долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120232',@link_self,'Расходы на обслуживание внешнего государственного долга','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120241',@link_self,'Расходы на безвозмездные перечисления государственным и муниципальным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120242',@link_self,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120251',@link_self,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120252',@link_self,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120253',@link_self,'Расходы на перечисления международным организациям','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120261',@link_self,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120262',@link_self,'Расходы на пособия по социальной помощи населению','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120263',@link_self,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120271',@link_self,'Расходы на амортизацию основных средств и нематериальных активов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120272',@link_self,'Расходование материальных запасов','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120273',@link_self,'Чрезвычайные расходы по операциям с активами','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740120290',@link_self,'Прочие расходы','R_SPR_110_02_2011',0,'',0,'','','19000101','19000101'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник счетов для формы 0503110. Таблица 4 (счета с 3) С КОДОМ R_SPR_110_04_03_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', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_110_04_03_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_110_04_03_2011', 'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_110_04_03_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_110_04_03_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 18.02.2012

	справочник Справочник счетов для формы 0503110. Таблица 4 (счета с 3) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_110_04_03_2011]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_110_04_03_2011' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_110_04_03_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_04_03_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_04_03_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_03_2011', 'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)', 298, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_03_2011', NAME = 'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)', ORDERS = '298', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_03_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_03_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_03_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_03_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_03_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_03_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_03_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_03_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_03_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_03_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011', 'TITLE', 'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_110_04_03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_110_04_03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011', 'SERVER_TABLE_NAME', 'R_SPR_110_04_03_2011'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_110_04_03_2011'''
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_03_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_03_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_03_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_03_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_04_03_2011',0,'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_110_04_03_2011',@link_self,'Справочник счетов для формы 0503110. Таблица 4 (счета с 3)','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_110_04_03_2011')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_110_04_03_2011')
delete report_kbk where code_form= 'R_SPR_110_04_03_2011'
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 '340110110',0,'R_SPR_110_04_03_2011',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110120',0,'R_SPR_110_04_03_2011',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110130',0,'R_SPR_110_04_03_2011',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110140',0,'R_SPR_110_04_03_2011',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110151',0,'R_SPR_110_04_03_2011',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110152',0,'R_SPR_110_04_03_2011',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110153',0,'R_SPR_110_04_03_2011',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110160',0,'R_SPR_110_04_03_2011',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110171',0,'R_SPR_110_04_03_2011',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110172',0,'R_SPR_110_04_03_2011',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110173',0,'R_SPR_110_04_03_2011',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340110180',0,'R_SPR_110_04_03_2011',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120211',0,'R_SPR_110_04_03_2011',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120212',0,'R_SPR_110_04_03_2011',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120213',0,'R_SPR_110_04_03_2011',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120221',0,'R_SPR_110_04_03_2011',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120222',0,'R_SPR_110_04_03_2011',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120223',0,'R_SPR_110_04_03_2011',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120224',0,'R_SPR_110_04_03_2011',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120225',0,'R_SPR_110_04_03_2011',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120226',0,'R_SPR_110_04_03_2011',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120231',0,'R_SPR_110_04_03_2011',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120232',0,'R_SPR_110_04_03_2011',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120241',0,'R_SPR_110_04_03_2011',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120242',0,'R_SPR_110_04_03_2011',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120251',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120252',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120253',0,'R_SPR_110_04_03_2011',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120261',0,'R_SPR_110_04_03_2011',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120262',0,'R_SPR_110_04_03_2011',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120263',0,'R_SPR_110_04_03_2011',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120271',0,'R_SPR_110_04_03_2011',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120272',0,'R_SPR_110_04_03_2011',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120273',0,'R_SPR_110_04_03_2011',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '340120290',0,'R_SPR_110_04_03_2011',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_110_04_03_2011'

GO


GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Cправочник счетов для формы 0503110. Таблица 1. С КОДОМ R_SPR_AUTO_110_01_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', 2, 'Name', 'Наименование', '', 0,0)
declare @link int
select @link = link from report_spr where code = 'R_SPR_AUTO_110_01_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_AUTO_110_01_2011', 'Cправочник счетов для формы 0503110. Таблица 1.', '#Cols_tmp', '#Data_tmp', 1

GO


------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_AUTO_110_01_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_AUTO_110_01_2011]

GO
/*******************************************************************************
	© Кейсистемс (Keysystems), 25.01.2012
	справочник Cправочник счетов для формы 0503110. Таблица 1. (сгенерировано Редактором справочников)
*******************************************************************************/
CREATE     VIEW dbo.[R_SPR_AUTO_110_01_2011]
AS
SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_AUTO_110_01_2011' GROUP BY Code, begin_date, end_date

GO

GRANT SELECT ON dbo.[R_SPR_AUTO_110_01_2011] TO PUBLIC

GO

------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_110_01_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_110_01_2011'
GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011', 'Cправочник счетов для формы 0503110. Таблица 1.', 84, (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_110_01_2011', NAME = 'Cправочник счетов для формы 0503110. Таблица 1.', ORDERS = '84', 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_110_01_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'TITLE', 'Cправочник счетов для формы 0503110. Таблица 1.'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_AUTO_110_01_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_AUTO_110_01_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SERVER_TABLE_NAME', 'R_SPR_AUTO_110_01_2011'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_AUTO_110_01_2011'''
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС - получатель', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Cправочник счетов для формы 0503110. Таблица 2. С КОДОМ R_SPR_110_02_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', 2, 'Name', 'Наименование', '', 0,0)
declare @link int
select @link = link from report_spr where code = 'R_SPR_110_02_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_110_02_2011', 'Cправочник счетов для формы 0503110. Таблица 2.', '#Cols_tmp', '#Data_tmp', 1

GO


------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_110_02_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_110_02_2011]

GO
/*******************************************************************************
	© Кейсистемс (Keysystems), 25.01.2012
	справочник Cправочник счетов для формы 0503110. Таблица 2. (сгенерировано Редактором справочников)
*******************************************************************************/
CREATE     VIEW dbo.[R_SPR_110_02_2011]
AS
SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_110_02_2011' GROUP BY Code, begin_date, end_date

GO

GRANT SELECT ON dbo.[R_SPR_110_02_2011] TO PUBLIC

GO

------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_02_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_02_2011'
GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011', 'Cправочник счетов для формы 0503110. Таблица 2.', 86, (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_110_02_2011', NAME = 'Cправочник счетов для формы 0503110. Таблица 2.', ORDERS = '86', 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_110_02_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_02_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_02_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_02_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_02_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'TITLE', 'Cправочник счетов для формы 0503110. Таблица 2.'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_110_02_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_110_02_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SERVER_TABLE_NAME', 'R_SPR_110_02_2011'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_110_02_2011'''
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_110_02_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС - получатель', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_02_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO

------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник счетов для формы 0503110. Таблица 4. С КОДОМ R_SPR_110_04_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', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_AUTO_110_01_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_110_02_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_110_04_03_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_110_04_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_110_04_2011', 'Справочник счетов для формы 0503110. Таблица 4.', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_110_04_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_110_04_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 18.02.2012

	справочник Справочник счетов для формы 0503110. Таблица 4. (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_110_04_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME],begin_date,end_date FROM R_SPR_AUTO_110_01_2011 GROUP BY Code,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME],begin_date,end_date FROM R_SPR_110_02_2011 GROUP BY Code,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME],begin_date,end_date FROM R_SPR_110_04_03_2011 GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_110_04_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_04_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_110_04_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_2011', 'Справочник счетов для формы 0503110. Таблица 4.', 296, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_2011', NAME = 'Справочник счетов для формы 0503110. Таблица 4.', ORDERS = '296', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_110_04_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_110_04_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_110_04_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_110_04_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011', 'TITLE', 'Справочник счетов для формы 0503110. Таблица 4.'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_110_04_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_110_04_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011', 'SERVER_TABLE_NAME', 'R_SPR_110_04_2011'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_110_04_2011'''
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_110_04_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_110_04_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Источники (КОСГУ) С КОДОМ R_SPR_155_IST------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_STR', 3, 'code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ST', 4, 'right(code,3)', 'КОСГУ', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_155_IST'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_155_IST', 'Источники (КОСГУ)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_155_IST]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_155_IST]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Источники (КОСГУ) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_155_IST]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],code_str as [CODE_STR],right(code,3) as [ST],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_155_IST' GROUP BY Code,code_str,right(code,3), begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_155_IST] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_155_IST')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_155_IST'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST', 'Источники (КОСГУ)', 212, (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_155_IST', NAME = 'Источники (КОСГУ)', ORDERS = '212', 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_155_IST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_IST_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_IST_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_IST_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_IST_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_IST_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_IST_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST_CODE_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST_CODE_STR', 'Код строки', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_IST_CODE_STR', NAME = 'Код строки', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_IST_CODE_STR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_IST_ST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_IST_ST', 'КОСГУ', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_IST_ST', NAME = 'КОСГУ', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_IST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_IST_ST'
GO
EXEC X_SET_PROP 'R_SPR_155_IST', 'SERVER_TABLE_NAME', 'R_SPR_155_IST'
GO
EXEC X_SET_PROP 'R_SPR_155_IST', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_155_IST'''
GO
EXEC X_SET_PROP 'R_SPR_155_IST', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_155_IST'')'
GO
EXEC X_SET_PROP 'R_SPR_155_IST', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_155_IST'')'
GO
EXEC X_SET_PROP 'R_SPR_155_IST', 'TITLE', 'Источники (КОСГУ)'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE_STR', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE_STR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE_STR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_STR"'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_CODE_STR', 'FIELD_DATA', 'CODE_STR'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_ST', 'TITLE', 'КОСГУ'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_ST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_ST', 'CONTROLSOURCE', 'm.cAlias + ".ST"'
GO
EXEC X_SET_PROP 'R_SPR_155_IST_ST', 'FIELD_DATA', 'ST'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_155_IST', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_155_IST', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_155_IST', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_155_IST',0,'Источники (КОСГУ)','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_155_IST',@link_self,'Источники (КОСГУ)','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'500000',@link_self,'Источники финансирования дефицита - всего','R_SPR_155_ist',0,'500',0,'','','19000101',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,'520000',@link_self,'Источники внутреннего финансирования','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520171',@link_self,'Доходы от переоценки активов','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520310',@link_self,'Увеличение стоимости основных средств','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520410',@link_self,'Уменьшение стоимости основных средств','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520500',@link_self,'Увеличение остатков','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520520',@link_self,'Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520540',@link_self,'Увеличение задолженности по бюджетным кредитам','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520550',@link_self,'Увеличение стоимости иных финансовых активов','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520600',@link_self,'Уменьшение остатков средств','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520610',@link_self,'Выбытие со счетов бюджетов','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520620',@link_self,'Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520630',@link_self,'Уменьшение стоимости акций и иных форм участия в капитале','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520640',@link_self,'Уменьшение задолженности по бюджетным ссудам и кредитам','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520650',@link_self,'Уменьшение стоимости иных финансовых активов','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520700',@link_self,'Увеличение задолженности','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520710',@link_self,'Увеличение задолженности по внутреннему государственному       (муниципальному) долгу','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520800',@link_self,'Уменьшение задолженности','R_SPR_155_ist',0,'520',0,'','','19000101',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,'520810',@link_self,'Уменьшение задолженности по внутреннему государственному       (муниципальному) долгу','R_SPR_155_ist',0,'520',0,'','','19000101',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,'620000',@link_self,'Источники внешнего финансирования','R_SPR_155_ist',0,'620',0,'','','19000101',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,'620540',@link_self,'Увеличение задолженности по бюджетным кредитам','R_SPR_155_ist',0,'620',0,'','','19000101',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,'620640',@link_self,'Уменьшение задолженности по бюджетным ссудам и кредитам','R_SPR_155_ist',0,'620',0,'','','19000101',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,'620720',@link_self,'Увеличение задолженности по внешнему государственному долгу','R_SPR_155_ist',0,'620',0,'','','19000101',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,'620800',@link_self,'Уменьшение задолженности','R_SPR_155_ist',0,'620',0,'','','19000101',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,'620820',@link_self,'Уменьшение задолженности по внешнему государственному долгу','R_SPR_155_ist',0,'620',0,'','','19000101',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,'700000',@link_self,'Изменение остатков средств','R_SPR_155_ist',0,'700',0,'','','19000101',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,'710500',@link_self,'Увеличение остатков средств','R_SPR_155_ist',0,'710',0,'','','19000101',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,'710510',@link_self,'Увеличение задолженности по внутреннему государственному       (муниципальному) долгу','R_SPR_155_ist',0,'710',0,'','','19000101',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,'720600',@link_self,'Уменьшение остатков средств','R_SPR_155_ist',0,'720',0,'','','19000101',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,'720610',@link_self,'Выбытие со счетов бюджетов','R_SPR_155_ist',0,'720',0,'','','19000101',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,'800000',@link_self,'Изменение остатков по внутренним расходам','R_SPR_155_ist',0,'800',0,'','','19000101',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,'825000',@link_self,'Увеличение остатков по внутренним расходам','R_SPR_155_ist',0,'825',0,'','','19000101',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,'826000',@link_self,'Уменьшение остатков по внутренним расходам','R_SPR_155_ist',0,'826',0,'','','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник счетов для 410 формы С КОДОМ R_SPR_410_cshet------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_410_cshet'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_410_cshet', 'Справочник счетов для 410 формы', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_410_cshet]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_410_cshet]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 06.02.2012

	справочник Справочник счетов для 410 формы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_410_cshet]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_410_cshet' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_410_cshet] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_410_cshet')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_410_cshet'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_410_cshet', 'Справочник счетов для 410 формы', 293, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_410_cshet', NAME = 'Справочник счетов для 410 формы', ORDERS = '293', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_410_cshet'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_410_cshet_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_410_cshet_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_410_cshet_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_410_cshet_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_410_cshet_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_410_cshet_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_410_cshet_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_410_cshet_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_410_cshet'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_410_cshet_Name'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet', 'TITLE', 'Справочник счетов для 410 формы'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_410_cshet'')'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_410_cshet'')'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet', 'SERVER_TABLE_NAME', 'R_SPR_410_cshet'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_410_cshet'''
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_410_cshet_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_410_cshet', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_410_cshet', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_410_cshet', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_410_cshet',0,'Справочник счетов для 410 формы','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_410_cshet',@link_self,'Справочник счетов для 410 формы','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_410_cshet')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_410_cshet')
delete report_kbk where code_form= 'R_SPR_410_cshet'
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 '000000',0,'R_SPR_410_cshet',1,'',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20000101', '', ''
from dbo.report_kbk 
where code_form = 'R_SPR_410_cshet' and code = '740120' and begin_date  is NULL and end_date  is NULL
insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20120203', 'Расходы текущего финансового года', ''
from dbo.report_kbk 
where code_form = 'R_SPR_410_cshet' and code = '740120' and begin_date  is NULL and end_date  is NULL
exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_410_cshet'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ОКАТО для 63 формы С КОДОМ R_SPR_63_okato------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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, 'replace(OKATO,'' '','''')', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('DICTIONARY_DEPARTMENT', 'budg like ''330__'' and budg not like ''33000'' and budg not like ''3300'' and budg not like ''3309''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_63_okato'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_63_okato', 'Справочник ОКАТО для 63 формы', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_63_okato]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_63_okato]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 13.01.2012

	справочник Справочник ОКАТО для 63 формы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_63_okato]

AS

SELECT max(LINK) as Link, 0 as Link_Self,replace(OKATO,' ','') as [CODE],max(NAME) as [NAME] FROM DICTIONARY_DEPARTMENT WHERE budg like '330__' and budg not like '33000' and budg not like '3300' and budg not like '3309' GROUP BY replace(OKATO,' ','')

	UNION

	select -1 as Link, 0 as Link_Self,'88888888888' as CODE,'Всего:' as NAME

GO


GRANT SELECT ON dbo.[R_SPR_63_okato] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_63_okato')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_63_okato'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_63_okato')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_63_okato', 'Справочник ОКАТО для 63 формы', 285, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_63_okato', NAME = 'Справочник ОКАТО для 63 формы', ORDERS = '285', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_63_okato'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_63_okato_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_63_okato_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_63_okato_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_63_okato_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_63_okato_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_63_okato_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_63_okato_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_63_okato_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_63_okato_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_63_okato_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_63_okato_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_63_okato'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_63_okato_Name'
GO
EXEC X_SET_PROP 'R_SPR_63_okato', 'TITLE', 'Справочник ОКАТО для 63 формы'
GO
EXEC X_SET_PROP 'R_SPR_63_okato', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_63_okato'')'
GO
EXEC X_SET_PROP 'R_SPR_63_okato', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_63_okato'')'
GO
EXEC X_SET_PROP 'R_SPR_63_okato', 'SERVER_TABLE_NAME', 'R_SPR_63_okato'
GO
EXEC X_SET_PROP 'R_SPR_63_okato', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_63_okato'''
GO
EXEC X_SET_PROP 'R_SPR_63_okato_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_63_okato_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_63_okato', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_63_okato', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_63_okato', 'Свод-КС - получатель', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов С КОДОМ R_SPR_ACCOUNTS------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ПлСчет_Каз_2011''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACCOUNTS'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACCOUNTS', 'План счетов', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACCOUNTS]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACCOUNTS]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACCOUNTS]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ПлСчет_Каз_2011' GROUP BY Code,begin_date,end_date

	UNION

	select -1 as Link, 0 as Link_Self,'000000000' as CODE,'' as NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACCOUNTS] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACCOUNTS')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACCOUNTS'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACCOUNTS', 'План счетов', 200, (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_ACCOUNTS', NAME = 'План счетов', ORDERS = '200', 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_ACCOUNTS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACCOUNTS_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACCOUNTS_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACCOUNTS_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACCOUNTS_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACCOUNTS_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACCOUNTS_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACCOUNTS_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACCOUNTS_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACCOUNTS_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS', 'TITLE', 'План счетов'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACCOUNTS'')'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACCOUNTS'')'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS', 'SERVER_TABLE_NAME', 'R_SPR_ACCOUNTS'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACCOUNTS'''
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACCOUNTS_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACCOUNTS', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACCOUNTS', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACCOUNTS', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503779 (020120000) С КОДОМ R_SPR_ACC_779_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, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_779_1'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_779_1', 'План счетов для 0503779 (020120000)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_779_1]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_779_1]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503779 (020120000) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_779_1]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_779_1' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_779_1] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_1')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_1'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_1', 'План счетов для 0503779 (020120000)', 80, (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_ACC_779_1', NAME = 'План счетов для 0503779 (020120000)', ORDERS = '80', 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_ACC_779_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_1_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_1_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_1_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_1_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_1_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_1_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_1_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_1_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_1_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1', 'TITLE', 'План счетов для 0503779 (020120000)'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_779_1'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_779_1'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1', 'SERVER_TABLE_NAME', 'R_SPR_ACC_779_1'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_779_1'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_1_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_1', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_1', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_1', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_779_1',0,'План счетов для 0503779 (020120000)','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_ACC_779_1',@link_self,'План счетов для 0503779 (020120000)','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'020120000',@link_self,'Денежные средства на счетах учреждения в кредитной организации
','R_SPR_ACC_779_1',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,'020121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',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,'020122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',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,'020123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',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,'020126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',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,'020127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',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,'220120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'220121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'220122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'220123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'220126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'220127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'320127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'420127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'520127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'620127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720120000',@link_self,'"Денежные средства на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720121000',@link_self,'Денежные средства учреждения на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720122000',@link_self,'Денежные средства учреждения, размещенные на депозиты в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720123000',@link_self,'Денежные средства учреждения в кредитной организации в пути','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720126000',@link_self,'Аккредитивы на счетах учреждения в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',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,'720127000',@link_self,'Денежные средства учреждения в иностранной валюте на счетах в кредитной организации','R_SPR_ACC_779_1',0,'',0,'','','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503779 (020110000) С КОДОМ R_SPR_ACC_779_2------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_779_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_779_2', 'План счетов для 0503779 (020110000)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_779_2]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_779_2]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503779 (020110000) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_779_2]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_779_2' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_779_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_2', 'План счетов для 0503779 (020110000)', 81, (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_ACC_779_2', NAME = 'План счетов для 0503779 (020110000)', ORDERS = '81', 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_ACC_779_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_2_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_2_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_2_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_2_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_2_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2', 'TITLE', 'План счетов для 0503779 (020110000)'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_779_2'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_779_2'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2', 'SERVER_TABLE_NAME', 'R_SPR_ACC_779_2'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_779_2'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_2_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_779_2',0,'План счетов для 0503779 (020110000)','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_ACC_779_2',@link_self,'План счетов для 0503779 (020110000)','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'020110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',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,'020111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',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,'020113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',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,'220110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'220111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'220113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'320110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'320111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'320113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'420110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'420111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'420113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'520110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'520111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'520113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'620110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'620111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'620113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'720110000',@link_self,'Денежные средства на лицевых счетах учреждения в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'720111000',@link_self,'Денежные средства учреждения на лицевых счетах в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',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,'720113000',@link_self,'Денежные средства учреждения в пути в органе казначейства','R_SPR_ACC_779_2',0,'',0,'','','19000101',NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503779 (020134000) С КОДОМ R_SPR_ACC_779_3------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_ACC_779_3'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ACC_779_3', 'План счетов для 0503779 (020134000)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ACC_779_3]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ACC_779_3]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник План счетов для 0503779 (020134000) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ACC_779_3]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_ACC_779_3' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_ACC_779_3] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_3')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ACC_779_3'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_3', 'План счетов для 0503779 (020134000)', 82, (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_ACC_779_3', NAME = 'План счетов для 0503779 (020134000)', ORDERS = '82', 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_ACC_779_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_3_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_3_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_3_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_3_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_3_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_3_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ACC_779_3_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ACC_779_3_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ACC_779_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ACC_779_3_Name'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3', 'TITLE', 'План счетов для 0503779 (020134000)'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ACC_779_3'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ACC_779_3'')'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3', 'SERVER_TABLE_NAME', 'R_SPR_ACC_779_3'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ACC_779_3'''
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ACC_779_3_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_3', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_3', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ACC_779_3', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ACC_779_3',0,'План счетов для 0503779 (020134000)','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_ACC_779_3',@link_self,'План счетов для 0503779 (020134000)','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'020134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'220134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'320134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'420134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'520134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'620134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',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,'720134000',@link_self,'Денежные средства  в кассе учреждения','R_SPR_ACC_779_3',0,'',0,'','',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Cправочник счетов для формы 0503110. Таблица 1. С КОДОМ R_SPR_AUTO_110_01_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', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_AUTO_110_01_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_AUTO_110_01_2011', 'Cправочник счетов для формы 0503110. Таблица 1.', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_AUTO_110_01_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_AUTO_110_01_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 21.01.2012

	справочник Cправочник счетов для формы 0503110. Таблица 1. (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_AUTO_110_01_2011]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_AUTO_110_01_2011' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_AUTO_110_01_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_110_01_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_AUTO_110_01_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011', 'Cправочник счетов для формы 0503110. Таблица 1.', 84, (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_110_01_2011', NAME = 'Cправочник счетов для формы 0503110. Таблица 1.', ORDERS = '84', 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_110_01_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_AUTO_110_01_2011_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_AUTO_110_01_2011_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_AUTO_110_01_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_AUTO_110_01_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SERVER_TABLE_NAME', 'R_SPR_AUTO_110_01_2011'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_AUTO_110_01_2011'''
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_AUTO_110_01_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_AUTO_110_01_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011', 'TITLE', 'Cправочник счетов для формы 0503110. Таблица 1.'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_AUTO_110_01_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_AUTO_110_01_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_AUTO_110_01_2011',0,'Cправочник счетов для формы 0503110. Таблица 1.','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='0503110' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_AUTO_110_01_2011',@link_self,'Cправочник счетов для формы 0503110. Таблица 1.','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'000000850',@link_self,'','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'121100000',@link_self,'Внутренние расчеты по поступлениям в бюджет','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'130800000',@link_self,'Внутренние расчеты по поступлениям','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210110',@link_self,'Поступления в бюджет по налоговым доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210120',@link_self,'Поступления в бюджет по доходам от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210153',@link_self,'Поступления в бюджет от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210180',@link_self,'Поступления в бюджет по прочим доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210410',@link_self,'Поступления в бюджет от реализации основных средств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210440',@link_self,'Поступления в бюджет от реализации материальных запасов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'140210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'221100000',@link_self,'Внутренние расчеты по поступлениям в бюджет','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'230800000',@link_self,'Внутренние расчеты по поступлениям','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240200000',@link_self,'Результат по кассовым операциям бюджета','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210110',@link_self,'Поступления в бюджет по налоговым доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210120',@link_self,'Поступления в бюджет по доходам от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210130',@link_self,'Поступления в бюджет по доходам от оказания  платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210140',@link_self,'Поступления в бюджет по суммам принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210151',@link_self,'Поступления в бюджет от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210152',@link_self,'Поступления в бюджет от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210153',@link_self,'Поступления в бюджет от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210160',@link_self,'Поступления в бюджет страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210171',@link_self,'Поступления в бюджет по доходам от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210173',@link_self,'Поступление в бюджет по чрезвычайным доходам от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210180',@link_self,'Поступления в бюджет по прочим доходам','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210410',@link_self,'Поступления в бюджет от реализации основных средств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210420',@link_self,'Поступления в бюджет от реализации нематериальных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210430',@link_self,'Поступления в бюджет от реализации непроизведенных активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210440',@link_self,'Поступления в бюджет от реализации материальных запасов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210620',@link_self,'Поступления в бюджет от реализации ценных бумаг, кроме акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210630',@link_self,'Поступления в бюджет от реализации акций и иных форм участия в капитале','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210640',@link_self,'Поступления в бюджет от возврата бюджетных ссуд и кредитов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210650',@link_self,'Поступления в бюджет от выбытия иных финансовых активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210710',@link_self,'Поступления в бюджет от заимствований в виде внутреннего долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'240210720',@link_self,'Поступления в бюджет от заимствований в виде внешнего государственного долга','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101',NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110110',@link_self,'Налоговые доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110120',@link_self,'Доходы от собственности','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110130',@link_self,'Доходы от  оказания платных услуг','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110140',@link_self,'Доходы от сумм принудительного изъятия','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110151',@link_self,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110152',@link_self,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110153',@link_self,'Доходы от поступления от международных финансовых организаций','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110160',@link_self,'Доходы от страховых взносов на обязательное социальное страхование','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110171',@link_self,'Доходы от переоценки активов','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110172',@link_self,'Доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110173',@link_self,'Чрезвычайные доходы от операций с активами','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'740110180',@link_self,'Прочие доходы','R_SPR_AUTO_110_01_2011',0,'',0,'','','19000101','19000101'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503710 формы С КОДОМ R_SPR_CHET_710------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_CHET_710'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CHET_710', 'План счетов для 0503710 формы', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_CHET_710]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_CHET_710]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 14.11.2011

	справочник План счетов для 0503710 формы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_CHET_710]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_CHET_710' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_CHET_710] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CHET_710')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CHET_710'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CHET_710', 'План счетов для 0503710 формы', 242, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CHET_710', NAME = 'План счетов для 0503710 формы', ORDERS = '242', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CHET_710'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CHET_710_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CHET_710_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CHET_710_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CHET_710_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CHET_710_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CHET_710_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CHET_710_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CHET_710_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CHET_710'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CHET_710_Name'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710', 'TITLE', 'План счетов для 0503710 формы'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CHET_710'')'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CHET_710'')'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710', 'SERVER_TABLE_NAME', 'R_SPR_CHET_710'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CHET_710'''
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CHET_710_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CHET_710', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CHET_710', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CHET_710', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_CHET_710',0,'План счетов для 0503710 формы','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_CHET_710',@link_self,'План счетов для 0503710 формы','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_CHET_710')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_CHET_710')
delete report_kbk where code_form= 'R_SPR_CHET_710'
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 '230404000',0,'R_SPR_CHET_710',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230405000',0,'R_SPR_CHET_710',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '230406000',0,'R_SPR_CHET_710',1,' Расчеты, связанные с изменением типа бюджетных учреждений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110110',0,'R_SPR_CHET_710',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110120',0,'R_SPR_CHET_710',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110130',0,'R_SPR_CHET_710',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110140',0,'R_SPR_CHET_710',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110151',0,'R_SPR_CHET_710',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110152',0,'R_SPR_CHET_710',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110153',0,'R_SPR_CHET_710',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110160',0,'R_SPR_CHET_710',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110171',0,'R_SPR_CHET_710',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110172',0,'R_SPR_CHET_710',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110173',0,'R_SPR_CHET_710',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110180',0,'R_SPR_CHET_710',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120211',0,'R_SPR_CHET_710',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120212',0,'R_SPR_CHET_710',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120213',0,'R_SPR_CHET_710',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120221',0,'R_SPR_CHET_710',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120222',0,'R_SPR_CHET_710',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120223',0,'R_SPR_CHET_710',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120224',0,'R_SPR_CHET_710',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120225',0,'R_SPR_CHET_710',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120226',0,'R_SPR_CHET_710',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120231',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120232',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120241',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120242',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120251',0,'R_SPR_CHET_710',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120252',0,'R_SPR_CHET_710',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120253',0,'R_SPR_CHET_710',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120261',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120262',0,'R_SPR_CHET_710',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120263',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120271',0,'R_SPR_CHET_710',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120272',0,'R_SPR_CHET_710',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120273',0,'R_SPR_CHET_710',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120290',0,'R_SPR_CHET_710',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430404000',0,'R_SPR_CHET_710',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430405000',0,'R_SPR_CHET_710',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '430406000',0,'R_SPR_CHET_710',1,'Расчеты, связанные с изменением типа бюджетных учреждений',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110110',0,'R_SPR_CHET_710',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110120',0,'R_SPR_CHET_710',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110130',0,'R_SPR_CHET_710',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110140',0,'R_SPR_CHET_710',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110151',0,'R_SPR_CHET_710',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110152',0,'R_SPR_CHET_710',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110153',0,'R_SPR_CHET_710',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110160',0,'R_SPR_CHET_710',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110171',0,'R_SPR_CHET_710',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110172',0,'R_SPR_CHET_710',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110173',0,'R_SPR_CHET_710',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440110180',0,'R_SPR_CHET_710',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120211',0,'R_SPR_CHET_710',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120212',0,'R_SPR_CHET_710',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120213',0,'R_SPR_CHET_710',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120221',0,'R_SPR_CHET_710',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120222',0,'R_SPR_CHET_710',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120223',0,'R_SPR_CHET_710',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120224',0,'R_SPR_CHET_710',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120225',0,'R_SPR_CHET_710',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120226',0,'R_SPR_CHET_710',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120231',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120232',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120241',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120242',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120251',0,'R_SPR_CHET_710',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120252',0,'R_SPR_CHET_710',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120253',0,'R_SPR_CHET_710',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120261',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120262',0,'R_SPR_CHET_710',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120263',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120271',0,'R_SPR_CHET_710',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120272',0,'R_SPR_CHET_710',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120273',0,'R_SPR_CHET_710',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '440120290',0,'R_SPR_CHET_710',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530404000',0,'R_SPR_CHET_710',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '530406000',0,'R_SPR_CHET_710',1,'Расчеты, связанные с изменением типа бюджетных учреждений',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110110',0,'R_SPR_CHET_710',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110120',0,'R_SPR_CHET_710',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110130',0,'R_SPR_CHET_710',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110140',0,'R_SPR_CHET_710',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110151',0,'R_SPR_CHET_710',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110152',0,'R_SPR_CHET_710',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110153',0,'R_SPR_CHET_710',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110160',0,'R_SPR_CHET_710',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110171',0,'R_SPR_CHET_710',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110172',0,'R_SPR_CHET_710',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110173',0,'R_SPR_CHET_710',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540110180',0,'R_SPR_CHET_710',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120211',0,'R_SPR_CHET_710',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120212',0,'R_SPR_CHET_710',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120213',0,'R_SPR_CHET_710',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120221',0,'R_SPR_CHET_710',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120222',0,'R_SPR_CHET_710',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120223',0,'R_SPR_CHET_710',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120224',0,'R_SPR_CHET_710',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120225',0,'R_SPR_CHET_710',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120226',0,'R_SPR_CHET_710',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120231',0,'R_SPR_CHET_710',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 '540120232',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120241',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120242',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120251',0,'R_SPR_CHET_710',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120252',0,'R_SPR_CHET_710',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120253',0,'R_SPR_CHET_710',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120261',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120262',0,'R_SPR_CHET_710',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120263',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120271',0,'R_SPR_CHET_710',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120272',0,'R_SPR_CHET_710',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120273',0,'R_SPR_CHET_710',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '540120290',0,'R_SPR_CHET_710',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630404000',0,'R_SPR_CHET_710',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '630406000',0,'R_SPR_CHET_710',1,'Расчеты, связанные с изменением типа бюджетных учреждений',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110110',0,'R_SPR_CHET_710',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110120',0,'R_SPR_CHET_710',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110130',0,'R_SPR_CHET_710',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110140',0,'R_SPR_CHET_710',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110151',0,'R_SPR_CHET_710',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110152',0,'R_SPR_CHET_710',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110153',0,'R_SPR_CHET_710',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110160',0,'R_SPR_CHET_710',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110171',0,'R_SPR_CHET_710',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110172',0,'R_SPR_CHET_710',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110173',0,'R_SPR_CHET_710',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640110180',0,'R_SPR_CHET_710',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120211',0,'R_SPR_CHET_710',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120212',0,'R_SPR_CHET_710',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120213',0,'R_SPR_CHET_710',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120221',0,'R_SPR_CHET_710',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120222',0,'R_SPR_CHET_710',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120223',0,'R_SPR_CHET_710',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120224',0,'R_SPR_CHET_710',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120225',0,'R_SPR_CHET_710',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120226',0,'R_SPR_CHET_710',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120231',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120232',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120241',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120242',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120251',0,'R_SPR_CHET_710',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120252',0,'R_SPR_CHET_710',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120253',0,'R_SPR_CHET_710',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120261',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120262',0,'R_SPR_CHET_710',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120263',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120271',0,'R_SPR_CHET_710',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120272',0,'R_SPR_CHET_710',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120273',0,'R_SPR_CHET_710',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '640120290',0,'R_SPR_CHET_710',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730404000',0,'R_SPR_CHET_710',1,'Внутриведомственные расчеты',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730405000',0,'R_SPR_CHET_710',1,'Расчеты по платежам из бюджета с финансовым органом',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '730406000',0,'R_SPR_CHET_710',1,' Расчеты, связанные с изменением типа бюджетных учреждений',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110110',0,'R_SPR_CHET_710',1,'Налоговые доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110120',0,'R_SPR_CHET_710',1,'Доходы от собственности',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110130',0,'R_SPR_CHET_710',1,'Доходы от  оказания платных услуг',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110140',0,'R_SPR_CHET_710',1,'Доходы от сумм принудительного изъятия',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110151',0,'R_SPR_CHET_710',1,'Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110152',0,'R_SPR_CHET_710',1,'Доходы от поступлений от наднациональных организаций и правительств иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110153',0,'R_SPR_CHET_710',1,'Доходы от поступления от международных финансовых организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110160',0,'R_SPR_CHET_710',1,'Доходы от страховых взносов на обязательное социальное страхование',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110171',0,'R_SPR_CHET_710',1,'Доходы от переоценки активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110172',0,'R_SPR_CHET_710',1,'Доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110173',0,'R_SPR_CHET_710',1,'Чрезвычайные доходы от операций с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110180',0,'R_SPR_CHET_710',1,'Прочие доходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120211',0,'R_SPR_CHET_710',1,'Расходы по заработной плате',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120212',0,'R_SPR_CHET_710',1,'Расходы по прочим выплатам',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120213',0,'R_SPR_CHET_710',1,'Расходы на начисления на выплаты по оплате труда',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120221',0,'R_SPR_CHET_710',1,'Расходы на услуги связи',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120222',0,'R_SPR_CHET_710',1,'Расходы на транспортные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120223',0,'R_SPR_CHET_710',1,'Расходы на коммунальные услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120224',0,'R_SPR_CHET_710',1,'Расходы на арендную плату за пользование имуществом',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120225',0,'R_SPR_CHET_710',1,'Расходы на работы, услуги по содержанию имущества',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120226',0,'R_SPR_CHET_710',1,'Расходы на прочие работы, услуги',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120231',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внутреннего долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120232',0,'R_SPR_CHET_710',1,'Расходы на обслуживание внешнего государственного долга',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120241',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления государственным и муниципальным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120242',0,'R_SPR_CHET_710',1,'Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120251',0,'R_SPR_CHET_710',1,'Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120252',0,'R_SPR_CHET_710',1,'Расходы на перечисления наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120253',0,'R_SPR_CHET_710',1,'Расходы на перечисления международным организациям',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120261',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120262',0,'R_SPR_CHET_710',1,'Расходы на пособия по социальной помощи населению',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120263',0,'R_SPR_CHET_710',1,'Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120271',0,'R_SPR_CHET_710',1,'Расходы на амортизацию основных средств и нематериальных активов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120272',0,'R_SPR_CHET_710',1,'Расходование материальных запасов',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120273',0,'R_SPR_CHET_710',1,'Чрезвычайные расходы по операциям с активами',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120290',0,'R_SPR_CHET_710',1,'Прочие расходы',0,'',0,'','', '19000101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_CHET_710',1,'Итого',0,'',0,'','', '19000101',NULL,0

insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20000101', '', ''
from dbo.report_kbk 
where code_form = 'R_SPR_CHET_710' and code = '530406000' and begin_date  is NULL and end_date  is NULL
insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20120208', 'Расчеты, связанные с изменением типа бюджетных учреждений', ''
from dbo.report_kbk 
where code_form = 'R_SPR_CHET_710' and code = '530406000' and begin_date  is NULL and end_date  is NULL
exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_CHET_710'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Федеральный справочник целевых статей 0503324 С КОДОМ R_SPR_CSR_FED_2011_324------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_CSR_FED_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_CSR_FED_2011_324'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_CSR_FED_2011_324', 'Федеральный справочник целевых статей 0503324', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_CSR_FED_2011_324]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_CSR_FED_2011_324]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 13.01.2012

	справочник Федеральный справочник целевых статей 0503324 (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_CSR_FED_2011_324]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM R_SPR_CSR_FED_2011 GROUP BY Code

	UNION

	select -1 as Link, 0 as Link_Self,'8888888' as CODE,'' as NAME

GO


GRANT SELECT ON dbo.[R_SPR_CSR_FED_2011_324] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_FED_2011_324')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_CSR_FED_2011_324'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2011_324', 'Федеральный справочник целевых статей 0503324', 281, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2011_324', NAME = 'Федеральный справочник целевых статей 0503324', ORDERS = '281', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2011_324'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2011_324_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2011_324_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2011_324_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2011_324_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2011_324_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2011_324_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_CSR_FED_2011_324_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_CSR_FED_2011_324_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_CSR_FED_2011_324'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_CSR_FED_2011_324_Name'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324', 'SERVER_TABLE_NAME', 'R_SPR_CSR_FED_2011_324'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_CSR_FED_2011_324'''
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_CSR_FED_2011_324'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_CSR_FED_2011_324'')'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324', 'TITLE', 'Федеральный справочник целевых статей 0503324'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_CSR_FED_2011_324_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2011_324', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2011_324', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_CSR_FED_2011_324', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы расходов С КОДОМ R_SPR_DEP_410rash_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 ('RzPr', 1, '''000''+SUBSTRING(R.Code,4,4) + ''0000000000''', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Shet', 2, 'left(S.Code,6)', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('EKR', 3, 'substring(R .Code,18,3)', 'ЭКР', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_RASH_317_2011 R join (select code from R_SPR_410_cshet ) S on 1=1', '((SUBSTRING(R.code,18, 3) IN (''251'',''241'') AND substring(R.code, 4, 4) LIKE ''14%'') OR (SUBSTRING(R.code,18,3) <> ''251'') AND NOT (substring(R.code, 4,4) LIKE ''14%'') OR (SUBSTRING(R.code,18, 3)=''251'') AND NOT (substring(R.code, 4, 4) LIKE ''14%''))')

insert #Data_tmp (Table_From, Filter)
values ('(select link, ''00000000000000000'' + code code  from R_SPR_EKR_RASH_2011) R join (select code from R_SPR_410_cshet  where left(code,4) = ''2401'' OR left(code,4) = ''7401'') S on 1=1', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410rash_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410rash_2011', 'Справочник зависимостей для формы 410 таблицы расходов', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410rash_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410rash_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 03.02.2012

	справочник Справочник зависимостей для формы 410 таблицы расходов (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410rash_2011]

AS

SELECT max(LINK) as Link, 0 as Link_Self,'000'+SUBSTRING(R.Code,4,4) + '0000000000' as [RZPR],left(S.Code,6) as [SHET],substring(R .Code,18,3) as [EKR],convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date FROM R_SPR_RASH_317_2011 R join (select code from R_SPR_410_cshet ) S on 1=1 WHERE ((SUBSTRING(R.code,18, 3) IN ('251','241') AND substring(R.code, 4, 4) LIKE '14%') OR (SUBSTRING(R.code,18,3) <> '251') AND NOT (substring(R.code, 4,4) LIKE '14%') OR (SUBSTRING(R.code,18, 3)='251') AND NOT (substring(R.code, 4, 4) LIKE '14%')) GROUP BY '000'+SUBSTRING(R.Code,4,4) + '0000000000',left(S.Code,6),substring(R .Code,18,3)

	UNION

	SELECT max(LINK) as Link, 0 as Link_Self,'000'+SUBSTRING(R.Code,4,4) + '0000000000' as [RZPR],left(S.Code,6) as [SHET],substring(R .Code,18,3) as [EKR],convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date FROM (select link, '00000000000000000' + code code  from R_SPR_EKR_RASH_2011) R join (select code from R_SPR_410_cshet  where left(code,4) = '2401' OR left(code,4) = '7401') S on 1=1 GROUP BY '000'+SUBSTRING(R.Code,4,4) + '0000000000',left(S.Code,6),substring(R .Code,18,3)

	UNION

	select -1 as Link, 0 as Link_Self,'00000000000000000' as RZPR,'000000' as SHET,'960' as EKR,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410rash_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410rash_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410rash_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410rash_2011', 'Справочник зависимостей для формы 410 таблицы расходов', 220, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410rash_2011', NAME = 'Справочник зависимостей для формы 410 таблицы расходов', ORDERS = '220', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410rash_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410rash_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410rash_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410rash_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011_RzPr')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410rash_2011_RzPr', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410rash_2011_RzPr', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410rash_2011_RzPr'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011_Shet')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410rash_2011_Shet', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410rash_2011_Shet', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410rash_2011_Shet'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011_EKR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410rash_2011_EKR', 'ЭКР', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410rash_2011_EKR', NAME = 'ЭКР', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410rash_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410rash_2011_EKR'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы расходов'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410rash_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410rash_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410rash_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410rash_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_RzPr', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_RzPr', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_RzPr', 'CONTROLSOURCE', 'm.cAlias + ".RzPr"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_RzPr', 'FIELD_DATA', 'RzPr'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_Shet', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_Shet', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_Shet', 'CONTROLSOURCE', 'm.cAlias + ".Shet"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_Shet', 'FIELD_DATA', 'Shet'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_EKR', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_EKR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_EKR', 'CONTROLSOURCE', 'm.cAlias + ".EKR"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410rash_2011_EKR', 'FIELD_DATA', 'EKR'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410rash_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410rash_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410rash_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы доходы С КОДОМ R_SPR_DEP_410_08_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 ('DOH', 1, 'Code', 'Доходы', '', 1,17)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ACC', 2, '''740110''', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SGU', 3, 'Code', 'СГУ', '', 18,3)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011'' and substring(Code,4,1)  = ''3''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410_08_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410_08_2011', 'Справочник зависимостей для формы 410 таблицы доходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410_08_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410_08_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 04.02.2012

	справочник Справочник зависимостей для формы 410 таблицы доходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410_08_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,1,17) as [DOH],'740110' as [ACC],SUBSTRING(Code,18,3) as [SGU],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011' and substring(Code,4,1)  = '3' GROUP BY SUBSTRING(Code,1,17),SUBSTRING(Code,18,3),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410_08_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_08_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_08_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_08_2011', 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_08_2011', NAME = 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_08_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_08_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_08_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_08_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_08_2011_DOH', 'Доходы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_08_2011_DOH', NAME = 'Доходы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_08_2011_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_08_2011_ACC', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_08_2011_ACC', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_08_2011_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011_SGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_08_2011_SGU', 'СГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_08_2011_SGU', NAME = 'СГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_08_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_08_2011_SGU'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410_08_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410_08_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410_08_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410_08_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_DOH', 'TITLE', 'Доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_DOH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_DOH', 'CONTROLSOURCE', 'm.cAlias + ".DOH"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_DOH', 'FIELD_DATA', 'DOH'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_ACC', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_ACC', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_ACC', 'CONTROLSOURCE', 'm.cAlias + ".ACC"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_ACC', 'FIELD_DATA', 'ACC'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_SGU', 'TITLE', 'СГУ'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_SGU', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_SGU', 'CONTROLSOURCE', 'm.cAlias + ".SGU"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_08_2011_SGU', 'FIELD_DATA', 'SGU'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_08_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_08_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_08_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы доходы С КОДОМ R_SPR_DEP_410_09_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 ('DOH', 1, 'Code', 'Доходы', '', 1,17)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ACC', 2, '''740110''', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SGU', 3, '''172''', 'СГУ', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011'' and (code like ''000302%'' or code like ''000303%'' )')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410_09_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410_09_2011', 'Справочник зависимостей для формы 410 таблицы доходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410_09_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410_09_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 04.02.2012

	справочник Справочник зависимостей для формы 410 таблицы доходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410_09_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,1,17) as [DOH],'740110' as [ACC],'172' as [SGU],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011' and (code like '000302%' or code like '000303%' ) GROUP BY SUBSTRING(Code,1,17),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410_09_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_09_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_09_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_09_2011', 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_09_2011', NAME = 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_09_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_09_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_09_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_09_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_09_2011_DOH', 'Доходы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_09_2011_DOH', NAME = 'Доходы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_09_2011_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_09_2011_ACC', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_09_2011_ACC', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_09_2011_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011_SGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_09_2011_SGU', 'СГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_09_2011_SGU', NAME = 'СГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_09_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_09_2011_SGU'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410_09_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410_09_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410_09_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410_09_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_DOH', 'TITLE', 'Доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_DOH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_DOH', 'CONTROLSOURCE', 'm.cAlias + ".DOH"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_DOH', 'FIELD_DATA', 'DOH'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_ACC', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_ACC', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_ACC', 'CONTROLSOURCE', 'm.cAlias + ".ACC"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_ACC', 'FIELD_DATA', 'ACC'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_SGU', 'TITLE', 'СГУ'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_SGU', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_SGU', 'CONTROLSOURCE', 'm.cAlias + ".SGU"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_09_2011_SGU', 'FIELD_DATA', 'SGU'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_09_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_09_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_09_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы доходы С КОДОМ R_SPR_DEP_410_10_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 ('DOH', 1, 'Code', 'Доходы', '', 1,17)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ACC', 2, '''740110''', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SGU', 3, '''173''', 'СГУ', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011'' and (code like ''000302%'' or code like ''000303%'' )')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410_10_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410_10_2011', 'Справочник зависимостей для формы 410 таблицы доходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410_10_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410_10_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 04.02.2012

	справочник Справочник зависимостей для формы 410 таблицы доходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410_10_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,1,17) as [DOH],'740110' as [ACC],'173' as [SGU],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011' and (code like '000302%' or code like '000303%' ) GROUP BY SUBSTRING(Code,1,17),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410_10_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_10_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_10_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_10_2011', 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_10_2011', NAME = 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_10_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_10_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_10_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_10_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_10_2011_DOH', 'Доходы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_10_2011_DOH', NAME = 'Доходы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_10_2011_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_10_2011_ACC', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_10_2011_ACC', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_10_2011_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011_SGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_10_2011_SGU', 'СГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_10_2011_SGU', NAME = 'СГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_10_2011_SGU'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410_10_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410_10_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410_10_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410_10_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_DOH', 'TITLE', 'Доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_DOH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_DOH', 'CONTROLSOURCE', 'm.cAlias + ".DOH"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_DOH', 'FIELD_DATA', 'DOH'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_ACC', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_ACC', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_ACC', 'CONTROLSOURCE', 'm.cAlias + ".ACC"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_ACC', 'FIELD_DATA', 'ACC'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_SGU', 'TITLE', 'СГУ'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_SGU', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_SGU', 'CONTROLSOURCE', 'm.cAlias + ".SGU"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_10_2011_SGU', 'FIELD_DATA', 'SGU'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_10_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_10_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_10_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы доходы С КОДОМ R_SPR_DEP_410_11_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 ('DOH', 1, 'Code', 'Доходы', '', 1,17)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ACC', 2, '''740110''', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SGU', 3, '''171''', 'СГУ', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011'' and (code like ''000302%'' or code like ''000303%'' )')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410_11_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410_11_2011', 'Справочник зависимостей для формы 410 таблицы доходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410_11_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410_11_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 04.02.2012

	справочник Справочник зависимостей для формы 410 таблицы доходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410_11_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,1,17) as [DOH],'740110' as [ACC],'171' as [SGU],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011' and (code like '000302%' or code like '000303%' ) GROUP BY SUBSTRING(Code,1,17),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410_11_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_11_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_11_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_11_2011', 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_11_2011', NAME = 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_11_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_11_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_11_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_11_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_11_2011_DOH', 'Доходы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_11_2011_DOH', NAME = 'Доходы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_11_2011_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_11_2011_ACC', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_11_2011_ACC', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_11_2011_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011_SGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_11_2011_SGU', 'СГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_11_2011_SGU', NAME = 'СГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_11_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_11_2011_SGU'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410_11_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410_11_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410_11_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410_11_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_DOH', 'TITLE', 'Доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_DOH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_DOH', 'CONTROLSOURCE', 'm.cAlias + ".DOH"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_DOH', 'FIELD_DATA', 'DOH'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_ACC', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_ACC', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_ACC', 'CONTROLSOURCE', 'm.cAlias + ".ACC"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_ACC', 'FIELD_DATA', 'ACC'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_SGU', 'TITLE', 'СГУ'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_SGU', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_SGU', 'CONTROLSOURCE', 'm.cAlias + ".SGU"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_11_2011_SGU', 'FIELD_DATA', 'SGU'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_11_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_11_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_11_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник зависимостей для формы 410 таблицы доходы С КОДОМ R_SPR_DEP_410_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 ('DOH', 1, '''000''+substring(DOH,4,10)+''0000''', 'Доходы', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ACC', 2, 'ACC', 'Счет', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SGU', 3, 'SGU', 'СГУ', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_01_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_02_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_03_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_04_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_05_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_06_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_07_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_08_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_09_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_10_2011', '')

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_DEP_410_11_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DEP_410_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DEP_410_2011', 'Справочник зависимостей для формы 410 таблицы доходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DEP_410_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DEP_410_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 04.02.2012

	справочник Справочник зависимостей для формы 410 таблицы доходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DEP_410_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_01_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_02_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_03_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_04_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_05_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_06_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_07_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_08_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_09_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_10_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'000'+substring(DOH,4,10)+'0000' as [DOH],ACC as [ACC],SGU as [SGU],begin_date,end_date FROM R_SPR_DEP_410_11_2011 GROUP BY '000'+substring(DOH,4,10)+'0000',ACC,SGU,begin_date,end_date

	UNION

	select -1 as Link, 0 as Link_Self,'00000000000000000' as DOH,'000000' as ACC,'850' as SGU,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_DEP_410_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DEP_410_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_2011', 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_2011', NAME = 'Справочник зависимостей для формы 410 таблицы доходы', 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_DEP_410_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_2011_DOH', 'Доходы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_2011_DOH', NAME = 'Доходы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_2011_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_2011_ACC', 'Счет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_2011_ACC', NAME = 'Счет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_2011_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011_SGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DEP_410_2011_SGU', 'СГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DEP_410_2011_SGU', NAME = 'СГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DEP_410_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DEP_410_2011_SGU'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011', 'TITLE', 'Справочник зависимостей для формы 410 таблицы доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DEP_410_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DEP_410_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011', 'SERVER_TABLE_NAME', 'R_SPR_DEP_410_2011'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DEP_410_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_DOH', 'TITLE', 'Доходы'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_DOH', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_DOH', 'CONTROLSOURCE', 'm.cAlias + ".DOH"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_DOH', 'FIELD_DATA', 'DOH'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_ACC', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_ACC', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_ACC', 'CONTROLSOURCE', 'm.cAlias + ".ACC"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_ACC', 'FIELD_DATA', 'ACC'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_SGU', 'TITLE', 'СГУ'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_SGU', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_SGU', 'CONTROLSOURCE', 'm.cAlias + ".SGU"'
GO
EXEC X_SET_PROP 'R_SPR_DEP_410_2011_SGU', 'FIELD_DATA', 'SGU'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DEP_410_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник доходов (10 знаков) С КОДОМ R_SPR_DOH_10_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', 'Код', '', 4,10)

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 ('Code_str', 2, 'Code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 4, 'LONG_NAME', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('PROPERTY', 5, 'PROPERTY', 'Итог', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form=''ДОХОДЫ_2011'' and Code not in(select KK.Code from dbo.report_kbk KK where KK.Code_form=''ДОХОДЫ_2011_USER'' and(isnull(kk.[ed],''30000101'')>isnull(report_kbk.[bd],''19000101'') and isnull(report_kbk.[ed],''30000101'')>isnull(kk.[bd],''19000101'')))')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DOH_10_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DOH_10_2011', 'Справочник доходов (10 знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DOH_10_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DOH_10_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 15.02.2012

	справочник Справочник доходов (10 знаков) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DOH_10_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,10) as [CODE],Code_str as [CODE_STR],PROPERTY as [PROPERTY],max(Name) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form='ДОХОДЫ_2011' and Code not in(select KK.Code from dbo.report_kbk KK where KK.Code_form='ДОХОДЫ_2011_USER' and(isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101') and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) GROUP BY SUBSTRING(Code,4,10),Code_str,PROPERTY,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,10) as [CODE],Code_str as [CODE_STR],PROPERTY as [PROPERTY],max(Name) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011_USER' GROUP BY SUBSTRING(Code,4,10),Code_str,PROPERTY,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DOH_10_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_10_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_10_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011', 'Справочник доходов (10 знаков)', 237, (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_DOH_10_2011', NAME = 'Справочник доходов (10 знаков)', ORDERS = '237', 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_DOH_10_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_Long_name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_Long_name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_Long_name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011_PROPERTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_10_2011_PROPERTY', 'Итог', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_10_2011_PROPERTY', NAME = 'Итог', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_10_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_10_2011_PROPERTY'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011', 'TITLE', 'Справочник доходов (10 знаков)'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DOH_10_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DOH_10_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011', 'SERVER_TABLE_NAME', 'R_SPR_DOH_10_2011'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DOH_10_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_PROPERTY', 'TITLE', 'Итог'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_PROPERTY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_PROPERTY', 'CONTROLSOURCE', 'm.cAlias + ".PROPERTY"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_10_2011_PROPERTY', 'FIELD_DATA', 'PROPERTY'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_10_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_10_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_10_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник доходов (14 знаков) С КОДОМ R_SPR_DOH_14_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', 'Код', '', 4,14)

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, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 4, 'Long_name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form=''ДОХОДЫ_2011'' and Code not in(select KK.Code from dbo.report_kbk KK where KK.Code_form=''ДОХОДЫ_2011_USER'' and(isnull(kk.[ed],''30000101'')>isnull(report_kbk.[bd],''19000101'') and isnull(report_kbk.[ed],''30000101'')>isnull(kk.[bd],''19000101'')))')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ДОХОДЫ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_DOH_14_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_DOH_14_2011', 'Справочник доходов (14 знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_DOH_14_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_DOH_14_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 15.02.2012

	справочник Справочник доходов (14 знаков) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_DOH_14_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,14) as [CODE],Code_str as [CODE_STR],max(Name) as [NAME],max(Long_name) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form='ДОХОДЫ_2011' and Code not in(select KK.Code from dbo.report_kbk KK where KK.Code_form='ДОХОДЫ_2011_USER' and(isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101') and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) GROUP BY SUBSTRING(Code,4,14),Code_str,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,SUBSTRING(Code,4,14) as [CODE],Code_str as [CODE_STR],max(Name) as [NAME],max(Long_name) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ДОХОДЫ_2011_USER' GROUP BY SUBSTRING(Code,4,14),Code_str,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_DOH_14_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_14_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_DOH_14_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011', 'Справочник доходов (14 знаков)', 236, (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_DOH_14_2011', NAME = 'Справочник доходов (14 знаков)', ORDERS = '236', 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_DOH_14_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_14_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_14_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_14_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_14_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_14_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_14_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_14_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_14_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_DOH_14_2011_Long_name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_DOH_14_2011_Long_name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_DOH_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_DOH_14_2011_Long_name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011', 'TITLE', 'Справочник доходов (14 знаков)'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_DOH_14_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_DOH_14_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011', 'SERVER_TABLE_NAME', 'R_SPR_DOH_14_2011'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_DOH_14_2011'''
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_DOH_14_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_14_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_14_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_DOH_14_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Источники финасирования 20 зкнаков (без досчета строки 700500) С КОДОМ R_SPR_IST_124M03_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 ('CODE_STR', 2, 'CODE_STR', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_IST', 3, 'CODE_IST', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('STROKA', 4, 'STROKA', 'Номер строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('NAME', 5, 'NAME', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LONG_NAME', 6, 'LONG_NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_IST_124_2011', 'CODE <> ''70001050000000000000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_124M03_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_124M03_2011', 'Источники финасирования 20 зкнаков (без досчета строки 700500)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_IST_124M03_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_IST_124M03_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 28.01.2012

	справочник Источники финасирования 20 зкнаков (без досчета строки 700500) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_IST_124M03_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],CODE_STR as [CODE_STR],CODE_IST as [CODE_IST],STROKA as [STROKA],max(NAME) as [NAME],max(LONG_NAME) as [LONG_NAME] FROM R_SPR_IST_124_2011 WHERE CODE <> '70001050000000000000' GROUP BY Code,CODE_STR,CODE_IST,STROKA

GO


GRANT SELECT ON dbo.[R_SPR_IST_124M03_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_124M03_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_124M03_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011', 'Источники финасирования 20 зкнаков (без досчета строки 700500)', 201, (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_IST_124M03_2011', NAME = 'Источники финасирования 20 зкнаков (без досчета строки 700500)', ORDERS = '201', 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_IST_124M03_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_CODE_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_CODE_STR', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_CODE_STR', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_CODE_STR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_CODE_IST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_CODE_IST', 'Код', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_CODE_IST', NAME = 'Код', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_CODE_IST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_STROKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_STROKA', 'Номер строки', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_STROKA', NAME = 'Номер строки', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_STROKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_NAME', 'Наименование', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_NAME', NAME = 'Наименование', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011_LONG_NAM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_124M03_2011_LONG_NAM', 'Наименование', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_124M03_2011_LONG_NAM', NAME = 'Наименование', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_124M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_124M03_2011_LONG_NAM'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011', 'TITLE', 'Источники финасирования 20 зкнаков (без досчета строки 700500)'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_124M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_124M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_124M03_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_124M03_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_STR', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_STR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_STR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_STR"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_STR', 'FIELD_DATA', 'CODE_STR'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_IST', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_IST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_IST', 'CONTROLSOURCE', 'm.cAlias + ".CODE_IST"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_CODE_IST', 'FIELD_DATA', 'CODE_IST'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_STROKA', 'TITLE', 'Номер строки'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_STROKA', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_STROKA', 'CONTROLSOURCE', 'm.cAlias + ".STROKA"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_STROKA', 'FIELD_DATA', 'STROKA'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_LONG_NAM', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_LONG_NAM', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_LONG_NAM', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_124M03_2011_LONG_NAM', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_124M03_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_124M03_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_124M03_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник источников (14знаков) С КОДОМ R_SPR_IST_14_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, 'left(Code,3)+substring(code,7,14)', 'КОД', '', 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, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LONG_NAME', 4, 'LONG_NAME', 'полное наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_IST', 5, 'Code', 'КОД', '', 7,14)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('property', 6, 'property', '', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form=''ИСТОЧНИКИ_2011'' and Code NOT IN (select KK.code from dbo.[rk] KK where KK.Code_form=''ИСТОЧНИКИ_2011_USER'' and(isnull(kk.[ed],''30000101'')>isnull([rk].[bd],''19000101'')and isnull([rk].[ed],''30000101'')>isnull(kk.[bd],''19000101''))) and code<''800''')

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ИСТОЧНИКИ_2011_USER''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_14_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_14_2011', 'Справочник источников (14знаков)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_IST_14_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_IST_14_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 15.02.2012

	справочник Справочник источников (14знаков) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_IST_14_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(Code,3)+substring(code,7,14) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,14) as [CODE_IST],property as [PROPERTY],max(Name) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form='ИСТОЧНИКИ_2011' and Code NOT IN (select KK.code from dbo.report_kbk KK where KK.Code_form='ИСТОЧНИКИ_2011_USER' and(isnull(kk.end_date,'30000101')>isnull(report_kbk.begin_date,'19000101')and isnull(report_kbk.end_date,'30000101')>isnull(kk.begin_date,'19000101'))) and code<'800' GROUP BY left(Code,3)+substring(code,7,14),Code_str,SUBSTRING(Code,7,14),property,begin_date,end_date

	UNION

	SELECT max(LINK) as Link, max(Link_Self) as Link_Self,left(Code,3)+substring(code,7,14) as [CODE],Code_str as [CODE_STR],SUBSTRING(Code,7,14) as [CODE_IST],property as [PROPERTY],max(Name) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ИСТОЧНИКИ_2011_USER' GROUP BY left(Code,3)+substring(code,7,14),Code_str,SUBSTRING(Code,7,14),property,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_14_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_14_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_14_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011', 'Справочник источников (14знаков)', 239, (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_IST_14_2011', NAME = 'Справочник источников (14знаков)', ORDERS = '239', 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_IST_14_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_Code')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_Code', 'КОД', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_Code', NAME = 'КОД', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_Code'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_LONG_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_LONG_NAME', 'полное наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_LONG_NAME', NAME = 'полное наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_LONG_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_Code_IST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_Code_IST', 'КОД', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_Code_IST', NAME = 'КОД', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_Code_IST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011_property')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_14_2011_property', '', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_14_2011_property', NAME = '', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_14_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_14_2011_property'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011', 'TITLE', 'Справочник источников (14знаков)'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_14_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_14_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_14_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_14_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code', 'TITLE', 'КОД'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code', 'CONTROLSOURCE', 'm.cAlias + ".Code"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code', 'FIELD_DATA', 'Code'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_LONG_NAME', 'TITLE', 'полное наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_LONG_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_LONG_NAME', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_LONG_NAME', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_IST', 'TITLE', 'КОД'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_IST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_IST', 'CONTROLSOURCE', 'm.cAlias + ".Code_IST"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_Code_IST', 'FIELD_DATA', 'Code_IST'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_property', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_property', 'CONTROLSOURCE', 'm.cAlias + ".property"'
GO
EXEC X_SET_PROP 'R_SPR_IST_14_2011_property', 'FIELD_DATA', 'property'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_14_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_14_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_14_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник источников (без досчета строки 7000105) С КОДОМ R_SPR_IST_1703_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 ('Code_str', 2, 'Code_str', 'КОД СТРОКИ', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 4, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_IST', 3, 'CODE_IST', 'Код источника', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LONG_NAME', 5, 'LONG_NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_IST_17_2011', 'CODE<>''70001050000000000000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_1703_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_1703_2011', 'Справочник источников (без досчета строки 7000105)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_IST_1703_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_IST_1703_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Справочник источников (без досчета строки 7000105) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_IST_1703_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,CODE as [CODE],Code_str as [CODE_STR],CODE_IST as [CODE_IST],max(Name) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM R_SPR_IST_17_2011 WHERE CODE<>'70001050000000000000' GROUP BY CODE,Code_str,CODE_IST,begin_date,end_date

	UNION

	select -1 as Link, isnull((select link from dbo.R_SPR_IST_17_2011 where code = '70001000000000000000'),0) as Link_Self,'70001050000000000000' as CODE,'700' as CODE_STR,'01050000000000000' as CODE_IST,'Изменение остатков средств на счетах по учету средств бюджета ' as NAME,'Изменение остатков средств на счетах по учету средств бюджета' as LONG_NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_1703_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_1703_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_1703_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011', 'Справочник источников (без досчета строки 7000105)', 19, (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_IST_1703_2011', NAME = 'Справочник источников (без досчета строки 7000105)', ORDERS = '19', 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_IST_1703_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_CODE_IST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_CODE_IST', 'Код источника', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_CODE_IST', NAME = 'Код источника', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_CODE_IST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_Name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_Name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011_LONG_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_1703_2011_LONG_NAME', 'Наименование', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_1703_2011_LONG_NAME', NAME = 'Наименование', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_1703_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_1703_2011_LONG_NAME'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_1703_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_1703_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_1703_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_1703_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011', 'TITLE', 'Справочник источников (без досчета строки 7000105)'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE_IST', 'TITLE', 'Код источника'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE_IST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE_IST', 'CONTROLSOURCE', 'm.cAlias + ".CODE_IST"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_CODE_IST', 'FIELD_DATA', 'CODE_IST'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_LONG_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_LONG_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_LONG_NAME', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_1703_2011_LONG_NAME', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_1703_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_1703_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_1703_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник истчников для формы 0503317M С КОДОМ R_SPR_IST_317_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 ('Code_str', 2, 'Code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('STROKA', 3, 'add_info', 'Строка', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 4, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Code_Ist', 5, 'Code', 'Код источника', '', 4,20)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Long_name', 6, 'Long_name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ИСТОЧНИКИ_2011'' and code_str< ''800''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_317_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_317_2011', 'Справочник истчников для формы 0503317M', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_IST_317_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_IST_317_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Справочник истчников для формы 0503317M (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_IST_317_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],add_info as [STROKA],SUBSTRING(Code,4,20) as [CODE_IST],max(Name) as [NAME],max(Long_name) as [LONG_NAME],begin_date,end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE Code_Form = 'ИСТОЧНИКИ_2011' and code_str< '800' GROUP BY Code,Code_str,add_info,SUBSTRING(Code,4,20),begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_317_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_317_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_317_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011', 'Справочник истчников для формы 0503317M', 14, (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_IST_317_2011', NAME = 'Справочник истчников для формы 0503317M', ORDERS = '14', 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_IST_317_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_STROKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_STROKA', 'Строка', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_STROKA', NAME = 'Строка', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_STROKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_Name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_Name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_Code_Ist')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_Code_Ist', 'Код источника', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_Code_Ist', NAME = 'Код источника', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_Code_Ist'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011_Long_name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317_2011_Long_name', 'Наименование', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317_2011_Long_name', NAME = 'Наименование', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317_2011_Long_name'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011', 'TITLE', 'Справочник истчников для формы 0503317M'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_317_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_317_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_317_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_317_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_STROKA', 'TITLE', 'Строка'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_STROKA', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_STROKA', 'CONTROLSOURCE', 'm.cAlias + ".STROKA"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_STROKA', 'FIELD_DATA', 'STROKA'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_Ist', 'TITLE', 'Код источника'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_Ist', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_Ist', 'CONTROLSOURCE', 'm.cAlias + ".Code_Ist"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Code_Ist', 'FIELD_DATA', 'Code_Ist'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Long_name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Long_name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Long_name', 'CONTROLSOURCE', 'm.cAlias + ".Long_name"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317_2011_Long_name', 'FIELD_DATA', 'Long_name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Источники финасирования (без досчета строки 700500) С КОДОМ R_SPR_IST_317M03_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 ('CODE_STR', 2, 'CODE_STR', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_IST', 3, 'CODE_IST', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('STROKA', 4, 'STROKA', 'Номер строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('NAME', 5, 'NAME', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('LONG_NAME', 6, 'LONG_NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_IST_317_2011', 'CODE<>''70000001050000000000000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_IST_317M03_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_IST_317M03_2011', 'Источники финасирования (без досчета строки 700500)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_IST_317M03_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_IST_317M03_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 28.01.2012

	справочник Источники финасирования (без досчета строки 700500) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_IST_317M03_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],CODE_STR as [CODE_STR],CODE_IST as [CODE_IST],STROKA as [STROKA],max(NAME) as [NAME],max(LONG_NAME) as [LONG_NAME],begin_date,end_date FROM R_SPR_IST_317_2011 WHERE CODE<>'70000001050000000000000' GROUP BY Code,CODE_STR,CODE_IST,STROKA,begin_date,end_date

	UNION

	select -1 as Link, isnull((select link from dbo.r_spr_ist_317_2011 where code = '70000001000000000000000'),0) as Link_Self,'70000001050000000000000' as CODE,'700' as CODE_STR,'00001050000000000000' as CODE_IST,'03390' as STROKA,'Изменение остатков средств на счетах по учету средств бюджета' as NAME,'Изменение остатков средств на счетах по учету средств бюджета' as LONG_NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_IST_317M03_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_317M03_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_IST_317M03_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011', 'Источники финасирования (без досчета строки 700500)', 213, (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_IST_317M03_2011', NAME = 'Источники финасирования (без досчета строки 700500)', ORDERS = '213', 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_IST_317M03_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_CODE_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_CODE_STR', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_CODE_STR', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_CODE_STR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_CODE_IST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_CODE_IST', 'Код', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_CODE_IST', NAME = 'Код', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_CODE_IST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_STROKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_STROKA', 'Номер строки', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_STROKA', NAME = 'Номер строки', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_STROKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_NAME', 'Наименование', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_NAME', NAME = 'Наименование', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011_LONG_NAM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_IST_317M03_2011_LONG_NAM', 'Наименование', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_IST_317M03_2011_LONG_NAM', NAME = 'Наименование', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_IST_317M03_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_IST_317M03_2011_LONG_NAM'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011', 'TITLE', 'Источники финасирования (без досчета строки 700500)'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_IST_317M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_IST_317M03_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011', 'SERVER_TABLE_NAME', 'R_SPR_IST_317M03_2011'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_IST_317M03_2011'''
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_STR', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_STR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_STR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_STR"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_STR', 'FIELD_DATA', 'CODE_STR'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_IST', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_IST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_IST', 'CONTROLSOURCE', 'm.cAlias + ".CODE_IST"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_CODE_IST', 'FIELD_DATA', 'CODE_IST'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_STROKA', 'TITLE', 'Номер строки'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_STROKA', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_STROKA', 'CONTROLSOURCE', 'm.cAlias + ".STROKA"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_STROKA', 'FIELD_DATA', 'STROKA'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_LONG_NAM', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_LONG_NAM', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_LONG_NAM', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'R_SPR_IST_317M03_2011_LONG_NAM', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317M03_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317M03_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_IST_317M03_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник видов контролей С КОДОМ R_SPR_KVK------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_KVK'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_KVK', 'Справочник видов контролей', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_KVK]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_KVK]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Справочник видов контролей (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_KVK]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_KVK' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_KVK] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_KVK')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_KVK'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_KVK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_KVK', 'Справочник видов контролей', 62, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_KVK', NAME = 'Справочник видов контролей', ORDERS = '62', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_KVK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_KVK_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_KVK_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_KVK_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_KVK_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_KVK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_KVK_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_KVK_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_KVK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_KVK_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_KVK_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_KVK_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_KVK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_KVK_Name'
GO
EXEC X_SET_PROP 'R_SPR_KVK', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_KVK'')'
GO
EXEC X_SET_PROP 'R_SPR_KVK', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_KVK'')'
GO
EXEC X_SET_PROP 'R_SPR_KVK', 'TITLE', 'Справочник видов контролей'
GO
EXEC X_SET_PROP 'R_SPR_KVK', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_KVK'''
GO
EXEC X_SET_PROP 'R_SPR_KVK_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_KVK_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_KVK', 'SERVER_TABLE_NAME', 'R_SPR_KVK'
GO
EXEC X_SET_PROP 'R_SPR_KVK_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_KVK_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_KVK_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_KVK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_KVK_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_KVK_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_KVK_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_KVK_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_KVK_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_KVK', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_KVK', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_KVK', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_KVK',0,'Справочник видов контролей','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='SYSTEM_SPR_2010' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_KVK',@link_self,'Справочник видов контролей','HEADER'
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'1',@link_self,'Предварительный','R_SPR_KVK',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'2',@link_self,'текущий','R_SPR_KVK',0,'',0,'','',NULL,NULL
GO
declare @link_self int 
set @link_self=0
exec RN_SAVE_REPORT_KBK null,'3',@link_self,'последующий','R_SPR_KVK',0,'',0,'','',NULL,NULL
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ОКАТО для форм 0503173, 0503373 С КОДОМ R_SPR_OKATO_173_373------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 ('OKATO', 1, 'substring(REPLACE(OKATO, '' '', ''''),1,8)', 'ОКАТО', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('DICTIONARY_DEPARTMENT', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_OKATO_173_373'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_OKATO_173_373', 'Справочник ОКАТО для форм 0503173, 0503373', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_OKATO_173_373]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_OKATO_173_373]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 26.12.2011

	справочник Справочник ОКАТО для форм 0503173, 0503373 (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_OKATO_173_373]

AS

SELECT max(LINK) as Link, 0 as Link_Self,substring(REPLACE(OKATO, ' ', ''),1,8) as [OKATO],max(Name) as [NAME] FROM DICTIONARY_DEPARTMENT GROUP BY substring(REPLACE(OKATO, ' ', ''),1,8)

	UNION

	select -1 as Link, 0 as Link_Self,'00000000' as OKATO,'' as NAME

	UNION

	select -2 as Link, 0 as Link_Self,'22222222' as OKATO,'' as NAME

GO


GRANT SELECT ON dbo.[R_SPR_OKATO_173_373] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_OKATO_173_373')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_OKATO_173_373'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_OKATO_173_373', 'Справочник ОКАТО для форм 0503173, 0503373', 278, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_OKATO_173_373', NAME = 'Справочник ОКАТО для форм 0503173, 0503373', ORDERS = '278', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_OKATO_173_373'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_OKATO_173_373_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_OKATO_173_373_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_OKATO_173_373_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373_OKATO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_OKATO_173_373_OKATO', 'ОКАТО', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_OKATO_173_373_OKATO', NAME = 'ОКАТО', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_OKATO_173_373_OKATO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_OKATO_173_373_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_OKATO_173_373_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_OKATO_173_373'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_OKATO_173_373_Name'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373', 'TITLE', 'Справочник ОКАТО для форм 0503173, 0503373'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_OKATO_173_373'')'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_OKATO_173_373'')'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373', 'SERVER_TABLE_NAME', 'R_SPR_OKATO_173_373'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_OKATO_173_373'''
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_OKATO', 'TITLE', 'ОКАТО'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_OKATO', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_OKATO', 'CONTROLSOURCE', 'm.cAlias + ".OKATO"'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_OKATO', 'FIELD_DATA', 'OKATO'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_OKATO_173_373_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_OKATO_173_373', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_OKATO_173_373', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_OKATO_173_373', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503169_VBD_2011 С КОДОМ R_SPR_plan_chet169VBD_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', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ПлСчет_Каз_2011'' AND (SUBSTRING(code, 2, 3) IN (''205'', ''206'', ''207'', ''208'', ''209'') OR (SUBSTRING(code, 2, 3) = ''210'' AND SUBSTRING(code, 5, 2) IN (''00'', ''01''))) AND LEFT(code, 1) in (''2'',''7'') AND RIGHT(code, 3)= ''000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_plan_chet169VBD_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_plan_chet169VBD_2011', 'План счетов для 0503169_VBD_2011', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_plan_chet169VBD_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_plan_chet169VBD_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 23.01.2012

	справочник План счетов для 0503169_VBD_2011 (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_plan_chet169VBD_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM REPORT_KBK WHERE Code_Form = 'ПлСчет_Каз_2011' AND (SUBSTRING(code, 2, 3) IN ('205', '206', '207', '208', '209') OR (SUBSTRING(code, 2, 3) = '210' AND SUBSTRING(code, 5, 2) IN ('00', '01'))) AND LEFT(code, 1) in ('2','7') AND RIGHT(code, 3)= '000' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_plan_chet169VBD_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_plan_chet169VBD_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_plan_chet169VBD_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VBD_2011', 'План счетов для 0503169_VBD_2011', 282, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VBD_2011', NAME = 'План счетов для 0503169_VBD_2011', ORDERS = '282', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VBD_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VBD_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VBD_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VBD_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011_COD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VBD_2011_COD', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VBD_2011_COD', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VBD_2011_COD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011_Nam')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VBD_2011_Nam', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VBD_2011_Nam', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VBD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VBD_2011_Nam'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011', 'TITLE', 'План счетов для 0503169_VBD_2011'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_plan_chet169VBD_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_plan_chet169VBD_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011', 'SERVER_TABLE_NAME', 'R_SPR_plan_chet169VBD_2011'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_plan_chet169VBD_2011'''
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_COD', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_COD', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_COD', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_COD', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_Nam', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_Nam', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_Nam', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VBD_2011_Nam', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VBD_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VBD_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VBD_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: План счетов для 0503169_VKD_2011 С КОДОМ R_SPR_plan_chet169VKD_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', 2, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ПлСчет_Каз_2011'' AND (SUBSTRING(code, 2, 3) IN (''302'', ''303'') OR (SUBSTRING(code, 2, 3) = ''304'' AND SUBSTRING(code, 5, 2) IN (''00'', ''02'', ''03'', ''04''))) AND LEFT(code, 1) in (''2'',''7'') AND RIGHT(code, 3)= ''000''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_plan_chet169VKD_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_plan_chet169VKD_2011', 'План счетов для 0503169_VKD_2011', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_plan_chet169VKD_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_plan_chet169VKD_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 23.01.2012

	справочник План счетов для 0503169_VKD_2011 (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_plan_chet169VKD_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME] FROM REPORT_KBK WHERE Code_Form = 'ПлСчет_Каз_2011' AND (SUBSTRING(code, 2, 3) IN ('302', '303') OR (SUBSTRING(code, 2, 3) = '304' AND SUBSTRING(code, 5, 2) IN ('00', '02', '03', '04'))) AND LEFT(code, 1) in ('2','7') AND RIGHT(code, 3)= '000' GROUP BY Code

GO


GRANT SELECT ON dbo.[R_SPR_plan_chet169VKD_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_plan_chet169VKD_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_plan_chet169VKD_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VKD_2011', 'План счетов для 0503169_VKD_2011', 283, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VKD_2011', NAME = 'План счетов для 0503169_VKD_2011', ORDERS = '283', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VKD_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VKD_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VKD_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VKD_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011_COD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VKD_2011_COD', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VKD_2011_COD', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VKD_2011_COD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011_Nam')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_plan_chet169VKD_2011_Nam', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_plan_chet169VKD_2011_Nam', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_plan_chet169VKD_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_plan_chet169VKD_2011_Nam'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011', 'TITLE', 'План счетов для 0503169_VKD_2011'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_plan_chet169VKD_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_plan_chet169VKD_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011', 'SERVER_TABLE_NAME', 'R_SPR_plan_chet169VKD_2011'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_plan_chet169VKD_2011'''
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_COD', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_COD', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_COD', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_COD', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_Nam', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_Nam', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_Nam', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_plan_chet169VKD_2011_Nam', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VKD_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VKD_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_plan_chet169VKD_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Автозаполняемый справочник для формы 0503317M_ФК - Расходы С КОДОМ R_SPR_RASH_317FK_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 ('Code_str', 2, 'Code_str', 'Код строки', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 3, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_RASH_317FK_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_RASH_317FK_2011', 'Автозаполняемый справочник для формы 0503317M_ФК - Расходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_RASH_317FK_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_RASH_317FK_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Автозаполняемый справочник для формы 0503317M_ФК - Расходы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_RASH_317FK_2011]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_RASH_317FK_2011' GROUP BY Code,Code_str, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_RASH_317FK_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_317FK_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_317FK_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317FK_2011', 'Автозаполняемый справочник для формы 0503317M_ФК - Расходы', 17, (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_317FK_2011', NAME = 'Автозаполняемый справочник для формы 0503317M_ФК - Расходы', ORDERS = '17', 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_317FK_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317FK_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317FK_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317FK_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317FK_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317FK_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317FK_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317FK_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317FK_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317FK_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317FK_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317FK_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317FK_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317FK_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011', 'SERVER_TABLE_NAME', 'R_SPR_RASH_317FK_2011'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_RASH_317FK_2011'''
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_RASH_317FK_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_RASH_317FK_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011', 'TITLE', 'Автозаполняемый справочник для формы 0503317M_ФК - Расходы'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317FK_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317FK_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317FK_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317FK_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник для формы 0503317M - Расходы С КОДОМ R_SPR_RASH_317_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 ('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 ('STROKA', 4, 'add_info', 'Строка', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_RASH_317_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_RASH_317_2011', 'Справочник для формы 0503317M - Расходы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_RASH_317_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_RASH_317_2011]


GO



/*******************************************************************************



	© Кейсистемс (Keysystems), 25.01.2012



	справочник Справочник для формы 0503317M - Расходы (сгенерировано Редактором справочников)



*******************************************************************************/



CREATE     VIEW dbo.[R_SPR_RASH_317_2011]



AS



SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [CODE_STR],add_info as [STROKA],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_317_2011' GROUP BY Code,Code_str,add_info, begin_date, end_date




GO


GRANT SELECT ON dbo.[R_SPR_RASH_317_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_317_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_RASH_317_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011', 'Справочник для формы 0503317M - Расходы', 110, (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_317_2011', NAME = 'Справочник для формы 0503317M - Расходы', ORDERS = '110', 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_317_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011_Code_str', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317_2011_Code_str', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317_2011_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011_STROKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_RASH_317_2011_STROKA', 'Строка', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_RASH_317_2011_STROKA', NAME = 'Строка', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_RASH_317_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_RASH_317_2011_STROKA'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011', 'TITLE', 'Справочник для формы 0503317M - Расходы'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_RASH_317_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_RASH_317_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011', 'SERVER_TABLE_NAME', 'R_SPR_RASH_317_2011'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_RASH_317_2011'''
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Code_str', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_STROKA', 'TITLE', 'Строка'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_STROKA', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_STROKA', 'CONTROLSOURCE', 'm.cAlias + ".STROKA"'
GO
EXEC X_SET_PROP 'R_SPR_RASH_317_2011_STROKA', 'FIELD_DATA', 'STROKA'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_RASH_317_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ЭКР С КОДОМ R_SPR_ST_738_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 ('Code_str', 2, 'Code_Str', 'КОД СТРОКИ', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 3, 'Name', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_ST_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_ST_738_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_ST_738_2011', 'Справочник ЭКР', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_ST_738_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_ST_738_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Справочник ЭКР (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_ST_738_2011]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_Str as [CODE_STR],max(Name) as [NAME],begin_date,end_date FROM R_SPR_ST_2011 GROUP BY Code,Code_Str,begin_date,end_date

	UNION

	select -1 as Link, 0 as Link_Self,'960' as CODE,'' as CODE_STR,'' as NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_ST_738_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ST_738_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_ST_738_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_738_2011', 'Справочник ЭКР', 193, (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_ST_738_2011', NAME = 'Справочник ЭКР', ORDERS = '193', 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_ST_738_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_738_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_738_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_738_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_738_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_738_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_738_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011_Code_str')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_738_2011_Code_str', 'КОД СТРОКИ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_738_2011_Code_str', NAME = 'КОД СТРОКИ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_738_2011_Code_str'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_ST_738_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_ST_738_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_ST_738_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_ST_738_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011', 'SERVER_TABLE_NAME', 'R_SPR_ST_738_2011'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_ST_738_2011'''
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_ST_738_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_ST_738_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011', 'TITLE', 'Справочник ЭКР'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Code_str', 'TITLE', 'КОД СТРОКИ'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Code_str', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Code_str', 'CONTROLSOURCE', 'm.cAlias + ".Code_str"'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Code_str', 'FIELD_DATA', 'Code_str'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_ST_738_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_738_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_738_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_ST_738_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник видов расходоы С КОДОМ R_SPR_VR_FED_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, 'isnull(Long_name, name)', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('REPORT_KBK', 'Code_Form = ''ВР_2011''')

declare @link int
select @link = link from report_spr where code = 'R_SPR_VR_FED_2011'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_VR_FED_2011', 'Справочник видов расходоы', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_VR_FED_2011]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_VR_FED_2011]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Справочник видов расходоы (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_VR_FED_2011]

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 = 'ВР_2011' GROUP BY Code,begin_date,end_date

GO


GRANT SELECT ON dbo.[R_SPR_VR_FED_2011] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_FED_2011')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_VR_FED_2011'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_FED_2011', 'Справочник видов расходоы', 75, (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_FED_2011', NAME = 'Справочник видов расходоы', ORDERS = '75', 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_FED_2011'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_FED_2011_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_FED_2011_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_FED_2011_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_FED_2011_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_FED_2011_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_FED_2011_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_VR_FED_2011_Name', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_VR_FED_2011_Name', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_VR_FED_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_VR_FED_2011_Name'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011', 'TITLE', 'Справочник видов расходоы'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_VR_FED_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_FED_2011'')'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011', 'SERVER_TABLE_NAME', 'R_SPR_VR_FED_2011'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_VR_FED_2011'''
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_VR_FED_2011_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_FED_2011', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_FED_2011', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_VR_FED_2011', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник ОГС для 86н С КОДОМ SPR_86n_OGS------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 ('INN', 2, 'Code_str', 'ИНН', '', 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 ('LONG_NAME', 4, 'Long_name', 'Организация (полное наименование)', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('REGION', 5, 'add_info', 'Код региона', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'SPR_86n_OGS'
exec dbo.RO_SPR_SAVE @link, 'SPR_86n_OGS', 'Справочник ОГС для 86н', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SPR_86n_OGS]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SPR_86n_OGS]


GO















/*******************************************************************************















	© Кейсистемс (Keysystems), 07.02.2012















	справочник Справочник ОГС для 86н (сгенерировано Редактором справочников)















*******************************************************************************/















CREATE     VIEW dbo.[SPR_86n_OGS]















AS















SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_str as [INN],add_info as [REGION],max(Name) as [NAME],max(Long_name) as [LONG_NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'SPR_86n_OGS' GROUP BY Code,Code_str,add_info, begin_date, end_date






















GO


GRANT SELECT ON dbo.[SPR_86n_OGS] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_OGS')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_OGS'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS', 'Справочник ОГС для 86н', 199, (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 = 'SPR_86n_OGS', NAME = 'Справочник ОГС для 86н', ORDERS = '199', 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 ='SPR_86n_OGS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_CODE', 'ОГС', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_CODE', NAME = 'ОГС', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_INN', 'ИНН', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_INN', NAME = 'ИНН', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_INN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_NAME', 'Организация (краткое наименование)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_NAME', NAME = 'Организация (краткое наименование)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_LONG_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_LONG_NAME', 'Организация (полное наименование)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_LONG_NAME', NAME = 'Организация (полное наименование)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_LONG_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_OGS_REGION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_OGS_REGION', 'Код региона', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_OGS_REGION', NAME = 'Код региона', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_OGS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_OGS_REGION'
GO
EXEC X_SET_PROP 'SPR_86n_OGS', 'SERVER_TABLE_NAME', 'SPR_86n_OGS'
GO
EXEC X_SET_PROP 'SPR_86n_OGS', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''SPR_86n_OGS'''
GO
EXEC X_SET_PROP 'SPR_86n_OGS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SPR_86n_OGS'')'
GO
EXEC X_SET_PROP 'SPR_86n_OGS', 'INIT_OBJECT_METHOD', 'x_spisok(''SPR_86n_OGS'')'
GO
EXEC X_SET_PROP 'SPR_86n_OGS', 'TITLE', 'Справочник ОГС для 86н'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_CODE', 'TITLE', 'ОГС'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_INN', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_INN', 'CONTROLSOURCE', 'm.cAlias + ".INN"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_INN', 'FIELD_DATA', 'INN'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_NAME', 'TITLE', 'Организация (краткое наименование)'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_LONG_NAME', 'TITLE', 'Организация (полное наименование)'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_LONG_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_LONG_NAME', 'CONTROLSOURCE', 'm.cAlias + ".LONG_NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_LONG_NAME', 'FIELD_DATA', 'LONG_NAME'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_REGION', 'TITLE', 'Код региона'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_REGION', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_REGION', 'CONTROLSOURCE', 'm.cAlias + ".REGION"'
GO
EXEC X_SET_PROP 'SPR_86n_OGS_REGION', 'FIELD_DATA', 'REGION'
GO
EXEC DBO.W_SPERM_WRITE 'SPR_86n_OGS', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_OGS', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_OGS', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS',0,'Справочник ОГС для 86н','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_OGS' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_OGS',@link_self,'Справочник ОГС для 86н','HEADER'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Показатели качетства услуг С КОДОМ SPR_86n_POK_KACH------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'SPR_86n_POK_KACH'
exec dbo.RO_SPR_SAVE @link, 'SPR_86n_POK_KACH', 'Показатели качетства услуг', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SPR_86n_POK_KACH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SPR_86n_POK_KACH]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 20.03.2012

	справочник Показатели качетства услуг (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[SPR_86n_POK_KACH]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'SPR_86n_POK_KACH' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[SPR_86n_POK_KACH] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_POK_KACH')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_POK_KACH'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_KACH', 'Показатели качетства услуг', 286, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_KACH', NAME = 'Показатели качетства услуг', ORDERS = '286', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_KACH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_KACH_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_KACH_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_KACH_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_KACH_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_KACH_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_KACH_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_KACH_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_KACH_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_KACH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_KACH_Name'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH', 'SERVER_TABLE_NAME', 'SPR_86n_POK_KACH'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''SPR_86n_POK_KACH'''
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SPR_86n_POK_KACH'')'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH', 'INIT_OBJECT_METHOD', 'x_spisok(''SPR_86n_POK_KACH'')'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH', 'TITLE', 'Показатели качетства услуг'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_KACH_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_KACH', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_KACH', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_KACH', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_KACH',0,'Показатели качества услуг','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_KACH',@link_self,'Показатели качества услуг','HEADER'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Показатели объема услуг С КОДОМ SPR_86n_POK_OB------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'SPR_86n_POK_OB'
exec dbo.RO_SPR_SAVE @link, 'SPR_86n_POK_OB', 'Показатели объема услуг', '#Cols_tmp', '#Data_tmp', 0


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SPR_86n_POK_OB]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SPR_86n_POK_OB]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 20.03.2012

	справочник Показатели объема услуг (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[SPR_86n_POK_OB]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'SPR_86n_POK_OB' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[SPR_86n_POK_OB] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_POK_OB')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_POK_OB'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_OB', 'Показатели объема услуг', 287, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_OB', NAME = 'Показатели объема услуг', ORDERS = '287', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_USER'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_OB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_OB_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_OB_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_OB_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_OB_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_OB_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_OB_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_POK_OB_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_POK_OB_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_POK_OB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_POK_OB_Name'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB', 'TITLE', 'Показатели объема услуг'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB', 'INIT_OBJECT_METHOD', 'x_spisok(''SPR_86n_POK_OB'')'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SPR_86n_POK_OB'')'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB', 'SERVER_TABLE_NAME', 'SPR_86n_POK_OB'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''SPR_86n_POK_OB'''
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'SPR_86n_POK_OB_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_OB', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_OB', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_POK_OB', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_OB',0,'Показатели объема услуг','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='86n_002' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'SPR_86n_POK_OB',@link_self,'Показатели объема услуг','HEADER'
GO

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник услуг С КОДОМ SPR_86n_Service------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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 ('PPO_NAME', 2, 'PPO_NAME', 'Наименование региона', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SERVICE_NAME', 3, 'SERVICE_NAME', 'Наименование услуги', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('SERVICE_NUMBER', 4, 'SERVICE_NUMBER', 'Номер по утвержденному перечню услуг', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CATEGORY', 5, 'CATEGORY', 'Категория потребителей', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('PROPERTY', 6, 'PROPERTY', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('NAME', 7, 'SERVICE_NAME', '', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('RN_VIEW_86n_SERVICE', '')

declare @link int
select @link = link from report_spr where code = 'SPR_86n_Service'
exec dbo.RO_SPR_SAVE @link, 'SPR_86n_Service', 'Справочник услуг', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SPR_86n_Service]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SPR_86n_Service]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 27.04.2012

	справочник Справочник услуг (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[SPR_86n_Service]

AS

SELECT max(LINK) as Link, 0 as Link_Self,Code as [CODE],SERVICE_NUMBER as [SERVICE_NUMBER],CATEGORY as [CATEGORY],PROPERTY as [PROPERTY],max(PPO_NAME) as [PPO_NAME],max(SERVICE_NAME) as [SERVICE_NAME],max(SERVICE_NAME) as [NAME],convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date FROM RN_VIEW_86n_SERVICE GROUP BY Code,SERVICE_NUMBER,CATEGORY,PROPERTY

GO


GRANT SELECT ON dbo.[SPR_86n_Service] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_Service')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_Service'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service', 'Справочник услуг', 257, (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 = 'SPR_86n_Service', NAME = 'Справочник услуг', ORDERS = '257', 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 ='SPR_86n_Service'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_CODE', 'Код услуги', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_CODE', NAME = 'Код услуги', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_PPO_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_PPO_NAME', 'Наименование региона', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_PPO_NAME', NAME = 'Наименование региона', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_PPO_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_SERVICE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_SERVICE_NAME', 'Наименование услуги', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_SERVICE_NAME', NAME = 'Наименование услуги', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_SERVICE_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_SERVICE_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_SERVICE_NUMBER', 'Номер по утвержденному перечню услуг', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_SERVICE_NUMBER', NAME = 'Номер по утвержденному перечню услуг', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_SERVICE_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_CATEGORY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_CATEGORY', 'Категория потребителей', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_CATEGORY', NAME = 'Категория потребителей', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_CATEGORY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_PROPERTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_PROPERTY', '', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_PROPERTY', NAME = '', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_PROPERTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_NAME', '', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_NAME', NAME = '', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_NAME'
GO
EXEC X_SET_PROP 'SPR_86n_Service', 'TITLE', 'Справочник услуг'
GO
EXEC X_SET_PROP 'SPR_86n_Service', 'INIT_OBJECT_METHOD', 'x_spisok(''SPR_86n_Service'')'
GO
EXEC X_SET_PROP 'SPR_86n_Service', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SPR_86n_Service'')'
GO
EXEC X_SET_PROP 'SPR_86n_Service', 'SERVER_TABLE_NAME', 'SPR_86n_Service'
GO
EXEC X_SET_PROP 'SPR_86n_Service', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''SPR_86n_Service'''
GO
EXEC X_SET_PROP 'SPR_86n_Service_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SPR_86n_Service_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CODE', 'TITLE', 'Код услуги'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PPO_NAME', 'TITLE', 'Наименование региона'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PPO_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PPO_NAME', 'CONTROLSOURCE', 'm.cAlias + ".PPO_NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PPO_NAME', 'FIELD_DATA', 'PPO_NAME'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NAME', 'TITLE', 'Наименование услуги'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NAME', 'CONTROLSOURCE', 'm.cAlias + ".SERVICE_NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NAME', 'FIELD_DATA', 'SERVICE_NAME'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NUMBER', 'TITLE', 'Номер по утвержденному перечню услуг'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NUMBER', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".SERVICE_NUMBER"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_SERVICE_NUMBER', 'FIELD_DATA', 'SERVICE_NUMBER'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CATEGORY', 'TITLE', 'Категория потребителей'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CATEGORY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CATEGORY', 'CONTROLSOURCE', 'm.cAlias + ".CATEGORY"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_CATEGORY', 'FIELD_DATA', 'CATEGORY'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PROPERTY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PROPERTY', 'CONTROLSOURCE', 'm.cAlias + ".PROPERTY"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_PROPERTY', 'FIELD_DATA', 'PROPERTY'
GO
EXEC X_SET_PROP 'SPR_86n_Service_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник услуг - НПА С КОДОМ SPR_86n_Service_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 ('E_TYPE', 2, 'E_TYPE', 'Вид', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('E_AUTHOR', 3, 'E_AUTHOR', 'Наименование органа, утвердившего НПА', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('E_DATE', 4, 'E_DATE', 'Дата', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('E_NUMBER', 5, 'E_NUMBER', 'Номер', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('E_NAME', 6, 'E_NAME', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('PROPERTY', 7, 'PROPERTY', '', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('NAME', 6, 'E_NAME', 'Наименование', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('RN_VIEW_86n_SERVICE', '')

declare @link int
select @link = link from report_spr where code = 'SPR_86n_Service_2'
exec dbo.RO_SPR_SAVE @link, 'SPR_86n_Service_2', 'Справочник услуг - НПА', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SPR_86n_Service_2]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SPR_86n_Service_2]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 27.04.2012

	справочник Справочник услуг - НПА (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[SPR_86n_Service_2]

AS

SELECT max(LINK) as Link, 0 as Link_Self,Code as [CODE],E_TYPE as [E_TYPE],E_AUTHOR as [E_AUTHOR],E_DATE as [E_DATE],E_NUMBER as [E_NUMBER],PROPERTY as [PROPERTY],max(E_NAME) as [E_NAME],max(E_NAME) as [NAME],convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date FROM RN_VIEW_86n_SERVICE GROUP BY Code,E_TYPE,E_AUTHOR,E_DATE,E_NUMBER,PROPERTY

GO


GRANT SELECT ON dbo.[SPR_86n_Service_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_Service_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SPR_86n_Service_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2', 'Справочник услуг - НПА', 258, (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 = 'SPR_86n_Service_2', NAME = 'Справочник услуг - НПА', ORDERS = '258', 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 ='SPR_86n_Service_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_CODE', 'Код услуги', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_CODE', NAME = 'Код услуги', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_E_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_E_TYPE', 'Вид', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_E_TYPE', NAME = 'Вид', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_E_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_E_AUTHOR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_E_AUTHOR', 'Наименование органа, утвердившего НПА', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_E_AUTHOR', NAME = 'Наименование органа, утвердившего НПА', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_E_AUTHOR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_E_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_E_DATE', 'Дата', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_E_DATE', NAME = 'Дата', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_E_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_E_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_E_NUMBER', 'Номер', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_E_NUMBER', NAME = 'Номер', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_E_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_E_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_E_NAME', 'Наименование', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_E_NAME', NAME = 'Наименование', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_E_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_NAME', 'Наименование', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_NAME', NAME = 'Наименование', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2_PROPERTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SPR_86n_Service_2_PROPERTY', '', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SPR_86n_Service_2_PROPERTY', NAME = '', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_86n_Service_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SPR_86n_Service_2_PROPERTY'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2', 'TITLE', 'Справочник услуг - НПА'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2', 'INIT_OBJECT_METHOD', 'x_spisok(''SPR_86n_Service_2'')'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SPR_86n_Service_2'')'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2', 'SERVER_TABLE_NAME', 'SPR_86n_Service_2'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''SPR_86n_Service_2'''
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_CODE', 'TITLE', 'Код услуги'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_TYPE', 'TITLE', 'Вид'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_TYPE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_TYPE', 'CONTROLSOURCE', 'm.cAlias + ".E_TYPE"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_TYPE', 'FIELD_DATA', 'E_TYPE'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_AUTHOR', 'TITLE', 'Наименование органа, утвердившего НПА'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_AUTHOR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_AUTHOR', 'CONTROLSOURCE', 'm.cAlias + ".E_AUTHOR"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_AUTHOR', 'FIELD_DATA', 'E_AUTHOR'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_DATE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_DATE', 'CONTROLSOURCE', 'm.cAlias + ".E_DATE"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_DATE', 'FIELD_DATA', 'E_DATE'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NUMBER', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NUMBER', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".E_NUMBER"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NUMBER', 'FIELD_DATA', 'E_NUMBER'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NAME', 'CONTROLSOURCE', 'm.cAlias + ".E_NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_E_NAME', 'FIELD_DATA', 'E_NAME'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_NAME', 'FIELD_DATA', 'NAME'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_PROPERTY', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_PROPERTY', 'CONTROLSOURCE', 'm.cAlias + ".PROPERTY"'
GO
EXEC X_SET_PROP 'SPR_86n_Service_2_PROPERTY', 'FIELD_DATA', 'PROPERTY'
GO
EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'SPR_86n_Service_2', 'Свод-КС - ограниченый доступ к организациям', 63,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(@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)	/* Перечисленная сумма НДФЛ за период */
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,	/* Используется при другом способе вызова отчета */
	@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'
						
						
						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'),
							'17183'
						
						
						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'),
							'17059'
						
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'),
							''
						
						
						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'),
							'2011'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_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'),
							'2009'
						
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'),
							'Текущий месяц'
						
						
						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'
						
						
						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'),
					'Определить перечисленную сумму по проводкам',7, 
					(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'),
							'Выкл.'
						
						
						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'),
					'Перечисленная сумма НДФЛ за период',8, 
					(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'),
							'711.4'
						
						
						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'),
							'711.4'
						
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


GO
--- ОТЧЕТ: АКТ СВЕРКИ РАСЧЕТОВ С ПОСТАВЩИКАМИ И ПОДРЯДЧИКАМИ (SQL_REP_AKT_RESIVE_DEP1) --- 
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_SQL'), 'Акт сверки расчетов с поставщиками и подрядчиками', 201, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REPORTS_CATALOG_DTKT'), 'SQL_REP_AKT_RESIVE_DEP1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_NASTRS'), 'Группа настроек', 5, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_FILTER'), 'Стандартный фильтр для запроса', NULL, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1'), 'SQL_REP_AKT_RESIVE_DEP1_FIL1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PB'), 'Начало периода', 6, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PE'), 'Конец периода', 7, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_LSEL_SPR'), 'Поставщик/подрядчик', 8, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Отчет в разрезе ЭКР', 9, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS14', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS15')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Сводный отчет (ЦБ)', 10, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS15', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS16')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Не учитывать проводки по зачету аванса', 11, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS16', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS17')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Отчет в разрезе КБК', 12, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_NAS1'), 'SQL_REP_AKT_RESIVE_DEP1_NAS17', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_ACCT20'), 'Отбор субсчетов  "Расчеты с организациями"', 1, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL1'), 'SQL_REP_AKT_RESIVE_DEP1_FIL11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_DEPART'), 'Отбор учреждений', 2, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL1'), 'SQL_REP_AKT_RESIVE_DEP1_FIL12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_KBK'), 'Отбор КБК', 3, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL1'), 'SQL_REP_AKT_RESIVE_DEP1_FIL13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_EKR'), 'Отбор ЭКР', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP1_FIL1'), 'SQL_REP_AKT_RESIVE_DEP1_FIL14', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_DATETIME', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_FREEZEPANES', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_PAGES', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_BEFORE', 'EXEC	BK_REPORT_AKT_RESIVE_DEP1
	@dDateB1,
	@dDateE1,
	@cVal1, @nOtborLink1,
	@cVal2, @nOtborLink2,
	@cVal3, @nOtborLink3,	/* Отбор КБК */
	@cVal4, @nOtborLink4,	/* Отбор ЭКР */
	@nSel_Spr1	/* Поставщик/подрядчик */,
	@nCheck1	/* Отчет в разрезе ЭКР */,
	@nCheck4 	/* Отчет в разрезе КБК */,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	''206, 302, 207, 301'',
	@nCheck3	/* Не учитывать проводки по зачету аванса */

', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_DATETIME', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_DISTINCT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_FREEZEPANES', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_PAGES', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_PROCEDURE', '#REP_AKT_RESIVE_DEP1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_REPORT', 'IIF(.T.,"AKT_RESIVE_DEP1.XLT","")', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_SQL', 'CREATE PROCEDURE #REP_AKT_RESIVE_DEP1
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@nSel_Spr1 int	/* Поставщик/подрядчик */,
	@nCheck1 int	/* Отчет в разрезе ЭКР */,
	@nCheck2 int	/* Сводный отчет (ЦБ) */,
	@nCheck3 int	/* Не учитывать проводки по зачету аванса */,
	@nCheck4 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_ACCT20''))
	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_DEPART''))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal3 char(1), @nOtborLink3 int	/* Отбор КБК */
	SELECT @nOtborLink3 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_KBK''))
	SELECT @cVal3 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink3 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal4 char(1), @nOtborLink4 int	/* Отбор ЭКР */
	SELECT @nOtborLink4 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_EKR''))
	SELECT @cVal4 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink4 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

EXEC	BK_REPORT_AKT_RESIVE_DEP1
	@dDateB1,
	@dDateE1,
	@cVal1, @nOtborLink1,
	@cVal2, @nOtborLink2,
	@cVal3, @nOtborLink3,	/* Отбор КБК */
	@cVal4, @nOtborLink4,	/* Отбор ЭКР */
	@nSel_Spr1	/* Поставщик/подрядчик */,
	@nCheck1	/* Отчет в разрезе ЭКР */,
	@nCheck4 	/* Отчет в разрезе КБК */,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	''206, 302, 207, 301'',
	@nCheck3	/* Не учитывать проводки по зачету аванса */



END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'EOD_PROTOCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'QUERY_ADD_MODULE', 'KirRepCommon.bas', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1', 'REPORT_EXTERNAL_GENERATOR', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS1', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL1', 'QUERY_NASTR_NOTE', 'Стандартный фильтр для отчета', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL1', 'QUERY_VARIANT_ID', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_CAPTION', 'Начало периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_SOURCE', 'Текущяя дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_SQLPARAM', '@dDateB1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_VALUE', 'Начало расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS11', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_CAPTION', 'Конец периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_SOURCE', 'Текущяя дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_SQLPARAM', '@dDateE1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_VALUE', 'Конец расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS12', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_CAPTION', 'Поставщик/подрядчик', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_CONTROL', 'LSel_Spr', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_SOURCE', 'DICTIONARY_DEPARTMENT', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_SQLPARAM', '@nSel_Spr1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS13', 'SQUERY_NASTR_OPTIONAL', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_CAPTION', 'Отчет в разрезе ЭКР', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_SQLPARAM', '@nCheck1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS14', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_CAPTION', 'Сводный отчет (ЦБ)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_NUMPARAM', '2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_SQLPARAM', '@nCheck2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS15', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_CAPTION', 'Не учитывать проводки по зачету аванса', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_NUMPARAM', '3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_SQLPARAM', '@nCheck3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS16', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_CAPTION', 'Отчет в разрезе КБК', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_NUMPARAM', '4', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_SQLPARAM', '@nCheck4', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_NAS17', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_OTBOR_DICTIONARY_CODE', 'BK_SUBACCOUNTS302_01', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL11', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_OTBOR_DICTIONARY_CODE', 'DICTIONARY_DEPARTMENT', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL12', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_OTBOR_DICTIONARY_CODE', 'BI_DICTION_KBK', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL13', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_OTBOR_DICTIONARY_CODE', 'DICTIONARY_ITEM', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP1_FIL14', 'QUERY_OTBOR_VALUE', '', 0
GO




GO
--- ОТЧЕТ: АКТ СВЕРКИ РАСЧЕТОВ С ДЕБИТОРАМИ ПО ДОХОДАМ (SQL_REP_AKT_RESIVE_DEP2) --- 
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_SQL'), 'Акт сверки расчетов с дебиторами по доходам', NULL, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REPORTS_CATALOG_DTKT'), 'SQL_REP_AKT_RESIVE_DEP2', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_FILTER'), 'Стандартный фильтр для запроса', 0, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2'), 'SQL_REP_AKT_RESIVE_DEP2_FIL1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_NASTRS'), 'Группа настроек', 5, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2'), 'SQL_REP_AKT_RESIVE_DEP2_NAS1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_ACCT25'), 'Отбор субсчетов  "Расчеты с дебиторами по доходам"', 1, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL1'), 'SQL_REP_AKT_RESIVE_DEP2_FIL11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_DEPART'), 'Отбор учреждений', 2, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL1'), 'SQL_REP_AKT_RESIVE_DEP2_FIL12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_KBK'), 'Отбор КБК', 3, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL1'), 'SQL_REP_AKT_RESIVE_DEP2_FIL13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_SQL_EKR'), 'Отбор ЭКР', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_FIL1'), 'SQL_REP_AKT_RESIVE_DEP2_FIL14', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PB'), 'Начало периода', 6, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1'), 'SQL_REP_AKT_RESIVE_DEP2_NAS11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PE'), 'Конец периода', 7, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1'), 'SQL_REP_AKT_RESIVE_DEP2_NAS12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_LSEL_SPR'), 'Организация', 8, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1'), 'SQL_REP_AKT_RESIVE_DEP2_NAS13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Отчет в разрезе ЭКР', 9, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1'), 'SQL_REP_AKT_RESIVE_DEP2_NAS14', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS15')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Сводный отчет (ЦБ)', 10, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_AKT_RESIVE_DEP2_NAS1'), 'SQL_REP_AKT_RESIVE_DEP2_NAS15', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_BEFORE', 'EXEC	BK_REPORT_AKT_RESIVE_DEP1
	@dDateB1,
	@dDateE1,
	@cVal1, @nOtborLink1,
	@cVal2, @nOtborLink2,
	@cVal3, @nOtborLink3,	/* Отбор КБК */
	@cVal4, @nOtborLink4, /* Отбор ЭКР */
	@nSel_Spr1	/* Поставщик/подрядчик */,
	@nCheck1	/* Отчет в разрезе ЭКР */,
	0,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	''205'',
	0
', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_DISTINCT', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_PROCEDURE', '#REP_AKT_RESIVE_DEP2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_REPORT', 'IIF(.T.,"AKT_RESIVE_DEP1.XLT","")', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_SQL', 'CREATE PROCEDURE #REP_AKT_RESIVE_DEP2
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@nSel_Spr1 int	/* Организация */,
	@nCheck1 int	/* Отчет в разрезе ЭКР */,
	@nCheck2 int	/* Сводный отчет (ЦБ) */,
	@nFilterLink int	/* Фильтр */
AS
BEGIN
	DECLARE @cVal1 char(1), @nOtborLink1 int	/* Отбор субсчетов  "Расчеты с дебиторами по доходам" */
	SELECT @nOtborLink1 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_ACCT25''))
	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_DEPART''))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal3 char(1), @nOtborLink3 int	/* Отбор КБК */
	SELECT @nOtborLink3 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_KBK''))
	SELECT @cVal3 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink3 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal4 char(1), @nOtborLink4 int	/* Отбор ЭКР */
	SELECT @nOtborLink4 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_EKR''))
	SELECT @cVal4 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink4 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

EXEC	BK_REPORT_AKT_RESIVE_DEP1
	@dDateB1,
	@dDateE1,
	@cVal1, @nOtborLink1,
	@cVal2, @nOtborLink2,
	@cVal3, @nOtborLink3,	/* Отбор КБК */
	@cVal4, @nOtborLink4, /* Отбор ЭКР */
	@nSel_Spr1	/* Поставщик/подрядчик */,
	@nCheck1	/* Отчет в разрезе ЭКР */,
	0,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	''205'',
	0


END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'EOD_PROTOCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ADD_MODULE', 'KirRepCommon.bas', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_DATE_TYPE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'SQUERY_NO_SHOW', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'QUERY_ALTERNATIVE_PRINT_METHOD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2', 'REPORT_EXTERNAL_GENERATOR', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL1', 'QUERY_NASTR_NOTE', 'Стандартный фильтр для отчета', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL1', 'QUERY_VARIANT_ID', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS1', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_OTBOR_DICTIONARY_CODE', 'DICT_SUBACCOUNTS25', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL11', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_OTBOR_DICTIONARY_CODE', 'DICTIONARY_DEPARTMENT', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL12', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_OTBOR_DICTIONARY_CODE', 'BI_DICTION_KBK', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL13', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_OTBOR_DICTIONARY_CODE', 'DICTIONARY_ITEM', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_FIL14', 'QUERY_OTBOR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_CAPTION', 'Начало периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_SQLPARAM', '@dDateB1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_VALUE', 'Начало расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS11', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_CAPTION', 'Конец периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_SQLPARAM', '@dDateE1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_VALUE', 'Конец расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS12', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_CAPTION', 'Организация', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_CONTROL', 'LSel_Spr', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_SOURCE', 'DICTIONARY_DEPARTMENT', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_SQLPARAM', '@nSel_Spr1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS13', 'SQUERY_NASTR_OPTIONAL', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_CAPTION', 'Отчет в разрезе ЭКР', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_SQLPARAM', '@nCheck1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS14', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_CAPTION', 'Сводный отчет (ЦБ)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_NUMPARAM', '2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_SQLPARAM', '@nCheck2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_AKT_RESIVE_DEP2_NAS15', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO




GO
--- ОТЧЕТ: ЖУРНАЛ РЕГИСТРАЦИИ СЧЕТОВ-ФАКТУР (SQL_REP_JURN_INVOICE) --- 
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_SQL'), 'Журнал регистрации счетов-фактур', NULL, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REPORT_COMMON_CATALOG'), 'SQL_REP_JURN_INVOICE', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_NASTRS'), 'Группа настроек', 1, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE'), 'SQL_REP_JURN_INVOICE_NAS1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PB'), 'Начало расч. периода', 2, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS1'), 'SQL_REP_JURN_INVOICE_NAS11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_PE'), 'Конец расч. периода', 3, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS1'), 'SQL_REP_JURN_INVOICE_NAS12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_OPTIONGROUP'), 'Журнал регистрации:', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS1'), 'SQL_REP_JURN_INVOICE_NAS13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Сводый отчет', 5, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_JURN_INVOICE_NAS1'), 'SQL_REP_JURN_INVOICE_NAS14', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_BEFORE', 'EXEC	dbo.BK_REPORT_JURN_INVOICE
	@dDateB1	/* Начало расч. периода */,
	@dDateE1	/* Конец расч. периода */,
	@nOption1	/* Журнал регистрации */,
	@nCheck1	/* Сводый отчет */
', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_DISTINCT', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_PROCEDURE', '#REP_JURN_INVOICE', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_REPORT', 'IIF(@nOption1=1,"JURN_INVOICE_RECEIVED.XLT",IIF(@nOption1=2,"JURN_INVOICE_ISSUED.XLT",IIF(@nOption1=3,"JURN_INVOICE.XLT","")))', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_SQL', 'CREATE PROCEDURE #REP_JURN_INVOICE
	@dDateB1 datetime	/* Начало расч. периода */,
	@dDateE1 datetime	/* Конец расч. периода */,
	@nOption1 int	/* Журнал регистрации: */,
	@nCheck1 int	/* Сводый отчет */
AS
BEGIN

EXEC	dbo.BK_REPORT_JURN_INVOICE
	@dDateB1	/* Начало расч. периода */,
	@dDateE1	/* Конец расч. периода */,
	@nOption1	/* Журнал регистрации */,
	@nCheck1	/* Сводый отчет */


END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'EOD_PROTOCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ADD_MODULE', 'KirRepCommon.bas', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_DATE_TYPE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'SQUERY_NO_SHOW', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'QUERY_ALTERNATIVE_PRINT_METHOD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE', 'REPORT_EXTERNAL_GENERATOR', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS1', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_CAPTION', 'Начало расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_SQLPARAM', '@dDateB1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_VALUE', 'Начало расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS11', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_CAPTION', 'Конец расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_SQLPARAM', '@dDateE1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_VALUE', 'Конец расч. периода', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS12', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'SQUERY_NASTR_NON_VISIBLE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_CAPTION', 'Журнал регистрации:', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_CONTROL', 'OPTIONGROUP', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_SOURCE', 'Полученных счет-фактур,Выставленных счет-фактур,Общий', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_SQLPARAM', '@nOption1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_VALUE', 'Общий', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS13', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_CAPTION', 'Сводый отчет', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_SQLPARAM', '@nCheck1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_JURN_INVOICE_NAS14', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO




GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (апр  5 2012 11:42:02:953AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 4fss (Расчетная ведомость по средствам ФСС РФ)
-- Дата ввода : 20120101
-- Дата окончания действия :
-- Версия : 2012-04-05 11:42:02.953
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : нет
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '4fss' AND [START_DATE] = '20120101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2012-04-05 11:42:02.953',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '4fss',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '4fss'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20120101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчетная ведомость по средствам ФСС РФ',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_4FSS_090212()','4FSS_090212.bas','','KirRepMakerMultiSheet.XLS','4FSS_090212.xlt','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_ATR_NOM_OBR',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р0. Титул', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала года',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р0. Титул', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма',@iLINK_TABLE,0,0,3,2,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Номер платеж. поручения',@iLINK_TABLE,0,1,4,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Число случаев / количество получателей',@iLINK_TABLE,0,0,2,1,0,1,NULL,NULL,NULL,'999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Количество дней, выплат, пособий',@iLINK_TABLE,0,0,3,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Расходы. Всего',@iLINK_TABLE,0,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Расходы. в т.ч. выплаты за счет средств федерального бюджета',@iLINK_TABLE,0,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,1,1,1,0,250,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строк',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия имя отчество',@iLINK_TABLE,1,1,2,0,100,1,'KU_PERSON_FIO','COL2','CODE',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата справки',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.SA_4FSS_28022011_PREPARE_INV @Lsf',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам  9-ти месяцев года, предшествующего текущему расчетному пери',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего число получателей',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Всего количество дней, выплат, пособий',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего расходы (сумма)',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. Чернобыльская АЭС число получателей',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. Чернобыльская АЭС количество дней, выплат, пособий',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. Чернобыльская АЭС расходы (сумма)',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'В т.ч. ПО "Маяк" число получателей',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'В т.ч. ПО "Маяк" количество дней, выплат, пособий',@iLINK_TABLE,1,0,10,10,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'В т.ч. ПО "Маяк" расходы (сумма)',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'В т.ч. Семипалатинский полигон число получателей',@iLINK_TABLE,1,0,12,12,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'В т.ч. Семипалатинский полигон количество дней, выплат, пособий',@iLINK_TABLE,1,0,13,13,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'В т.ч. Семипалатинский полигон расходы (сумма)',@iLINK_TABLE,1,0,14,14,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'В т.ч. подразделения особого риска число получателей',@iLINK_TABLE,1,0,15,15,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'В т.ч. подразделения особого риска количество дней, выплат, пособий',@iLINK_TABLE,1,0,16,16,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'В т.ч. подразделения особого риска расходы (сумма)',@iLINK_TABLE,1,0,17,17,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'В т.ч. доп.выпл. по № 255-ФЗ число получателей',@iLINK_TABLE,1,0,18,18,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'В т.ч. доп.выпл. по № 255-ФЗ количество дней, выплат, пособий',@iLINK_TABLE,1,0,19,19,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'В т.ч. доп.выпл. по № 255-ФЗ расходы (сумма)',@iLINK_TABLE,1,0,20,20,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,11, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Выплаты, на которые начисляются стр. взносы, всего',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'в.т.ч. выплаты инвалидам, на которые начисляются стр. взносы',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Выплаты , на которые не начисляются стр. взносы',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Размер страхового тарифа',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Скидка к страховому тарифу',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Дата установления надбавки к стр. тарифу',@iLINK_TABLE,1,1,8,9,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'% надбавки к стр. тарифу',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Размер тарифа с учётом скидки (надбавки)',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма (руб.коп.)',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Дата, номер платеж. поручения',@iLINK_TABLE,1,1,4,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,13, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество дней',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сумма (руб., коп.)',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,14, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Численность пострадавших человек',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,15, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.10. Свед. по аттест. раб. мест и медосмотр', @iLINK_FORM,16
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Общее количество рабочих мест страхователя',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Кол. раб. мест, на которых проведена аттест. раб. мест - на начало год',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Кол. раб. мест, по результ. аттестации раб. мест  - 1 класс',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Кол. раб. мест, по результ. аттестации раб. мест  - 2 класс',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Общ. кол. раб., на вред. и (или) опас. производст. подлежащих медосмот',@iLINK_TABLE,1,0,8,8,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Кол. раб., на вред. и (или) опас. производ. прошедших медосмотр на нач',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.10. Свед. по аттест. раб. мест и медосмотр', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,3,1)
INSERT #R VALUES (3,1,4,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,2,1)
INSERT #R VALUES (3,2,34,1)
INSERT #R VALUES (4,2,4,1)
INSERT #R VALUES (5,2,33,1)
INSERT #R VALUES (6,2,6,1)
INSERT #R VALUES (7,2,7,1)
INSERT #R VALUES (8,2,8,1)
INSERT #R VALUES (9,2,34,1)
INSERT #R VALUES (10,2,10,1)
INSERT #R VALUES (11,2,33,1)
INSERT #R VALUES (12,2,12,1)
INSERT #R VALUES (13,2,13,1)
INSERT #R VALUES (14,2,14,1)
INSERT #R VALUES (15,2,34,1)
INSERT #R VALUES (16,2,16,1)
INSERT #R VALUES (17,2,33,1)
INSERT #R VALUES (18,2,18,1)
INSERT #R VALUES (19,2,19,1)
INSERT #R VALUES (20,2,20,1)
INSERT #R VALUES (21,2,34,1)
INSERT #R VALUES (22,2,22,1)
INSERT #R VALUES (23,2,33,1)
INSERT #R VALUES (24,2,24,1)
INSERT #R VALUES (25,2,25,1)
INSERT #R VALUES (26,2,26,1)
INSERT #R VALUES (27,2,34,1)
INSERT #R VALUES (28,2,28,1)
INSERT #R VALUES (29,2,33,1)
INSERT #R VALUES (30,2,30,1)
INSERT #R VALUES (31,2,31,1)
INSERT #R VALUES (32,2,32,1)
INSERT #R VALUES (33,2,55,1)
INSERT #R VALUES (34,2,34,1)
INSERT #R VALUES (35,2,35,1)
INSERT #R VALUES (36,2,36,1)
INSERT #R VALUES (37,2,37,1)
INSERT #R VALUES (38,2,38,1)
INSERT #R VALUES (39,2,39,1)
INSERT #R VALUES (40,2,53,1)
INSERT #R VALUES (41,2,41,1)
INSERT #R VALUES (42,2,52,1)
INSERT #R VALUES (43,2,43,1)
INSERT #R VALUES (44,2,44,1)
INSERT #R VALUES (45,2,45,1)
INSERT #R VALUES (46,2,53,1)
INSERT #R VALUES (47,2,47,1)
INSERT #R VALUES (48,2,52,1)
INSERT #R VALUES (49,2,49,1)
INSERT #R VALUES (50,2,50,1)
INSERT #R VALUES (1,3,2,1)
INSERT #R VALUES (2,3,1,1)
INSERT #R VALUES (3,3,2,1)
INSERT #R VALUES (4,3,1,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,2,1)
INSERT #R VALUES (7,3,1,1)
INSERT #R VALUES (8,3,2,1)
INSERT #R VALUES (9,3,1,1)
INSERT #R VALUES (10,3,1,1)
INSERT #R VALUES (11,3,1,1)
INSERT #R VALUES (12,3,4,1)
INSERT #R VALUES (3,4,3,1)
INSERT #R VALUES (4,4,4,1)
INSERT #R VALUES (5,4,5,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (6,4,6,1)
INSERT #R VALUES (7,4,7,1)
INSERT #R VALUES (2,4,2,1)
INSERT #R VALUES (2,6,2,1)
INSERT #R VALUES (3,6,4,1)
INSERT #R VALUES (1,6,1,1)
INSERT #R VALUES (1,7,1,1)
INSERT #R VALUES (2,7,2,1)
INSERT #R VALUES (3,7,4,1)
INSERT #R VALUES (4,7,5,1)
INSERT #R VALUES (5,7,6,1)
INSERT #R VALUES (6,7,7,1)
INSERT #R VALUES (1,8,1,1)
INSERT #R VALUES (2,8,3,1)
INSERT #R VALUES (3,8,4,1)
INSERT #R VALUES (4,8,5,1)
INSERT #R VALUES (5,8,6,1)
INSERT #R VALUES (1,9,1,1)
INSERT #R VALUES (2,9,2,1)
INSERT #R VALUES (3,9,3,1)
INSERT #R VALUES (1,10,1,1)
INSERT #R VALUES (2,10,2,1)
INSERT #R VALUES (3,10,3,1)
INSERT #R VALUES (4,10,4,1)
INSERT #R VALUES (5,10,5,1)
INSERT #R VALUES (1,11,1,1)
INSERT #R VALUES (2,11,3,1)
INSERT #R VALUES (3,11,4,1)
INSERT #R VALUES (4,11,5,1)
INSERT #R VALUES (5,11,6,1)
INSERT #R VALUES (6,11,7,1)
INSERT #R VALUES (7,11,8,1)
INSERT #R VALUES (1,12,1,1)
INSERT #R VALUES (2,12,3,1)
INSERT #R VALUES (3,12,4,1)
INSERT #R VALUES (4,12,5,1)
INSERT #R VALUES (5,12,6,1)
INSERT #R VALUES (1,13,1,1)
INSERT #R VALUES (2,13,3,1)
INSERT #R VALUES (3,13,4,1)
INSERT #R VALUES (4,13,5,1)
INSERT #R VALUES (5,13,6,1)
INSERT #R VALUES (6,13,7,1)
INSERT #R VALUES (7,13,8,1)
INSERT #R VALUES (8,13,9,1)
INSERT #R VALUES (9,13,10,1)
INSERT #R VALUES (10,13,11,1)
INSERT #R VALUES (11,13,12,1)
INSERT #R VALUES (12,13,13,1)
INSERT #R VALUES (13,13,14,1)
INSERT #R VALUES (14,13,15,1)
INSERT #R VALUES (15,13,16,1)
INSERT #R VALUES (16,13,17,1)
INSERT #R VALUES (17,13,18,1)
INSERT #R VALUES (18,13,19,1)
INSERT #R VALUES (19,13,20,1)
INSERT #R VALUES (20,13,21,1)
INSERT #R VALUES (21,13,22,1)
INSERT #R VALUES (22,13,23,1)
INSERT #R VALUES (23,13,24,1)
INSERT #R VALUES (24,13,25,1)
INSERT #R VALUES (25,13,26,1)
INSERT #R VALUES (26,13,27,1)
INSERT #R VALUES (27,13,28,1)
INSERT #R VALUES (28,13,29,1)
INSERT #R VALUES (29,13,30,1)
INSERT #R VALUES (30,13,31,1)
INSERT #R VALUES (31,13,32,1)
INSERT #R VALUES (1,14,1,1)
INSERT #R VALUES (2,14,3,1)
INSERT #R VALUES (3,14,4,1)
INSERT #R VALUES (4,14,5,1)
INSERT #R VALUES (5,14,6,1)
INSERT #R VALUES (6,14,7,1)
INSERT #R VALUES (7,14,8,1)
INSERT #R VALUES (8,14,9,1)
INSERT #R VALUES (9,14,10,1)
INSERT #R VALUES (10,14,11,1)
INSERT #R VALUES (1,15,1,1)
INSERT #R VALUES (2,15,3,1)
INSERT #R VALUES (3,15,4,1)
INSERT #R VALUES (4,15,5,1)
INSERT #R VALUES (5,15,6,1)
INSERT #R VALUES (1,16,1,1)
INSERT #R VALUES (2,16,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 155
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Численность работников                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,2,1,'из них: женщин                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,1,'работающих инвалидов                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,4,1,'работающих, занятых на работах с вредными и (или) опасными производственными факторами                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,1,3,'4ФСС_09022012_УСТАНОВКА() + 4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,2,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,3,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,4,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (2,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,3,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,4,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,6,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,7,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'Начислено страховых взносов по актам проверок                                                                                                                                                                                                             ')
INSERT #F VALUES (2,9,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,10,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,11,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,14,1,'Начислено страховых взносов страхователем за прошлые годы                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'Не принято к зачету расходов территориальным органом Фонда                                                                                                                                                                                                ')
INSERT #F VALUES (2,16,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,17,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,18,1,'1 месяц')
INSERT #F VALUES (2,19,1,'2 месяц')
INSERT #F VALUES (2,20,1,'3 месяц')
INSERT #F VALUES (2,21,1,'Получено от территориального органа Фонда на банковский счет в возмещение произведенных расходов                                                                                                                                                          ')
INSERT #F VALUES (2,22,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,23,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,24,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,26,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,27,1,'Возврат сумм излишне перечисленных страховых взносов                                                                                                                                                                                                      ')
INSERT #F VALUES (2,28,1,'Всего (стр. 1 - 7)                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,29,1,'Задолженность за территориальным органом Фонда на конец отчетного (расчетного) периода                                                                                                                                                                    ')
INSERT #F VALUES (2,30,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,31,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,32,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (2,33,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,34,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,35,1,'Расходы на цели обязательного социального страхования                                                                                                                                                                                                     ')
INSERT #F VALUES (2,36,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,37,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,38,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,39,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,40,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,41,1,'Перечислены страховые взносы                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,42,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,43,1,'За отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,44,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,45,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,46,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,47,1,'Списано                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,48,1,'Всего (стр. 12, 15, 16, 17)                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,49,1,'Задолженность за страхователем на конец отчетного (расчетного) периода                                                                                                                                                                                    ')
INSERT #F VALUES (2,50,1,'в том числе недоимка                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,9,2,'3_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'3_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'3_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'3_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'3_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,15,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,16,2,'5_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,17,2,'5_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,18,2,'5_3')
INSERT #F VALUES (2,19,2,'5_4')
INSERT #F VALUES (2,20,2,'5_5')
INSERT #F VALUES (2,21,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,22,2,'6_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,23,2,'6_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'6_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'6_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'6_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,27,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,28,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,29,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,30,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,31,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,32,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,33,2,'13                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,34,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,35,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,36,2,'15_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,37,2,'15_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,38,2,'15_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,39,2,'15_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,40,2,'15_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,41,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,42,2,'16_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,43,2,'16_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,44,2,'16_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,45,2,'16_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,46,2,'16_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,47,2,'17                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,48,2,'18                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,49,2,'19                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,50,2,'20                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,1,3,'КТСН("_.303.02","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,3,3,'4ФСС_РАЗДЕЛ1(''0121'',3)')
INSERT #F VALUES (2,5,3,'4ФСС_РАЗДЕЛ1(''0123'',3)')
INSERT #F VALUES (2,6,3,'4ФСС_РАЗДЕЛ1(''0124'',3)')
INSERT #F VALUES (2,7,3,'4ФСС_РАЗДЕЛ1(''0125'',3)')
INSERT #F VALUES (2,18,3,'')
INSERT #F VALUES (2,19,3,'')
INSERT #F VALUES (2,20,3,'')
INSERT #F VALUES (2,22,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,24,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,25,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,26,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,29,3,'ДТСК("_.303.02")')
INSERT #F VALUES (2,32,3,'ДТСН("_.303.02","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,36,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,38,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,39,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,40,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,42,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,44,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,45,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,46,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,26,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,27,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,32,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,33,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,34,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,35,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,36,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,37,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,38,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,39,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,40,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,41,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,42,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,43,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,44,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,45,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,46,4,'НОМ_ПЛАТЕЖ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,47,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,48,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,49,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,50,4,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,1,'По временной нетрудоспособности                                                                                                                                                                                                                               ')
INSERT #F VALUES (3,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,3,1,'По беременности и родам                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,5,1,'Единовременное пособие женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'Единовременное пособие при рождении ребенка                                                                                                                                                                                                               ')
INSERT #F VALUES (3,7,1,'Ежемесячное пособие по уходу за ребенком                                                                                                                                                                                                                  ')
INSERT #F VALUES (3,8,1,'          в том числе: по уходу за первым ребенком                                                                                                                                                                                                        ')
INSERT #F VALUES (3,9,1,'          по уходу за вторым и последующими детьми                                                                                                                                                                                                        ')
INSERT #F VALUES (3,10,1,'Оплата 4-х дополнительных выходных дней для ухода за детьми-инвалидами                                                                                                                                                                                    ')
INSERT #F VALUES (3,11,1,'Социальное пособие на погребение                                                                                                                                                                                                                          ')
INSERT #F VALUES (3,12,1,'ИТОГО ( сумма строк 1+ 3+ 5+ 6+ 7+ 10+11)                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,8,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,11,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,12,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,1,3,'4ФСС_РАЗДЕЛ1(''0201'',7)')
INSERT #F VALUES (3,2,3,'4ФСС_РАЗДЕЛ1(''0202'',7)')
INSERT #F VALUES (3,3,3,'4ФСС_РАЗДЕЛ1(''0203'',7)')
INSERT #F VALUES (3,4,3,'4ФСС_РАЗДЕЛ1(''0204'',7)')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,8,3,'4ФСС_РАЗДЕЛ1(''0208'',7)')
INSERT #F VALUES (3,9,3,'4ФСС_РАЗДЕЛ1(''0209'',7)')
INSERT #F VALUES (3,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,4,'4ФСС_РАЗДЕЛ1(''0201'',6)')
INSERT #F VALUES (3,2,4,'4ФСС_РАЗДЕЛ1(''0202'',6)')
INSERT #F VALUES (3,3,4,'4ФСС_РАЗДЕЛ1(''0203'',6)')
INSERT #F VALUES (3,4,4,'4ФСС_РАЗДЕЛ1(''0204'',6)')
INSERT #F VALUES (3,5,4,'4ФСС_РАЗДЕЛ1(''0205'',6) ')
INSERT #F VALUES (3,6,4,'4ФСС_РАЗДЕЛ1(''0206'',6)  ')
INSERT #F VALUES (3,8,4,'4ФСС_РАЗДЕЛ1(''0208'',6)')
INSERT #F VALUES (3,9,4,'4ФСС_РАЗДЕЛ1(''0209'',6)')
INSERT #F VALUES (3,10,4,'4ФСС_РАЗДЕЛ1(''0210'',6)')
INSERT #F VALUES (3,11,4,'4ФСС_РАЗДЕЛ1(''0211'',6)')
INSERT #F VALUES (3,1,5,'4ФСС_РАЗДЕЛ1(''0201'',3)')
INSERT #F VALUES (3,2,5,'4ФСС_РАЗДЕЛ1(''0202'',3)')
INSERT #F VALUES (3,3,5,'4ФСС_РАЗДЕЛ1(''0203'',3)')
INSERT #F VALUES (3,4,5,'4ФСС_РАЗДЕЛ1(''0204'',3)')
INSERT #F VALUES (3,5,5,'4ФСС_РАЗДЕЛ1(''0205'',3) ')
INSERT #F VALUES (3,6,5,'4ФСС_РАЗДЕЛ1(''0206'',3)  ')
INSERT #F VALUES (3,8,5,'4ФСС_РАЗДЕЛ1(''0208'',3)')
INSERT #F VALUES (3,9,5,'4ФСС_РАЗДЕЛ1(''0209'',3)')
INSERT #F VALUES (3,10,5,'4ФСС_РАЗДЕЛ1(''0210'',3)')
INSERT #F VALUES (3,11,5,'4ФСС_РАЗДЕЛ1(''0211'',3)')
INSERT #F VALUES (3,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,6,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                           ')
INSERT #F VALUES (4,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                 ')
INSERT #F VALUES (4,3,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24                                                                                                             ')
INSERT #F VALUES (4,4,1,'Итого база для начисления страховых взносов  (строка 1 - строка 2 - строка 3)                                                                                                                                                                             ')
INSERT #F VALUES (4,5,1,'из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы                                                                                                                                                      ')
INSERT #F VALUES (4,6,1,'Cумма выплат и иных вознаграждений, производимых физическим лицам в связи с осуществлением фармацевтической деятельности                                                                                                                                  ')
INSERT #F VALUES (4,7,1,'Cумма выплат и иных вознаграждений членам экипажей судов, зарегистрированных в Российском международном реестре судов, за исполнение трудовых обязанностей члена экипажа судна                                                                            ')
INSERT #F VALUES (4,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,7,2,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,1,3,'4ФСС_РАЗДЕЛ1(''030103'',3)')
INSERT #F VALUES (4,2,3,'4ФСС_РАЗДЕЛ1(''030203'',3)')
INSERT #F VALUES (4,3,3,'4ФСС_РАЗДЕЛ1(''030303'',3)')
INSERT #F VALUES (4,5,3,'4ФСС_РАЗДЕЛ1(''030503'',3)')
INSERT #F VALUES (4,6,3,'4ФСС_РАЗДЕЛ1(''030603'',3)')
INSERT #F VALUES (4,7,3,'4ФСС_РАЗДЕЛ1(''030703'',3)')
INSERT #F VALUES (4,1,4,'4ФСС_РАЗДЕЛ1(''030104'',3)')
INSERT #F VALUES (4,2,4,'4ФСС_РАЗДЕЛ1(''030204'',3)')
INSERT #F VALUES (4,3,4,'4ФСС_РАЗДЕЛ1(''030304'',3)')
INSERT #F VALUES (4,5,4,'4ФСС_РАЗДЕЛ1(''030504'',3)')
INSERT #F VALUES (4,6,4,'4ФСС_РАЗДЕЛ1(''030604'',3)')
INSERT #F VALUES (4,7,4,'4ФСС_РАЗДЕЛ1(''030704'',3)')
INSERT #F VALUES (4,1,5,'4ФСС_РАЗДЕЛ1(''030105'',3)')
INSERT #F VALUES (4,2,5,'4ФСС_РАЗДЕЛ1(''030205'',3)')
INSERT #F VALUES (4,3,5,'4ФСС_РАЗДЕЛ1(''030305'',3)')
INSERT #F VALUES (4,5,5,'4ФСС_РАЗДЕЛ1(''030505'',3)')
INSERT #F VALUES (4,6,5,'4ФСС_РАЗДЕЛ1(''030605'',3)')
INSERT #F VALUES (4,7,5,'4ФСС_РАЗДЕЛ1(''030705'',3)')
INSERT #F VALUES (4,1,6,'4ФСС_РАЗДЕЛ1(''030106'',3)')
INSERT #F VALUES (4,2,6,'4ФСС_РАЗДЕЛ1(''030206'',3)')
INSERT #F VALUES (4,3,6,'4ФСС_РАЗДЕЛ1(''030306'',3)')
INSERT #F VALUES (4,5,6,'4ФСС_РАЗДЕЛ1(''030506'',3)')
INSERT #F VALUES (4,6,6,'4ФСС_РАЗДЕЛ1(''030606'',3)')
INSERT #F VALUES (4,7,6,'4ФСС_РАЗДЕЛ1(''030706'',3)')
INSERT #F VALUES (6,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (6,2,1,'     из них: численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                    ')
INSERT #F VALUES (6,3,1,'Удельный вес, % ( стр.2  / стр.1) х 100                                                                                                                                                                                                                   ')
INSERT #F VALUES (6,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (6,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (6,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (7,1,1,'Среднесписочная численность, всего (чел.)                                                                                                                                                                                                                     ')
INSERT #F VALUES (7,2,1,'  из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                        ')
INSERT #F VALUES (7,3,1,'Удельный вес, % (стр. 5 / стр. 4) х 100                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,4,1,'Фонд оплаты труда,
всего (руб.)                                                                                                                                                                                                                              ')
INSERT #F VALUES (7,5,1,'     из него: заработная плата инвалидов (руб.)                                                                                                                                                                                                               ')
INSERT #F VALUES (7,6,1,'Удельный вес заработной платы инвалидов, % (стр. 8 / стр. 7) х 100                                                                                                                                                                                            ')
INSERT #F VALUES (7,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,1,1,' Средняя численность работников/среднесписочная численность работников (чел.)                                                                                                                                                                             ')
INSERT #F VALUES (8,2,1,' Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                          ')
INSERT #F VALUES (8,3,1,'  из них: сумма доходов, определяемая  исходя из критериев, указанных в пункте 2 части 2.1 или пункте 2 части 2.2 статьи  57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                           ')
INSERT #F VALUES (8,4,1,'  доля доходов, определяемая в целях применения  части 5 статьи  58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(стр.3 / стр. 2) х 100                                                                                                               ')
INSERT #F VALUES (8,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий*                                                                                                                                             ')
INSERT #F VALUES (8,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                            ')
INSERT #F VALUES (9,2,1,'  из них: сумма доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                       № 212-ФЗ (руб.)                                                                                     ')
INSERT #F VALUES (9,3,1,'Доля доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                                              № 212-ФЗ (%)
(стр. 2 / стр. 1) х 100                                                   ')
INSERT #F VALUES (9,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,1,1,'Сумма доходов*, всего (руб.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (10,2,1,'из них: сумма доходов в виде целевых поступлений на содержание некоммерческих организаций и ведение ими уставной деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                    ')
INSERT #F VALUES (10,3,1,'сумма доходов в виде грантов, получаемых для осуществления деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                          ')
INSERT #F VALUES (10,4,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах р - ф, я.4 - я.6 пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                    ')
INSERT #F VALUES (10,5,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
((с. 2 + с. 3 + с.4) / с. 1) х 100                                                                                                     ')
INSERT #F VALUES (10,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (11,1,1,'Пособие по временной нетрудоспособности                                                                                                                                                                                                                   ')
INSERT #F VALUES (11,2,1,'Пособие по беременности и родам                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,1,'Ежемесячное пособие по уходу за ребенком, всего (стр. 4, 5)                                                                                                                                                                                               ')
INSERT #F VALUES (11,4,1,'в том числе: по уходу за первым ребенком                                                                                                                                                                                                                      ')
INSERT #F VALUES (11,5,1,'по уходу за вторым и 
последующими детьми                                                                                                                                                                                                                ')
INSERT #F VALUES (11,6,1,'Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению                                                                                                                                                    ')
INSERT #F VALUES (11,7,1,'ВСЕГО (строки 1 - 3, 6)                                                                                                                                                                                                                                   ')
INSERT #F VALUES (11,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (11,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (11,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,10,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,12,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,13,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,14,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,16,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,18,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,7,19,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,20,'ЗАПРЕТ()')
INSERT #F VALUES (11,6,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,1,'Всего с начала расчетного  периода                                                                                                                                                                                                                        ')
INSERT #F VALUES (12,2,1,'    В том числе за последние три месяца отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (12,3,1,'       В том числе за 1 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,4,1,'       В том числе за 2 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,1,'       В том числе за 3 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,1,3,'4ФСС_РАЗДЕЛ1(''060103'',3)')
INSERT #F VALUES (12,3,3,'4ФСС_РАЗДЕЛ1(''060303'',3)')
INSERT #F VALUES (12,4,3,'4ФСС_РАЗДЕЛ1(''060403'',3)')
INSERT #F VALUES (12,5,3,'4ФСС_РАЗДЕЛ1(''060503'',3)')
INSERT #F VALUES (12,1,4,'4ФСС_РАЗДЕЛ1(''060104'',3)')
INSERT #F VALUES (12,3,4,'4ФСС_РАЗДЕЛ1(''060304'',3)')
INSERT #F VALUES (12,4,4,'4ФСС_РАЗДЕЛ1(''060404'',3)')
INSERT #F VALUES (12,5,4,'4ФСС_РАЗДЕЛ1(''060504'',3)')
INSERT #F VALUES (12,1,5,'4ФСС_РАЗДЕЛ1(''060105'',3)')
INSERT #F VALUES (12,3,5,'4ФСС_РАЗДЕЛ1(''060305'',3)')
INSERT #F VALUES (12,4,5,'4ФСС_РАЗДЕЛ1(''060405'',3)')
INSERT #F VALUES (12,5,5,'4ФСС_РАЗДЕЛ1(''060505'',3)')
INSERT #F VALUES (12,1,6,'4ФСС_СПРАВОЧНИК(''tax_rate'')')
INSERT #F VALUES (12,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,7,'4ФСС_СПРАВОЧНИК(''discount'')')
INSERT #F VALUES (12,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,8,'4ФСС_СПРАВОЧНИК(''raise_date'')')
INSERT #F VALUES (12,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,9,'4ФСС_СПРАВОЧНИК(''raise_val'')')
INSERT #F VALUES (12,2,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,9,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,10,'4ФСС_СПРАВОЧНИК(''tax_total'')')
INSERT #F VALUES (12,2,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (13,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,3,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,4,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,5,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,6,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,7,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,8,1,'Начислено взносов по результатам проверок                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,9,1,'Не принято к зачету расходов территориальным органом Фонда за прошлые расчетные периоды                                                                                                                                                                   ')
INSERT #F VALUES (13,10,1,'Начислено взносов страхователем за прошлые расчетные периоды                                                                                                                                                                                              ')
INSERT #F VALUES (13,11,1,'Получено от территориального органа Фонда на банковский счет                                                                                                                                                                                              ')
INSERT #F VALUES (13,12,1,'Возврат сумм излишне уплаченных (взысканных) страховых взносов                                                                                                                                                                                            ')
INSERT #F VALUES (13,13,1,'Всего  (сумма строк 1+2+3+4+5+6+7)                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,14,1,'Задолженность за территориальным органом Фонда на конец отчетного периода                                                                                                                                                                                 ')
INSERT #F VALUES (13,15,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (13,16,1,'Расходы по обязательному социальному страхованию                                                                                                                                                                                                          ')
INSERT #F VALUES (13,17,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,18,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (13,19,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,20,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,21,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,22,1,'Уплачено страховых взносов                                                                                                                                                                                                                                ')
INSERT #F VALUES (13,23,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (13,24,1,'за последние три месяца отчетного периода дата, № платежного  поручения                                                                                                                                                                                   ')
INSERT #F VALUES (13,25,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,26,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,27,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,28,1,'Списанная сумма задолженности страхователя                                                                                                                                                                                                                ')
INSERT #F VALUES (13,29,1,'Всего (сумма строк 10+11+12+13                                                                                                                                                                                                                            ')
INSERT #F VALUES (13,30,1,'Задолженность за страхователем на конец отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (13,31,1,'           в том числе недоимка                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (13,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,9,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,10,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,11,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,12,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,13,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,14,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,15,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,16,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,17,2,'11_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,18,2,'11_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,19,2,'11_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,20,2,'11_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,21,2,'11_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,22,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,23,2,'12_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,24,2,'12_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,25,2,'12_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,26,2,'12_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,27,2,'12_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (13,28,2,'13                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,29,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,30,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,31,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,1,3,'КТСН("_.303.06","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (13,3,3,'4ФСС_РАЗДЕЛ1(''1021'',3)')
INSERT #F VALUES (13,5,3,'4ФСС_РАЗДЕЛ1(''1023'',3)')
INSERT #F VALUES (13,6,3,'4ФСС_РАЗДЕЛ1(''1024'',3)')
INSERT #F VALUES (13,7,3,'4ФСС_РАЗДЕЛ1(''1025'',3)')
INSERT #F VALUES (13,11,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.06")')
INSERT #F VALUES (13,17,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (13,19,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,20,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,21,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,23,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (13,25,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,26,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,27,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,30,3,'КТСК("_.303.06")')
INSERT #F VALUES (13,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,25,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (13,26,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (13,27,4,'НОМ_ПЛАТЕЖ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (13,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,1,1,'Пособия по временной нетрудоспособности в связи
с несчастными случаями на производстве, всего                                                                                                                                                            ')
INSERT #F VALUES (14,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (14,3,1,'      пострадавшим на другом предприятии                                                                                                                                                                                                                  ')
INSERT #F VALUES (14,4,1,'Пособия по временной нетрудоспособности в связи
с профессиональными заболеваниями, всего                                                                                                                                                                 ')
INSERT #F VALUES (14,5,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (14,6,1,'      пострадавшим на другом предприятии                                                                                                                                                                                                                  ')
INSERT #F VALUES (14,7,1,'Оплата отпуска для санаторно-курортного лечения застрахованным (сверх ежегодного оплачиваемого отпуска, установленного законодательством Российской Федерации)                                                                                            ')
INSERT #F VALUES (14,8,1,'      из них: пострадавшим на другом предприятии                                                                                                                                                                                                          ')
INSERT #F VALUES (14,9,1,'Финансирование предупредительных мер по сокращению производственного травматизма и профзаболеваний                                                                                                                                                        ')
INSERT #F VALUES (14,10,1,'Всего расходов (сумма строк 1, 4, 7, 9)                                                                                                                                                                                                                   ')
INSERT #F VALUES (14,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,8,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,1,3,'4ФСС_РАЗДЕЛ1(''1101'',6)')
INSERT #F VALUES (14,2,3,'4ФСС_РАЗДЕЛ1(''1102'',6)')
INSERT #F VALUES (14,4,3,'4ФСС_РАЗДЕЛ1(''1104'',6)')
INSERT #F VALUES (14,5,3,'4ФСС_РАЗДЕЛ1(''1105'',6)')
INSERT #F VALUES (14,7,3,'4ФСС_РАЗДЕЛ1(''1107'',6)')
INSERT #F VALUES (14,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (14,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (14,1,4,'4ФСС_РАЗДЕЛ1(''1101'',3)')
INSERT #F VALUES (14,2,4,'4ФСС_РАЗДЕЛ1(''1102'',3)')
INSERT #F VALUES (14,4,4,'4ФСС_РАЗДЕЛ1(''1104'',3)')
INSERT #F VALUES (14,5,4,'4ФСС_РАЗДЕЛ1(''1105'',3)')
INSERT #F VALUES (14,7,4,'4ФСС_РАЗДЕЛ1(''1107'',3)')
INSERT #F VALUES (15,1,1,'По несчастным случаям                                                                                                                                                                                                                                     ')
INSERT #F VALUES (15,2,1,'      из них: со смертельным исходом                                                                                                                                                                                                                      ')
INSERT #F VALUES (15,3,1,'По профессиональным заболеваниям                                                                                                                                                                                                                          ')
INSERT #F VALUES (15,4,1,'ВСЕГО пострадавших (сумма строк 1, 3)                                                                                                                                                                                                                     ')
INSERT #F VALUES (15,5,1,'в том числе пострадавших (застрахованных) по случаям, закончившимся только временной нетрудоспособностью                                                                                                                                                  ')
INSERT #F VALUES (15,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,1,1,'Аттестация рабочих мест по условиям труда                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,2,1,'Проведение обязательных и периодических медицинских осмотров (обследований) работников                                                                                                                                                                        ')
INSERT #F VALUES (16,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (16,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (16,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (16,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (16,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (16,1,9,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 586
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 0
--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)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.2_2гр.3 =  т.2стр.2_3гр.3 +  т.2стр.2_4гр.3 +  т.2стр.2_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.3_2гр.3 =  т.2стр.3_3гр.3 +  т.2стр.3_4гр.3 +  т.2стр.3_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.5_2гр.3 =  т.2стр.5_3гр.3 +  т.2стр.5_4гр.3 +  т.2стр.5_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.6_2гр.3 =  т.2стр.6_3гр.3 +  т.2стр.6_4гр.3 +  т.2стр.6_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.8гр.3 =  т.2стр.1гр.3 +  т.2стр.2гр.3 +  т.2стр.3гр.3 +  т.2стр.4гр.3 +  т.2стр.5гр.3 +  т.2стр.6гр.3 +  т.2стр.7гр.3',1,2,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.15_2гр.3 =  т.2стр.15_3гр.3 +  т.2стр.15_4гр.3 +  т.2стр.15_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.16_2гр.3 =  т.2стр.16_3гр.3 +  т.2стр.16_4гр.3 +  т.2стр.16_5гр.3',1,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.18гр.3 =  т.2стр.12гр.3 +  т.2стр.15гр.3 +  т.2стр.16гр.3 +  т.2стр.17гр.3',1,2,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.15гр.3 =  т.3стр.12гр.4',0,0,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.3стр.12гр.4 =  т.3стр.1гр.4 +  т.3стр.3гр.4 +  т.3стр.5гр.4 +  т.3стр.6гр.4 +  т.3стр.7гр.4 +  т.3стр.10гр.4 +  т.3стр.11гр.4',1,1,1,'20110321','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.3стр.12гр.5 =  т.3стр.1гр.5 +  т.3стр.3гр.5 +  т.3стр.5гр.5 +  т.3стр.6гр.5 +  т.3стр.7гр.5 +  т.3стр.10гр.5 +  т.3стр.11гр.5',1,1,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.4стр.4гр.3 =  т.4стр.1гр.3 -  т.4стр.2гр.3 -  т.4стр.3гр.3',1,0,1,'20110330','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.4стр.4гр.4 =  т.4стр.1гр.4 -  т.4стр.2гр.4 -  т.4стр.3гр.4',1,0,1,'20110330','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.4стр.4гр.5 =  т.4стр.1гр.5 -  т.4стр.2гр.5 -  т.4стр.3гр.5',1,0,1,'20110330','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.4стр.4гр.6 =  т.4стр.1гр.6 -  т.4стр.2гр.6 -  т.4стр.3гр.6',1,0,1,'20110330','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.6стр.1гр.3 =  т.6стр.1гр.6',1,0,1,'20110321','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.6стр.2гр.3 =  т.6стр.2гр.6',1,0,1,'20110321','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.6стр.3гр.3 =  т.6стр.2гр.3 /  т.6стр.1гр.3 *  100',1,0,1,'20110321','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.6стр.3гр.4 =  т.6стр.2гр.4 /  т.6стр.1гр.4 *  100',1,0,1,'20110321','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.6стр.3гр.5 =  т.6стр.2гр.5 /  т.6стр.1гр.5 *  100',1,0,1,'20110321','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.6стр.3гр.6 =  т.6стр.2гр.6 /  т.6стр.1гр.6 *  100',1,0,1,'20110321','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.7стр.1гр.3 =  т.7стр.1гр.6',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.7стр.2гр.3 =  т.7стр.2гр.6',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.7стр.3гр.3 =  т.7стр.2гр.3 /  т.7стр.1гр.3 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.7стр.3гр.4 =  т.7стр.2гр.4 /  т.7стр.1гр.4 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.7стр.3гр.5 =  т.7стр.2гр.5 /  т.7стр.1гр.5 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.7стр.3гр.6 =  т.7стр.2гр.6 /  т.7стр.1гр.6 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.7стр.6гр.3 =  т.7стр.5гр.3 /  т.7стр.4гр.3 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.7стр.6гр.4 =  т.7стр.5гр.4 /  т.7стр.4гр.4 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.7стр.6гр.5 =  т.7стр.5гр.5 /  т.7стр.4гр.5 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.7стр.6гр.6 =  т.7стр.5гр.6 /  т.7стр.4гр.6 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.8стр.4гр.3 =  т.8стр.3гр.3 /  т.8стр.2гр.3 *  100',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.11стр.1гр.5 =  т.3стр.1гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.11стр.2гр.5 =  т.3стр.3гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.11стр.4гр.5 =  т.3стр.8гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.11стр.5гр.5 =  т.3стр.9гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.11стр.3гр.5 =  т.11стр.4гр.5 +  т.11стр.5гр.5',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.11стр.6гр.5 =  т.3стр.11гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.11стр.7гр.3 =  т.11стр.1гр.3 +  т.11стр.2гр.3 +  т.11стр.3гр.3 +  т.11стр.6гр.3',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.11стр.7гр.5 =  т.11стр.1гр.5 +  т.11стр.2гр.5 +  т.11стр.3гр.5 +  т.11стр.6гр.5',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.11стр.7гр.6 =  т.11стр.1гр.6 +  т.11стр.2гр.6 +  т.11стр.3гр.6 +  т.11стр.6гр.6',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.11стр.7гр.8 =  т.11стр.1гр.8 +  т.11стр.2гр.8 +  т.11стр.3гр.8 +  т.11стр.6гр.8',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.11стр.7гр.9 =  т.11стр.1гр.9 +  т.11стр.2гр.9 +  т.11стр.3гр.9 +  т.11стр.6гр.9',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.11стр.7гр.11 =  т.11стр.1гр.11 +  т.11стр.2гр.11 +  т.11стр.3гр.11 +  т.11стр.6гр.11',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.11стр.7гр.12 =  т.11стр.1гр.12 +  т.11стр.2гр.12 +  т.11стр.3гр.12 +  т.11стр.6гр.12',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.11стр.7гр.14 =  т.11стр.1гр.14 +  т.11стр.2гр.14 +  т.11стр.3гр.14 +  т.11стр.6гр.14',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.11стр.7гр.15 =  т.11стр.1гр.15 +  т.11стр.2гр.15 +  т.11стр.3гр.15 +  т.11стр.6гр.15',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.11стр.7гр.17 =  т.11стр.1гр.17 +  т.11стр.2гр.17 +  т.11стр.3гр.17 +  т.11стр.6гр.17',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.11стр.7гр.18 =  т.11стр.1гр.18 +  т.11стр.2гр.18 +  т.11стр.3гр.18 +  т.11стр.6гр.18',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.11стр.7гр.20 =  т.11стр.1гр.20 +  т.11стр.2гр.20 +  т.11стр.3гр.20 +  т.11стр.6гр.20',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.12стр.2гр.3 =  т.12стр.3гр.3 +  т.12стр.4гр.3 +  т.12стр.5гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.12стр.2гр.4 =  т.12стр.3гр.4 +  т.12стр.4гр.4 +  т.12стр.5гр.4',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.12стр.2гр.5 =  т.12стр.3гр.5 +  т.12стр.4гр.5 +  т.12стр.5гр.5',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.13стр.2_2гр.3 =  т.13стр.2_3гр.3 +  т.13стр.2_4гр.3 +  т.13стр.2_5гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.13стр.8гр.3 =  т.13стр.1гр.3 +  т.13стр.2гр.3 +  т.13стр.3гр.3 +  т.13стр.4гр.3 +  т.13стр.5гр.3 +  т.13стр.6гр.3 +  т.13стр.7гр.3',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.13стр.11_2гр.3 =  т.13стр.11_3гр.3 +  т.13стр.11_4гр.3 +  т.13стр.11_5гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.13стр.12_2гр.3 =  т.13стр.12_3гр.3 +  т.13стр.12_4гр.3 +  т.13стр.12_5гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.13стр.14гр.3 =  т.13стр.10гр.3 +  т.13стр.11гр.3 +  т.13стр.12гр.3 +  т.13стр.13гр.3',1,2,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.14стр.10гр.4 =  т.14стр.1гр.4 +  т.14стр.4гр.4 +  т.14стр.7гр.4 +  т.14стр.9гр.4',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.15стр.4гр.3 =  т.15стр.1гр.3 +  т.15стр.3гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.13стр.2гр.3 =  т.13стр.2_1гр.3 +  т.13стр.2_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.13стр.11гр.3 =  т.13стр.11_1гр.3 +  т.13стр.11_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.13стр.12гр.3 =  т.13стр.12_1гр.3 +  т.13стр.12_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.13гр.3 =  т.13гр.3 -  т.13гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.2гр.3 =  -  т.2гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.2гр.3 =  -  т.2гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.2гр.3 =  -  т.2гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.2гр.3 =  т.2гр.3',1,0,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.2гр.3 =  т.2гр.3 -  т.2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.2стр.2гр.3 =  т.2стр.2_1гр.3 +  т.2стр.2_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.2стр.3гр.3 =  т.2стр.3_1гр.3 +  т.2стр.3_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.2стр.5гр.3 =  т.2стр.5_1гр.3 +  т.2стр.5_2гр.3',1,1,1,'20120217','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.2стр.6гр.3 =  т.2стр.6_1гр.3 +  т.2стр.6_2гр.3',1,1,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.2стр.15гр.3 =  т.2стр.15_1гр.3 +  т.2стр.15_2гр.3',1,1,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.2стр.16гр.3 =  т.2стр.16_1гр.3 +  т.2стр.16_2гр.3',1,1,1,'20110322','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'Проверки =  0',0,100,1,'20110331','','','','4fss','20120101','','=',9,'')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.3стр.7гр.2 =  т.3стр.8гр.2 +  т.3стр.9гр.2',1,0,1,'20110328','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.3стр.7гр.3 =  т.3стр.8гр.3 +  т.3стр.9гр.3',1,0,1,'20110328','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.3стр.7гр.4 =  т.3стр.8гр.4 +  т.3стр.9гр.4',1,0,1,'20110328','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.3стр.7гр.5 =  т.3стр.8гр.5 +  т.3стр.9гр.5',1,0,1,'20110328','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.1стр.2гр.3 <=  т.1стр.1гр.3',0,0,1,'20110401','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.1стр.3гр.3 <=  т.1стр.1гр.3',0,0,1,'20110401','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.1стр.4гр.3 <=  т.1стр.1гр.3',0,0,1,'20110401','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.3стр.2гр.2 <=  т.3стр.1гр.2',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.3стр.2гр.3 <=  т.3стр.1гр.3',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.3стр.2гр.4 <=  т.3стр.1гр.4',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.3стр.2гр.5 <=  т.3стр.1гр.5',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.3стр.4гр.3 <=  т.3стр.3гр.3',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.3стр.4гр.4 <=  т.3стр.3гр.4',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.3стр.4гр.5 <=  т.3стр.3гр.5',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(94,NULL,0,NULL,94,7,0,0,0,'т.4стр.1гр.3 >=  т.4стр.1гр.4 +  т.4стр.1гр.5 +  т.4стр.1гр.6',0,0,1,'20110404','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(95,NULL,0,NULL,95,7,0,0,0,'т.4стр.2гр.3 >=  т.4стр.2гр.4 +  т.4стр.2гр.5 +  т.4стр.2гр.6',0,0,1,'20110404','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(96,NULL,0,NULL,96,7,0,0,0,'т.4стр.3гр.3 >=  т.4стр.3гр.4 +  т.4стр.3гр.5 +  т.4стр.3гр.6',0,0,1,'20110404','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(97,NULL,0,NULL,97,7,0,0,0,'т.4стр.4гр.3 >=  т.4стр.4гр.4 +  т.4стр.4гр.5 +  т.4стр.4гр.6',0,0,1,'20110404','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(98,NULL,0,NULL,98,7,0,0,0,'т.4стр.5гр.3 >=  т.4стр.5гр.4 +  т.4стр.5гр.5 +  т.4стр.5гр.6',0,0,1,'20110404','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(99,NULL,0,NULL,99,7,0,0,0,'т.4стр.5гр.3 <=  т.4стр.4гр.3',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(100,NULL,0,NULL,100,7,0,0,0,'т.4стр.5гр.4 <=  т.4стр.4гр.4',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(101,NULL,0,NULL,101,7,0,0,0,'т.4стр.5гр.5 <=  т.4стр.4гр.5',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(102,NULL,0,NULL,102,7,0,0,0,'т.4стр.5гр.6 <=  т.4стр.4гр.6',0,0,1,'20110404','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(103,NULL,0,NULL,103,7,0,0,0,'т.12стр.1гр.4 <=  т.12стр.1гр.3',0,0,1,'20120220','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(104,NULL,0,NULL,104,7,0,0,0,'т.13стр.16гр.3 <=  т.13стр.15гр.3',0,0,1,'20120220','','','','4fss','20120101','','<=',1,'')
INSERT #A VALUES(105,NULL,0,NULL,105,7,0,0,0,'т.13стр.11гр.3 =  т.14стр.10гр.4',0,0,1,'20120220','','','','4fss','20120101','','=',1,'')
INSERT #A VALUES(106,NULL,0,NULL,106,7,0,0,0,'т.14стр.1гр.3 >=  т.14стр.2гр.3 +  т.14стр.3гр.3',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(107,NULL,0,NULL,107,7,0,0,0,'т.14стр.1гр.4 >=  т.14стр.2гр.4 +  т.14стр.3гр.4',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(108,NULL,0,NULL,108,7,0,0,0,'т.14стр.4гр.3 >=  т.14стр.5гр.3 +  т.14стр.6гр.3',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(109,NULL,0,NULL,109,7,0,0,0,'т.14стр.4гр.4 >=  т.14стр.5гр.4 +  т.14стр.6гр.4',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(110,NULL,0,NULL,110,7,0,0,0,'т.14стр.7гр.3 >=  т.14стр.8гр.3',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(111,NULL,0,NULL,111,7,0,0,0,'т.14стр.7гр.4 >=  т.14стр.8гр.4',0,0,1,'20120220','','','','4fss','20120101','','>=',1,'')
INSERT #A VALUES(112,NULL,0,NULL,112,7,0,0,0,'т.8стр.4гр.4 =  т.8стр.3гр.4 /  т.8стр.2гр.4 *  100',1,0,1,'20120220','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(113,NULL,0,NULL,113,7,0,0,0,'т.9стр.3гр.3 =  т.9стр.2гр.3 /  т.9стр.1гр.3 *  100',1,0,1,'20120220','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(114,NULL,0,NULL,114,7,0,0,0,'т.10стр.5гр.3 =  т.10стр.4гр.3 +  т.10стр.3гр.3 +  т.10стр.2гр.3 /  т.10стр.1гр.3 *  100',1,0,1,'20120220','','','','4fss','20120101','','=',0,'')
INSERT #A VALUES(115,NULL,0,NULL,115,7,0,0,0,'т.10стр.5гр.4 =  т.10стр.4гр.4 +  т.10стр.3гр.4 +  т.10стр.2гр.4 /  т.10стр.1гр.4 *  100',1,0,1,'20120220','','','','4fss','20120101','','=',0,'')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 115
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]    FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','18','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','17','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','7','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','1','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','2','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','3','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','6','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','14','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','10','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','13','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''19''','','','','','3','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''12''','','','','','3','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3)  < CONVERT(FLOAT,0)','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''13''','','','','','3','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3)  < CONVERT(FLOAT,0)','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9'' AND COL(3) > CONVERT(FLOAT,0)','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''12''','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''12''','','','','','3','','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,2,'+',NULL,NULL,NULL,NULL,0,0,'SA_4FSS_EXPORT_TEST(0)','Проверки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',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) <> 401
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM

EXEC dbo.[I_CONTROL_RULES_ACTION] 7


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2012-04-05 11:42:02.953',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 = '2012-04-05 11:42:02.953'
	BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' не может быть обновлена версией от 2012-04-05 11:42:02.953. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев 28 2012  7:48:49:527PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : AV_ASS (Налоговая декларация по налогу на имущество организаций)
-- Дата ввода : 20080101
-- Дата окончания действия : 20111230
-- Версия : 2012-02-28 19:48:49.527
-- Параметры выгрузки :
-- только обновить  REPORT_FORMS              : да

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'AV_ASS' AND [START_DATE] = '20080101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2012-02-28 19:48:49.527',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Обновление только REPORT_FORMS.
UPDATE dbo.[REPORT_FORMS]
SET [NAME]                = 'Налоговая декларация по налогу на имущество организаций',
    [ExportCode]          = '          ',
    [START_DATE]          = '20080101',
    [END_DATE]            = '20111230',
    [PERIODIC]            = 1,
    [ISSVOD]              = 1,
    [ISEXPORTED]          = 1,
    [ISUSERFORM]          = 0,
    [IsKonsolid]          = 0,
    [IS_AUTOFILL]         = 0,
    [PRINT_OBJECT_METHOD] = 'SvodPrint_ass_bal()',
    [QUERY_ADD_MODULE]    = 'KirRepF_AV_ASS_K.bas#KirRepF_AV_ASS_F.bas',
    [QUERY_BEFORE]        = '',
    [QUERY_REPMAKER]      = 'KirRepMakerMultiSheet.xls',
    [QUERY_REPORT]        = 'F1152001_K.XLT#F1152001_F.XLT',
    [QUERY_REPORT_PATH]   = '',
    [DECRIPT_PROC]        = '',
    [EXPORT_PROC]         = 'i_report_export_nalog',
    [IsRemoteAccess]      = 0,
    [PARAM_EXPORT]        = NULL,
    [PARAM_IMPORT]        = NULL,
    [OBJECT]              = NULL,
    [ATRIBUTS]            = '',
    [SvodProc]            = NULL,
    [COMMENT]             = NULL,
    [PRINT_OBJECT_METHOD_NEW] = NULL,
    [QUERY_BEFORE_PRINT_NEW]  = '',
    [QUERY_REPORT_NEW]        = '',
    [IS_CALC]        = 1
WHERE [LINK_FORM] = @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2012-02-28 19:48:49.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 = '2012-02-28 19:48:49.527'
	BEGIN
		SELECT @vcMessage = 'Форма AV_ASS с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма AV_ASS с версией от ' + @vcMessage + ' не может быть обновлена версией от 2012-02-28 19:48:49.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


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев 28 2012  7:48:49:573PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : AV_F1152028 (Расчет авансового платежа по налогу на имущество организаций)
-- Дата ввода : 20080101
-- Дата окончания действия : 20111231
-- Версия : 2012-02-28 19:48:49.573
-- Параметры выгрузки :
-- только обновить  REPORT_FORMS              : да

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'AV_F1152028' AND [START_DATE] = '20080101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2012-02-28 19:48:49.573',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Обновление только REPORT_FORMS.
UPDATE dbo.[REPORT_FORMS]
SET [NAME]                = 'Расчет авансового платежа по налогу на имущество организаций',
    [ExportCode]          = '          ',
    [START_DATE]          = '20080101',
    [END_DATE]            = '20111231',
    [PERIODIC]            = 2,
    [ISSVOD]              = 0,
    [ISEXPORTED]          = 1,
    [ISUSERFORM]          = 0,
    [IsKonsolid]          = 0,
    [IS_AUTOFILL]         = 0,
    [PRINT_OBJECT_METHOD] = 'SVODPRINT_AV_ASSETS()',
    [QUERY_ADD_MODULE]    = 'KirRepF_AV_ASS_K.bas#KirRepF_AV_ASS_F.bas',
    [QUERY_BEFORE]        = '',
    [QUERY_REPMAKER]      = 'KirRepMakerMultiSheet.xls',
    [QUERY_REPORT]        = 'F1152001_K.XLT#F1152001_F.XLT',
    [QUERY_REPORT_PATH]   = '',
    [DECRIPT_PROC]        = NULL,
    [EXPORT_PROC]         = 'i_report_export_nalog',
    [IsRemoteAccess]      = 0,
    [PARAM_EXPORT]        = NULL,
    [PARAM_IMPORT]        = NULL,
    [OBJECT]              = NULL,
    [ATRIBUTS]            = '',
    [SvodProc]            = NULL,
    [COMMENT]             = NULL,
    [PRINT_OBJECT_METHOD_NEW] = NULL,
    [QUERY_BEFORE_PRINT_NEW]  = '',
    [QUERY_REPORT_NEW]        = '',
    [IS_CALC]        = 1
WHERE [LINK_FORM] = @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2012-02-28 19:48:49.573',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 = '2012-02-28 19:48:49.573'
	BEGIN
		SELECT @vcMessage = 'Форма AV_F1152028 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма AV_F1152028 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2012-02-28 19:48:49.573. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  1 2012  3:42:41:400PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20110101
-- Дата окончания действия :
-- Версия : 2012-02-01 15:42:41.400
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'РСВ-1' AND [START_DATE] = '20110101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2012-02-01 15:42:41.400',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + 'РСВ-1',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = 'РСВ-1'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20110101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_rsv_1_pfr_2011()','RSV_1_PFR_2011.bas','','KirRepMakerMultiSheet.XLS','RSV-1-PFR_2011.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Титульный лист', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество застрахованных лиц',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Среднесписочная численность',@iLINK_TABLE,1,0,4,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Титульный лист', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1. Расчет по начисленным и уплаченным страховым в', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Страховые взносы на ОПС: страховая часть',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на ОПС: накопительная часть',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы на ОМС: ФФОМС',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Страховые взносы на ОМС: ТФОМС',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1. Расчет по начисленным и уплаченным страховым в', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2. Расчет страховых взносов по тарифу, установлен', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2. Расчет страховых взносов по тарифу, установлен', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3. Расчет страховых взносов по пониженному тарифу', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3. Расчет страховых взносов по пониженному тарифу', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.1. Сведения, необходимые для применения пониже', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия имя отчество',@iLINK_TABLE,1,1,2,0,100,1,'KU_PERSON_FIO','COL2','CODE',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата справки',@iLINK_TABLE,0,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.1. Сведения, необходимые для применения пониже', @iLINK_FORM,5, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PFR_INV @dateBeginPeriod, @dateEndPeriod, @depLink, 7, 1',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.2. Расчет соответствия условий на право примене', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.2. Расчет соответствия условий на право примене', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.3. Соответсвие условиям п.4.,ч.2.,ст.57 ФЗ № 21', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам  9-ти месяцев года, предшествующего текущему расчетному пери',@iLINK_TABLE,1,0,3,1,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Дата записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,4,4,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,5,5,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.3. Соответсвие условиям п.4.,ч.2.,ст.57 ФЗ № 21', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.4. Соответсвие условиям ч.3.2. ст.58 ФЗ № 212-Ф', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,0,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.4. Соответсвие условиям ч.3.2. ст.58 ФЗ № 212-Ф', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5. Задолженность на ОПС  по состоянию на 31.12.09', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На страховую часть пенсии',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'На накопительную часть пенсии',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5. Задолженность на ОПС  по состоянию на 31.12.09', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (1,2,0,1)
INSERT #R VALUES (2,2,0,1)
INSERT #R VALUES (3,2,0,1)
INSERT #R VALUES (4,2,0,1)
INSERT #R VALUES (5,2,0,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,0,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,0,1)
INSERT #R VALUES (10,2,0,1)
INSERT #R VALUES (11,2,0,1)
INSERT #R VALUES (12,2,0,1)
INSERT #R VALUES (13,2,1,1)
INSERT #R VALUES (14,2,0,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,0,1)
INSERT #R VALUES (3,3,0,1)
INSERT #R VALUES (4,3,1,1)
INSERT #R VALUES (5,3,0,1)
INSERT #R VALUES (6,3,0,1)
INSERT #R VALUES (7,3,0,1)
INSERT #R VALUES (8,3,0,1)
INSERT #R VALUES (9,3,1,1)
INSERT #R VALUES (10,3,0,1)
INSERT #R VALUES (11,3,0,1)
INSERT #R VALUES (12,3,1,1)
INSERT #R VALUES (13,3,1,1)
INSERT #R VALUES (14,3,2,1)
INSERT #R VALUES (15,3,0,1)
INSERT #R VALUES (16,3,0,1)
INSERT #R VALUES (17,3,0,1)
INSERT #R VALUES (18,3,0,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,0,1)
INSERT #R VALUES (3,4,0,1)
INSERT #R VALUES (4,4,1,1)
INSERT #R VALUES (5,4,0,1)
INSERT #R VALUES (6,4,0,1)
INSERT #R VALUES (7,4,0,1)
INSERT #R VALUES (8,4,0,1)
INSERT #R VALUES (9,4,1,1)
INSERT #R VALUES (10,4,0,1)
INSERT #R VALUES (11,4,0,1)
INSERT #R VALUES (12,4,1,1)
INSERT #R VALUES (13,4,1,1)
INSERT #R VALUES (14,4,2,1)
INSERT #R VALUES (15,4,0,1)
INSERT #R VALUES (16,4,0,1)
INSERT #R VALUES (17,4,0,1)
INSERT #R VALUES (18,4,0,1)
INSERT #R VALUES (19,4,1,1)
INSERT #R VALUES (20,4,0,1)
INSERT #R VALUES (21,4,0,1)
INSERT #R VALUES (22,4,1,1)
INSERT #R VALUES (23,4,0,1)
INSERT #R VALUES (24,4,0,1)
INSERT #R VALUES (25,4,1,1)
INSERT #R VALUES (26,4,0,1)
INSERT #R VALUES (27,4,0,1)
INSERT #R VALUES (28,4,1,1)
INSERT #R VALUES (29,4,1,1)
INSERT #R VALUES (30,4,2,1)
INSERT #R VALUES (31,4,0,1)
INSERT #R VALUES (32,4,0,1)
INSERT #R VALUES (33,4,0,1)
INSERT #R VALUES (34,4,0,1)
INSERT #R VALUES (1,6,0,1)
INSERT #R VALUES (2,6,0,1)
INSERT #R VALUES (3,6,1,1)
INSERT #R VALUES (4,6,0,1)
INSERT #R VALUES (5,6,0,1)
INSERT #R VALUES (6,6,1,1)
INSERT #R VALUES (7,6,0,1)
INSERT #R VALUES (8,6,0,1)
INSERT #R VALUES (9,6,1,1)
INSERT #R VALUES (1,7,1,1)
INSERT #R VALUES (2,7,3,1)
INSERT #R VALUES (3,7,4,1)
INSERT #R VALUES (4,7,5,1)
INSERT #R VALUES (5,7,6,1)
INSERT #R VALUES (1,8,1,1)
INSERT #R VALUES (2,8,3,1)
INSERT #R VALUES (3,8,4,1)
INSERT #R VALUES (1,9,1,1)
INSERT #R VALUES (2,9,3,1)
INSERT #R VALUES (3,9,4,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 87
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Показатель                                                                                                                                                                                                                                                ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,1,3,'РСВ1_УСТАНОВКА() + РСВ1_ЗНАЧЕНИЕ(К.СТР.,1)')
INSERT #F VALUES (1,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,2)')
INSERT #F VALUES (2,1,1,'Остаток страховых взносов, подлежащих уплате на начало расчетного периода ((+) задолженность, (-) переплата)
                                                                                                                                                ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов с начала расчетного периода                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,1,'в том числе за последние три месяца отчетного периода: 1 месяц')
INSERT #F VALUES (2,4,1,'          2 месяц')
INSERT #F VALUES (2,5,1,'          3 месяц')
INSERT #F VALUES (2,6,1,'          итого (с. 111 + с. 112 + с. 113)')
INSERT #F VALUES (2,7,1,'Доначислено страховых взносов с начала расчетного периода')
INSERT #F VALUES (2,8,1,'Всего к уплате (с. 100 + с. 110 + с. 120)')
INSERT #F VALUES (2,9,1,'Уплачено с начала расчетного периода                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,10,1,'в том числе за последние три месяца отчетного периода: 1 месяц                                                                                                                                                                                                ')
INSERT #F VALUES (2,11,1,'          2 месяц                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,12,1,'          3 месяц                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,13,1,'          итого (с. 141 + с. 142 + с. 143)')
INSERT #F VALUES (2,14,1,'Остаток страховых взносов, подлежащих уплате на конец отчетного периода (+) задолженность, (-) переплата                                                                                                                                                      ')
INSERT #F VALUES (2,1,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,2,'110                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'111                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'112                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'113                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'114                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'120                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'130                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,9,2,'140                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'141                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'142                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'143                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'144                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'150                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,1,3,'КТСН("_.303.10","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,3,'АДТКТ("_.303.10","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,3,'АДТКТ("_.303.10","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,3,'АДТКТ("_.303.10","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,3,'АДТКТ("_.303.10","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,4,'КТСН("_.303.11","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,4,'АДТКТ("_.303.11","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,4,'АДТКТ("_.303.11","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,4,'АДТКТ("_.303.11","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,4,'АДТКТ("_.303.11","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,5,'КТСН("_.303.07","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,5,'АДТКТ("_.303.07","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,5,'АДТКТ("_.303.07","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,5,'АДТКТ("_.303.07","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,5,'АДТКТ("_.303.07","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,6,'КТСН("_.303.08","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,6,'АДТКТ("_.303.08","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,6,'АДТКТ("_.303.08","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,6,'АДТКТ("_.303.08","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,6,'АДТКТ("_.303.08","_.304.05:_.201.11:_.201.21:_.201.27,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (3,1,1,'Сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц (ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ): всего (с. 201 + с. 202)')
INSERT #F VALUES (3,2,1,'      1966 г.р. и старше                                                                                                                                                                                                                                      ')
INSERT #F VALUES (3,3,1,'      1967 г.р. и моложе                                                                                                                                                                                                                                      ')
INSERT #F VALUES (3,4,1,'Суммы, не подлежащие обложению страх. взн. (ч. 1, 2 ст. 9): всего (с. 211 + с. 212)')
INSERT #F VALUES (3,5,1,'                            1966 г.р. и старше                                                                                                                                                                                                                ')
INSERT #F VALUES (3,6,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,7,1,'              в соответствии с п. 1 ч. 3 ст. 9: 1966 г.р. и старше
                                                                                                                                                                                          ')
INSERT #F VALUES (3,8,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,9,1,'Суммы, превышающие предел. величину базы для начисления страх. взн., установленную ст. 8 ФЗ от 24 июля 2009 г. № 212-ФЗ: всего (с. 217 + с. 218)')
INSERT #F VALUES (3,10,1,'       1966 г.р. и старше                                                                                                                                                                                                                                     ')
INSERT #F VALUES (3,11,1,'       1967 г.р. и моложе                                                                                                                                                                                                                                     ')
INSERT #F VALUES (3,12,1,'База для начисления страховых взносов на обязательное пенсионное страхование: 1966 г.р. и старше (с. 201 - с. 211 - с. 214 - с. 217)')
INSERT #F VALUES (3,13,1,'       1967 г.р. и моложе (с. 202 - с. 212 - с. 215 - с. 218)
')
INSERT #F VALUES (3,14,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 200 - с. 210 - ст. 216)')
INSERT #F VALUES (3,15,1,'Начислено страховых взносов на обяза-тельное пенсионное страхование: страховая часть                                                                                                                                                                          ')
INSERT #F VALUES (3,16,1,'       накопительная часть                                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,17,1,'Начислено страховых взносов на обяза-тельное медицинское страхование: ФФОМС                                                                                                                                                                                   ')
INSERT #F VALUES (3,18,1,'      ТФОМС                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'201                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'202                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'211                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'212                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'214                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'215                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'216                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'217                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,11,2,'218                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,12,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,13,2,'221                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,14,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,15,2,'241                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,16,2,'242                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,17,2,'243                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,18,2,'244                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,1,1,'По инвалидам: сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц, в соответствии со ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ: (с. 301 + с. 302)')
INSERT #F VALUES (4,2,1,'                    1966 г.р. и старше                                                                                                                                                                                                                        ')
INSERT #F VALUES (4,3,1,'                    1967 г.р. и моложе                                                                                                                                                                                                                        ')
INSERT #F VALUES (4,4,1,'     Суммы, не подлежащие обложению страховыми взносами ( ч. 1, 2 ст. 9): всего (с. 311 + с. 312)')
INSERT #F VALUES (4,5,1,'                   1966 г.р. и старше                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,6,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,7,1,'            в соответствии с п. 1 ч. 3 ст. 9: 1966 г.р. и старше                                                                                                                                                                                              ')
INSERT #F VALUES (4,8,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,9,1,'     Суммы, превышающие предел. величину базы для начисления страх. взн. (ст. 8): всего (с. 317 + с. 318)')
INSERT #F VALUES (4,10,1,'                   1966 г.р. и старше                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,11,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,12,1,'      База для начисления страх. взн. на ОПС: 1966 г.р. и старше (с. 301 - с. 311 - с. 314 - с. 317)')
INSERT #F VALUES (4,13,1,'                   1967 г.р. и моложе (с. 302 - с. 312 - с. 315 - с. 318)')
INSERT #F VALUES (4,14,1,'      База для начисления страх. взн на ОМС (с. 300 - с. 310 - с. 316)')
INSERT #F VALUES (4,15,1,'      Начислено страховых взносов на ОПС: страховая часть                                                                                                                                                                                                     ')
INSERT #F VALUES (4,16,1,'                   накопительная часть                                                                                                                                                                                                                        ')
INSERT #F VALUES (4,17,1,'      Начислено страховых взносов на ОМС: ФФОМС                                                                                                                                                                                                               ')
INSERT #F VALUES (4,18,1,'                   ТФОМС                                                                                                                                                                                                                                      ')
INSERT #F VALUES (4,19,1,'По ЕНВД: Сумма выплат и иных вознаграждений, начисленных в пользу физ: всего (с. 351 + с. 352)')
INSERT #F VALUES (4,20,1,'                   1966 г.р. и старше                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,21,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,22,1,'      Суммы, не подлежащие обложению страховыми взносами в соответствии с ч. 1, ч. 2 ст. 9: всего (с. 361 + с. 362)')
INSERT #F VALUES (4,23,1,'                   1966 г.р. и старше                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,24,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,25,1,'      Суммы, превышающие предельную величину базы для начисления страх. взн. (ст. 8): всего (с. 364 + с. 365)')
INSERT #F VALUES (4,26,1,'                   1966 г.р. и старше                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,27,1,'                   1967 г.р. и моложе                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,28,1,'       База для начисления страх. взн. на ОПС: 1966 г.р. и старше (с. 351 - с. 361 - с. 364)')
INSERT #F VALUES (4,29,1,'                   1967 г.р. и моложе (с. 352 - с. 362 - с. 365)')
INSERT #F VALUES (4,30,1,'       База для начисления страховых взносов на ОМС: (с. 350 - с. 360 - с. 363)')
INSERT #F VALUES (4,31,1,'       Начислено страх. взн. на ОПС: страховая часть                                                                                                                                                                                                          ')
INSERT #F VALUES (4,32,1,'                    накопительная часть                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,33,1,'       Начислено страх. взн. на ОМС: ФФОМС                                                                                                                                                                                                                    ')
INSERT #F VALUES (4,34,1,'                   ТФОМС                                                                                                                                                                                                                                      ')
INSERT #F VALUES (4,1,2,'300                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'301                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,3,2,'302                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,4,2,'310                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,5,2,'311                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,6,2,'312                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,7,2,'314                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,8,2,'315                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,9,2,'316                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,10,2,'317                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,11,2,'318                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,12,2,'320                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,13,2,'321                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,14,2,'330                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,15,2,'341                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,16,2,'342                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,17,2,'343                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,18,2,'344                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,19,2,'350                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,20,2,'351                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,21,2,'352                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,22,2,'360                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,23,2,'361                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,24,2,'362                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,25,2,'363                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,26,2,'364                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,27,2,'365                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,28,2,'370                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,29,2,'371                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,30,2,'380                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,31,2,'391                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,32,2,'392                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,33,2,'393                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,34,2,'394                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,23,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,26,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,27,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,31,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,32,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,33,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,34,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,23,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,26,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,27,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,31,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,32,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,33,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,34,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,23,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,26,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,27,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,31,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,32,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,33,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,34,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,23,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,26,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,27,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,31,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,32,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,33,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,34,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,1,1,'I. Для общественных организаций инвалидов: Численность членов организации, всего (чел.)')
INSERT #F VALUES (6,2,1,'         из них численность инвалидов и их законных представителей (чел.)')
INSERT #F VALUES (6,3,1,'   Удельный вес, % (с. 422 / с. 421) х 100')
INSERT #F VALUES (6,4,1,'II. Для орг., уставный капитал которых полностью состоит из вкладов общ-ых орг. инв.: Среднесписочная численность, всего (чел.)
')
INSERT #F VALUES (6,5,1,'        из них: среднесписочная численность инвалидов (чел.')
INSERT #F VALUES (6,6,1,'   Удельный вес, % (с. 425 / с. 424) х 100')
INSERT #F VALUES (6,7,1,'   Фонд оплаты труда, всего (руб.)')
INSERT #F VALUES (6,8,1,'        из них:  заработная плата инвалидов (руб.)')
INSERT #F VALUES (6,9,1,'   Удельный вес заработной платы инвалидов, % (с. 428 / с. 427) х 100')
INSERT #F VALUES (6,1,2,'421                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,2,2,'422                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,3,2,'423                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,4,2,'424                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,5,2,'425                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,6,2,'426                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,7,2,'427                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,8,2,'428                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (6,9,2,'429                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,1,1,'Сумма доходов, определяемая в соответствии
со ст. 248 Налогового кодекса Российской Федерации, всего')
INSERT #F VALUES (7,2,1,'из них:
сумма доходов, определяемая в целях применения
п. 2 ч. 2.1 или п. 2 ч. 2.2 ст. 57 Федерального закона
от 24 июля 2009 г. № 212-ФЗ')
INSERT #F VALUES (7,3,1,'доля доходов, определяемая в целях применения
п. 2 ч. 2.1 или п. 2 ч. 2.2 ст. 57 Федерального закона
от 24 июля 2009 г. № 212-ФЗ
(стр. 431 / стр. 430) х 100 (%)')
INSERT #F VALUES (7,4,1,'Средняя численность работников */среднесписочная численность работников ** (чел.)')
INSERT #F VALUES (7,5,1,'Сведения о выписке из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий ***                                                                                                                                ')
INSERT #F VALUES (7,1,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,2,2,'431                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,3,2,'432                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,4,2,'433                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,5,2,'434                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (7,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (7,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (7,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (7,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (7,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (7,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (7,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (7,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,1,'Сумма доходов, определяемая в соответствии со ст. 346.15 
Налогового кодекса Российской Федерации, всего (руб.)')
INSERT #F VALUES (8,2,1,'из них:
сумма доходов, определяемая в целях применения ч. 1.4 ст. 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)')
INSERT #F VALUES (8,3,1,'Доля доходов, определяемая в целях применения ч. 1.4 ст. 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ
(стр. 436 / стр. 435) х 100 (%)')
INSERT #F VALUES (8,1,2,'435                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (8,2,2,'436                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (8,3,2,'437                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (9,1,1,'Остаток задолженности на начало расчетного периода (+) задолженность, (-) переплата')
INSERT #F VALUES (9,2,1,'Уплачено с начала расчетного периода')
INSERT #F VALUES (9,3,1,'Остаток задолженности на конец отчетного периода (+) задолженность, (-) переплата')
INSERT #F VALUES (9,1,2,'510                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (9,2,2,'520                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (9,3,2,'530                                                                                                                                                                                                                                                       ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 341
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.114гр.3 =  т.2стр.111гр.3 +  т.2стр.112гр.3 +  т.2стр.113гр.3',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.114гр.4 =  т.2стр.111гр.4 +  т.2стр.112гр.4 +  т.2стр.113гр.4',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.114гр.5 =  т.2стр.111гр.5 +  т.2стр.112гр.5 +  т.2стр.113гр.5',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.114гр.6 =  т.2стр.111гр.6 +  т.2стр.112гр.6 +  т.2стр.113гр.6',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.130гр.3 =  т.2стр.100гр.3 +  т.2стр.110гр.3 +  т.2стр.120гр.3',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.130гр.4 =  т.2стр.100гр.4 +  т.2стр.110гр.4 +  т.2стр.120гр.4',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.130гр.5 =  т.2стр.100гр.5 +  т.2стр.110гр.5 +  т.2стр.120гр.5',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.130гр.6 =  т.2стр.100гр.6 +  т.2стр.110гр.6 +  т.2стр.120гр.6',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.144гр.3 =  т.2стр.141гр.3 +  т.2стр.142гр.3 +  т.2стр.143гр.3',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.144гр.4 =  т.2стр.141гр.4 +  т.2стр.142гр.4 +  т.2стр.143гр.4',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.144гр.6 =  т.2стр.141гр.6 +  т.2стр.142гр.6 +  т.2стр.143гр.6',1,11,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.3стр.200гр.3 =  т.3стр.201гр.3 +  т.3стр.202гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.3стр.200гр.4 =  т.3стр.201гр.4 +  т.3стр.202гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.3стр.200гр.5 =  т.3стр.201гр.5 +  т.3стр.202гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.3стр.200гр.6 =  т.3стр.201гр.6 +  т.3стр.202гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.3стр.210гр.3 =  т.3стр.211гр.3 +  т.3стр.212гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.3стр.210гр.4 =  т.3стр.211гр.4 +  т.3стр.212гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.3стр.210гр.5 =  т.3стр.211гр.5 +  т.3стр.212гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.3стр.210гр.6 =  т.3стр.211гр.6 +  т.3стр.212гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.3стр.216гр.3 =  т.3стр.217гр.3 +  т.3стр.218гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.3стр.216гр.4 =  т.3стр.217гр.4 +  т.3стр.218гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.3стр.216гр.5 =  т.3стр.217гр.5 +  т.3стр.218гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.3стр.216гр.6 =  т.3стр.217гр.6 +  т.3стр.218гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.3стр.220гр.3 =  т.3стр.201гр.3 -  т.3стр.211гр.3 -  т.3стр.214гр.3 -  т.3стр.217гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.3стр.220гр.4 =  т.3стр.201гр.4 -  т.3стр.211гр.4 -  т.3стр.214гр.4 -  т.3стр.217гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.3стр.220гр.5 =  т.3стр.201гр.5 -  т.3стр.211гр.5 -  т.3стр.214гр.5 -  т.3стр.217гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.3стр.220гр.6 =  т.3стр.201гр.6 -  т.3стр.211гр.6 -  т.3стр.214гр.6 -  т.3стр.217гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.3стр.221гр.3 =  т.3стр.202гр.3 -  т.3стр.212гр.3 -  т.3стр.215гр.3 -  т.3стр.218гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.3стр.221гр.4 =  т.3стр.202гр.4 -  т.3стр.212гр.4 -  т.3стр.215гр.4 -  т.3стр.218гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.3стр.221гр.5 =  т.3стр.202гр.5 -  т.3стр.212гр.5 -  т.3стр.215гр.5 -  т.3стр.218гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.3стр.221гр.6 =  т.3стр.202гр.6 -  т.3стр.212гр.6 -  т.3стр.215гр.6 -  т.3стр.218гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.3стр.230гр.3 =  т.3стр.200гр.3 -  т.3стр.210гр.3 -  т.3стр.216гр.3',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.3стр.230гр.4 =  т.3стр.200гр.4 -  т.3стр.210гр.4 -  т.3стр.216гр.4',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.3стр.230гр.5 =  т.3стр.200гр.5 -  т.3стр.210гр.5 -  т.3стр.216гр.5',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.3стр.230гр.6 =  т.3стр.200гр.6 -  т.3стр.210гр.6 -  т.3стр.216гр.6',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.4стр.300гр.3 =  т.4стр.301гр.3 +  т.4стр.302гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.4стр.300гр.4 =  т.4стр.301гр.4 +  т.4стр.302гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.4стр.300гр.5 =  т.4стр.301гр.5 +  т.4стр.302гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.4стр.300гр.6 =  т.4стр.301гр.6 +  т.4стр.302гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.4стр.310гр.3 =  т.4стр.311гр.3 +  т.4стр.312гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.4стр.310гр.4 =  т.4стр.311гр.4 +  т.4стр.312гр.4',1,0,1,'20100419','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.4стр.310гр.5 =  т.4стр.311гр.5 +  т.4стр.312гр.5',1,0,1,'20100419','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.4стр.310гр.6 =  т.4стр.311гр.6 +  т.4стр.312гр.6',1,0,1,'20100419','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.4стр.316гр.3 =  т.4стр.317гр.3 +  т.4стр.318гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.4стр.316гр.4 =  т.4стр.317гр.4 +  т.4стр.318гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.4стр.316гр.5 =  т.4стр.317гр.5 +  т.4стр.318гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.4стр.316гр.6 =  т.4стр.317гр.6 +  т.4стр.318гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.4стр.320гр.3 =  т.4стр.301гр.3 -  т.4стр.311гр.3 -  т.4стр.314гр.3 -  т.4стр.317гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.4стр.320гр.4 =  т.4стр.301гр.4 -  т.4стр.311гр.4 -  т.4стр.314гр.4 -  т.4стр.317гр.4',1,0,1,'20100514','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.4стр.320гр.5 =  т.4стр.301гр.5 -  т.4стр.311гр.5 -  т.4стр.314гр.5 -  т.4стр.317гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.4стр.320гр.6 =  т.4стр.301гр.6 -  т.4стр.311гр.6 -  т.4стр.314гр.6 -  т.4стр.317гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.4стр.321гр.3 =  т.4стр.302гр.3 -  т.4стр.312гр.3 -  т.4стр.315гр.3 -  т.4стр.318гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.4стр.321гр.4 =  т.4стр.302гр.4 -  т.4стр.312гр.4 -  т.4стр.315гр.4 -  т.4стр.318гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.4стр.321гр.5 =  т.4стр.302гр.5 -  т.4стр.312гр.5 -  т.4стр.315гр.5 -  т.4стр.318гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.4стр.321гр.6 =  т.4стр.302гр.6 -  т.4стр.312гр.6 -  т.4стр.315гр.6 -  т.4стр.318гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.4стр.330гр.3 =  т.4стр.300гр.3 -  т.4стр.310гр.3 -  т.4стр.316гр.3',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.4стр.330гр.4 =  т.4стр.300гр.4 -  т.4стр.310гр.4 -  т.4стр.316гр.4',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.4стр.330гр.5 =  т.4стр.300гр.5 -  т.4стр.310гр.5 -  т.4стр.316гр.5',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.4стр.330гр.6 =  т.4стр.300гр.6 -  т.4стр.310гр.6 -  т.4стр.316гр.6',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.4стр.350гр.3 =  т.4стр.351гр.3 +  т.4стр.352гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.4стр.350гр.4 =  т.4стр.351гр.4 +  т.4стр.352гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.4стр.350гр.5 =  т.4стр.351гр.5 +  т.4стр.352гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.4стр.350гр.6 =  т.4стр.351гр.6 +  т.4стр.352гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.4стр.360гр.3 =  т.4стр.361гр.3 +  т.4стр.362гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.4стр.360гр.4 =  т.4стр.361гр.4 +  т.4стр.362гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.4стр.360гр.5 =  т.4стр.361гр.5 +  т.4стр.362гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.4стр.360гр.6 =  т.4стр.361гр.6 +  т.4стр.362гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.4стр.363гр.3 =  т.4стр.364гр.3 +  т.4стр.365гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.4стр.363гр.4 =  т.4стр.364гр.4 +  т.4стр.365гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.4стр.363гр.5 =  т.4стр.364гр.5 +  т.4стр.365гр.5',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.4стр.363гр.6 =  т.4стр.364гр.6 +  т.4стр.365гр.6',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.4стр.370гр.3 =  т.4стр.351гр.3 -  т.4стр.361гр.3 -  т.4стр.364гр.3',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.4стр.370гр.4 =  т.4стр.351гр.4 -  т.4стр.361гр.4 -  т.4стр.364гр.4',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.4стр.370гр.5 =  т.4стр.351гр.5 -  т.4стр.361гр.5 -  т.4стр.364гр.5',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.4стр.370гр.6 =  т.4стр.351гр.6 -  т.4стр.361гр.6 -  т.4стр.364гр.6',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.4стр.371гр.3 =  т.4стр.352гр.3 -  т.4стр.362гр.3 -  т.4стр.365гр.3',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.4стр.371гр.4 =  т.4стр.352гр.4 -  т.4стр.362гр.4 -  т.4стр.365гр.4',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'т.4стр.371гр.5 =  т.4стр.352гр.5 -  т.4стр.362гр.5 -  т.4стр.365гр.5',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.4стр.371гр.6 =  т.4стр.352гр.6 -  т.4стр.362гр.6 -  т.4стр.365гр.6',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.4стр.380гр.3 =  т.4стр.350гр.3 -  т.4стр.360гр.3 -  т.4стр.363гр.3',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.4стр.380гр.4 =  т.4стр.350гр.4 -  т.4стр.360гр.4 -  т.4стр.363гр.4',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.4стр.380гр.5 =  т.4стр.350гр.5 -  т.4стр.360гр.5 -  т.4стр.363гр.5',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.4стр.380гр.6 =  т.4стр.350гр.6 -  т.4стр.360гр.6 -  т.4стр.363гр.6',1,1,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.5стр.423гр.3 =  т.5стр.422гр.3 /  т.5стр.421гр.3 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.5стр.423гр.4 =  т.5стр.422гр.4 /  т.5стр.421гр.4 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.5стр.423гр.5 =  т.5стр.422гр.5 /  т.5стр.421гр.5 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.5стр.423гр.6 =  т.5стр.422гр.6 /  т.5стр.421гр.6 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.5стр.426гр.3 =  т.5стр.425гр.3 /  т.5стр.424гр.3 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.5стр.426гр.4 =  т.5стр.425гр.4 /  т.5стр.424гр.4 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.5стр.426гр.5 =  т.5стр.425гр.5 /  т.5стр.424гр.5 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.5стр.426гр.6 =  т.5стр.425гр.6 /  т.5стр.424гр.6 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.5стр.429гр.3 =  т.5стр.428гр.3 /  т.5стр.427гр.3 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(94,NULL,0,NULL,94,7,0,0,0,'т.5стр.429гр.4 =  т.5стр.428гр.4 /  т.5стр.427гр.4 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(95,NULL,0,NULL,95,7,0,0,0,'т.5стр.429гр.5 =  т.5стр.428гр.5 /  т.5стр.427гр.5 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(96,NULL,0,NULL,96,7,0,0,0,'т.5стр.429гр.6 =  т.5стр.428гр.6 /  т.5стр.427гр.6 *  100',1,0,1,'20100330','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(97,NULL,0,NULL,97,7,0,0,0,'т.2стр.110гр.3 =  т.3стр.241гр.3 +  т.4стр.341гр.3 +  т.4стр.391гр.3',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(98,NULL,0,NULL,98,7,0,0,0,'т.2стр.110гр.4 =  т.3стр.242гр.3 +  т.4стр.342гр.3 +  т.4стр.392гр.3',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(99,NULL,0,NULL,99,7,0,0,0,'т.2стр.110гр.5 =  т.3стр.243гр.3 +  т.4стр.343гр.3 +  т.4стр.393гр.3',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(100,NULL,0,NULL,100,7,0,0,0,'т.2стр.110гр.6 =  т.3стр.244гр.3 +  т.4стр.344гр.3 +  т.4стр.394гр.3',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(101,NULL,0,NULL,101,7,0,0,0,'т.2стр.111гр.3 =  т.3стр.241гр.4 +  т.4стр.341гр.4 +  т.4стр.391гр.4',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(102,NULL,0,NULL,102,7,0,0,0,'т.2стр.111гр.4 =  т.3стр.242гр.4 +  т.4стр.342гр.4 +  т.4стр.392гр.4',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(103,NULL,0,NULL,103,7,0,0,0,'т.2стр.111гр.5 =  т.3стр.243гр.4 +  т.4стр.343гр.4 +  т.4стр.393гр.4',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(104,NULL,0,NULL,104,7,0,0,0,'т.2стр.111гр.6 =  т.3стр.244гр.4 +  т.4стр.344гр.4 +  т.4стр.394гр.4',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(105,NULL,0,NULL,105,7,0,0,0,'т.2стр.112гр.3 =  т.3стр.241гр.5 +  т.4стр.341гр.5 +  т.4стр.391гр.5',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(106,NULL,0,NULL,106,7,0,0,0,'т.2стр.112гр.4 =  т.3стр.242гр.5 +  т.4стр.342гр.5 +  т.4стр.392гр.5',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(107,NULL,0,NULL,107,7,0,0,0,'т.2стр.112гр.5 =  т.3стр.243гр.5 +  т.4стр.343гр.5 +  т.4стр.393гр.5',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(108,NULL,0,NULL,108,7,0,0,0,'т.2стр.112гр.6 =  т.3стр.244гр.5 +  т.4стр.344гр.5 +  т.4стр.394гр.5',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(109,NULL,0,NULL,109,7,0,0,0,'т.2стр.113гр.3 =  т.3стр.241гр.6 +  т.4стр.341гр.6 +  т.4стр.391гр.6',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(110,NULL,0,NULL,110,7,0,0,0,'т.2стр.113гр.4 =  т.3стр.242гр.6 +  т.4стр.342гр.6 +  т.4стр.392гр.6',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(111,NULL,0,NULL,111,7,0,0,0,'т.2стр.113гр.5 =  т.3стр.243гр.6 +  т.4стр.343гр.6 +  т.4стр.393гр.6',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(112,NULL,0,NULL,112,7,0,0,0,'т.2стр.113гр.6 =  т.3стр.244гр.6 +  т.4стр.344гр.6 +  т.4стр.394гр.6',1,10,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(113,NULL,0,NULL,113,7,0,0,0,'т.6стр.530гр.3 =  т.6стр.510гр.3 -  т.6стр.520гр.3',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(114,NULL,0,NULL,114,7,0,0,0,'т.6стр.530гр.4 =  т.6стр.510гр.4 -  т.6стр.520гр.4',1,0,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(115,NULL,0,NULL,115,7,0,0,0,'т.2стр.150гр.3 =  т.2стр.130гр.3 -  т.2стр.140гр.3',1,12,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(116,NULL,0,NULL,116,7,0,0,0,'т.2стр.150гр.4 =  т.2стр.130гр.4 -  т.2стр.140гр.4',1,12,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(117,NULL,0,NULL,117,7,0,0,0,'т.2стр.150гр.5 =  т.2стр.130гр.5 -  т.2стр.140гр.5',1,12,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(118,NULL,0,NULL,118,7,0,0,0,'т.2стр.150гр.6 =  т.2стр.130гр.6 -  т.2стр.140гр.6',1,12,1,'20100330','','','','РСВ-1','20110101','','=',1,'')
INSERT #A VALUES(119,NULL,0,NULL,119,7,0,0,0,'т.7стр.432гр.3 =  т.7стр.431гр.3*100 /  т.7стр.430гр.3',1,0,1,'20110325','','','','РСВ-1','20110101','','=',0,'')
INSERT #A VALUES(120,NULL,0,NULL,120,7,0,0,0,'т.8стр.437гр.3 =  т.8стр.436гр.3*100 /  т.8стр.435гр.3',1,0,1,'20110325','','','','РСВ-1','20110101','','=',0,'')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 120
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','200','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','200','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','200','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','200','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','210','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','210','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','210','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','210','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','216','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','216','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','216','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','216','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','220','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','214','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','220','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','214','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','220','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','214','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','220','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','214','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','217','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','221','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','221','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','221','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','221','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','218','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','230','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','216','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','230','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','216','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','230','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','216','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','230','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','216','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','300','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','300','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','300','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','300','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','310','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','310','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','310','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','310','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','316','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','316','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','316','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','316','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','320','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','314','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','320','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','314','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','320','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','314','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','320','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','301','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','311','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','314','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','317','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','321','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','315','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','321','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','315','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','321','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','315','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','321','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','302','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','312','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','315','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','318','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','330','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','300','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','316','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','330','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','300','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','316','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','330','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','300','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','316','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','330','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','300','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','316','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','350','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','350','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','360','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','360','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','360','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','360','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','363','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','363','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','363','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','370','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','370','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','370','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','370','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','351','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','361','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','364','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','371','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','371','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','371','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','371','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','352','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','362','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','365','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','380','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','350','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','360','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','380','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','360','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','363','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','380','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','360','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','363','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','380','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','350','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','360','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','363','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','423','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','422','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','421','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','423','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','422','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','421','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','423','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','422','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','421','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','423','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','422','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','421','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','426','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','425','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','424','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','426','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','425','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','424','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','426','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','425','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','424','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','426','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','425','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','424','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','429','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','428','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','427','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','429','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','428','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','427','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','429','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','428','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','427','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','429','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','428','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','427','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','241','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','341','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','391','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','242','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','342','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','392','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','243','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','343','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','393','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','244','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','344','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','394','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','241','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','341','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','391','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','242','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','342','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','392','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','243','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','343','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','393','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','244','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','344','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','394','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','241','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','341','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','391','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','242','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','342','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','392','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','243','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','343','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','393','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','244','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','344','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','394','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','241','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','341','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','391','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','242','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','342','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','392','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','243','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','343','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','393','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','244','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','344','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','394','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','530','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','510','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','520','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','530','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','510','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','520','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','432','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(119,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','431','7',NULL,NULL,'',1,NULL,100,'*100',0)
INSERT #B VALUES(119,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','430','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(120,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','437','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(120,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','436','8',NULL,NULL,'',1,NULL,100,'*100',0)
INSERT #B VALUES(120,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','435','8',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) <> 452
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2012-02-01 15:42:41.400',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 = '2012-02-01 15:42:41.400'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2012-02-01 15:42:41.400. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

-- Загрузить подсказку.
DECLARE @iLINK_FORM INT
SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo
if object_id('tempdb..#F1') is NOT NULL drop table #r_files
create table #F1 (ID int, Name varchar(254), Path varchar(254), CreateDate datetime, FileSize int)
if object_id('tempdb..#F2') is NOT NULL drop table #r_fileparts
create table #F2 (File_ID int, Orders int, Body varchar(8000))
insert #F1 (ID, Name, Path, CreateDate, FileSize) values(116,'ФОРМА РСВ-1.MHT', 'C:\ОБЩАЯ\!LEXA', convert(datetime, '2011-04-05 08:17:00.000', 121), 42029)
insert #F2 (File_ID, Orders, Body) values(116,1, 'MIME-Version: 1.0
Content-Type: multipart/related; boundary="----=_NextPart_01CBF369.D8C55DC0"

Данный документ является веб-страницей в одном файле, также называемой файлом веб-архива. Если вы видите это сообщение, значит, данный обозреватель или редактор не поддерживает файлы веб-архива. Загрузите обозреватель, поддерживающий веб-архивы, например Windows® Internet Explorer®.

------=_NextPart_01CBF369.D8C55DC0
Content-Location: file:///C:/8E20CDD1/file4513.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="us-ascii"

<html xmlns:v=3D"urn:schemas-microsoft-com:vml"
xmlns:o=3D"urn:schemas-microsoft-com:office:office"
xmlns:w=3D"urn:schemas-microsoft-com:office:word"
xmlns:m=3D"http://schemas.microsoft.com/office/2004/12/omml"
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=3DContent-Type content=3D"text/html; charset=3Dus-ascii">
<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 12">
<meta name=3DOriginator content=3D"Microsoft Word 12">
<link rel=3DFile-List href=3D"file4513.files/filelist.xml">
<!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Author>&#1055;&#1072;&#1074;&#1083;&#1086;&#1074;&#1072; &#1053;.&#105=
3;.</o:Author>
  <o:Template>Normal</o:Template>
  <o:LastAuthor>nadya</o:LastAuthor>
  <o:Revision>2</o:Revision>
  <o:TotalTime>64</o:TotalTime>
  <o:Created>2011-04-05T04:17:00Z</o:Created>
  <o:LastSaved>2011-04-05T04:17:00Z</o:LastSaved>
  <o:Pages>1</o:Pages>
  <o:Words>331</o:Words>
  <o:Characters>1887</o:Characters>
  <o:Company>&#1054;&#1054;&#1054; &quot;&#1050;&#1077;&#1081;&#1089;&#1080=
;&#1089;&#1090;&#1077;&#1084;&#1089;&quot;</o:Company>
  <o:Lines>15</o:Lines>
  <o:Paragraphs>4</o:Paragraphs>
  <o:CharactersWithSpaces>2214</o:CharactersWithSpaces>
  <o:Version>12.00</o:Version>
 </o:DocumentProperties>
</xml><![endif]-->
<link rel=3DthemeData href=3D"file4513.files/themedata.thmx">
<link rel=3DcolorSchemeMapping href=3D"file4513.files/colorschememapping.xm=
l">
<!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:Zoom>150</w:Zoom>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:TrackMoves>false</w:TrackMoves>
  <w:TrackFormatting/>
  <w:PunctuationKerning/>
  <w:ValidateAgainstSchemas/>
  <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
  <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
  <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
  <w:DoNotPromoteQF/>
  <w:LidThemeOther>RU</w:LidThemeOther>
  <w:LidThemeAsian>X-NONE</w:LidThemeAsian>
  <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:DontGrowAutofit/>
   <w:SplitPgBreakAndParaMark/>
   <w:DontVertAlignCellWithSp/>
   <w:DontBreakConstrainedForcedTables/>
   <w:DontVertAlignInTxbx/>
   <w:Word11KerningPairs/>
   <w:CachedColBalance/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
  <m:mathPr>
   <m:mathFont m:val=3D"Cambria Math"/>
   <m:brkBin m:val=3D"before"/>
   <m:brkBinSub m:val=3D"&#45;-"/>
   <m:smallFrac m:val=3D"off"/>
   <m:dispDef/>
   <m:lMargin m:val=3D"0"/>
   <m:rMargin m:val=3D"0"/>
   <m:defJc m:val=3D"centerGroup"/>
   <m:wrapIndent m:val=3D"1440"/>
   <m:intLim m:val=3D"subSup"/>
   <m:naryLim m:val=3D"undOvr"/>
  </m:mathPr></w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:LatentStyles DefLockedState=3D"false" DefUnhideWhenUsed=3D"false"
  DefSemiHidden=3D"false" DefQFormat=3D"false" LatentStyleCount=3D"267">
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"Normal"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"heading 1"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"heading 2"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 3"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 4"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 5"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 6"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 7"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 8"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"heading 9"/>
  <w:LsdException Locked=3D"false" SemiHidden=3D"true" UnhideWhenUsed=3D"tr=
ue"
   QFormat=3D"true" Name=3D"caption"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"Title"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" Name=3D"Default Paragraph=
 Font"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"Subtitle"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"Strong"/>
  <w:LsdException Locked=3D"false" QFormat=3D"true" Name=3D"Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"99" Name=3D"No List"/>
  <w:LsdException Locked=3D"false" Priority=3D"99" SemiHidden=3D"true"
   Name=3D"Placeholder Text"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" QFormat=3D"true" Name=3D"=
No Spacing"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"99" SemiHidden=3D"true" Name=
=3D"Revision"/>
  <w:LsdException Locked=3D"false" Priority=3D"34" QFormat=3D"true"
   Name=3D"List Paragraph"/>
  <w:LsdException Locked=3D"false" Priority=3D"29" QFormat=3D"true" Name=3D=
"Quote"/>
  <w:LsdException Locked=3D"')

insert #F2 (File_ID, Orders, Body) values(116,2, 'false" Priority=3D"30" QFormat=3D"true"
   Name=3D"Intense Quote"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" Name=3D"Light Shading Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" Name=3D"Light List Accen=
t 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" Name=3D"Light Grid Accen=
t 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" Name=3D"Medium Shading 1=
 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" Name=3D"Medium Shading 2=
 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" Name=3D"Medium List 1 Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" Name=3D"Medium List 2 Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" Name=3D"Medium Grid 1 Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" Name=3D"Medium Grid 2 Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" Name=3D"Medium Grid 3 Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" Name=3D"Dark List Accent=
 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" Name=3D"Colorful Shading=
 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" Name=3D"Colorful List Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" Name=3D"Colorful Grid Ac=
cent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"19" QFormat=3D"true"
   Name=3D"Subtle Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"21" QFormat=3D"true"
   Name=3D"Intense Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"31" QFormat=3D"true"
   Name=3D"Subtle Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"32" QFormat=3D"true"
   Name=3D"Intense Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"33" QFormat=3D"true" Name=3D=
"Book Title"')

insert #F2 (File_ID, Orders, Body) values(116,3, '/>
  <w:LsdException Locked=3D"false" Priority=3D"37" SemiHidden=3D"true"
   UnhideWhenUsed=3D"true" Name=3D"Bibliography"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" SemiHidden=3D"true"
   UnhideWhenUsed=3D"true" QFormat=3D"true" Name=3D"TOC Heading"/>
 </w:LatentStyles>
</xml><![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:"Cambria Math";
	panose-1:2 4 5 3 5 4 6 3 2 4;
	mso-font-charset:1;
	mso-generic-font-family:roman;
	mso-font-format:other;
	mso-font-pitch:variable;
	mso-font-signature:0 0 0 0 0 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman","serif";
	mso-fareast-font-family:"Times New Roman";}
h2
	{mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-link:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2 \0417\043D=
\0430\043A";
	mso-style-next:\041E\0431\044B\0447\043D\044B\0439;
	margin-top:12.0pt;
	margin-right:0cm;
	margin-bottom:3.0pt;
	margin-left:28.8pt;
	text-indent:-28.8pt;
	mso-pagination:widow-orphan;
	page-break-after:avoid;
	mso-outline-level:2;
	mso-list:l0 level2 lfo2;
	tab-stops:list 28.8pt;
	font-size:14.0pt;
	font-family:"Arial","sans-serif";
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-theme-font:minor-fareast;
	font-style:italic;}
span.2
	{mso-style-name:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2 \0417\043=
D\0430\043A";
	mso-style-unhide:no;
	mso-style-locked:yes;
	mso-style-link:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2";
	mso-ansi-font-size:13.0pt;
	mso-bidi-font-size:13.0pt;
	font-family:"Cambria","serif";
	mso-ascii-font-family:Cambria;
	mso-ascii-theme-font:major-latin;
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-theme-font:major-fareast;
	mso-hansi-font-family:Cambria;
	mso-hansi-theme-font:major-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:major-bidi;
	color:#4F81BD;
	mso-themecolor:accent1;
	font-weight:bold;}
p.1, li.1, div.1
	{mso-style-name:\0421\0442\0438\043B\044C1;
	mso-style-unhide:no;
	mso-style-parent:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2";
	mso-style-next:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2";
	margin-top:12.0pt;
	margin-right:0cm;
	margin-bottom:3.0pt;
	margin-left:0cm;
	mso-pagination:widow-orphan;
	page-break-after:avoid;
	mso-outline-level:2;
	font-size:14.0pt;
	font-family:"Times New Roman","serif";
	mso-fareast-font-family:"Times New Roman";
	mso-bidi-font-family:Arial;
	font-weight:bold;
	mso-bidi-font-style:italic;}
span.a
	{mso-style-name:"\041F\0443\0442\044C \043C\0435\043D\044E";
	mso-style-unhide:no;
	mso-ansi-font-size:12.0pt;
	border:none windowtext 1.0pt;
	mso-border-alt:none windowtext 0cm;
	padding:0cm;
	background:#BFBFBF;
	mso-shading:windowtext;
	mso-pattern:gray-25 auto;
	font-weight:bold;
	mso-bidi-font-weight:normal;}
span.a0
	{mso-style-name:"\0417\043D\0430\043A \0417\043D\0430\043A";
	mso-style-unhide:no;
	mso-ansi-font-size:12.0pt;
	mso-bidi-font-size:12.0pt;
	mso-ansi-language:RU;
	mso-fareast-language:RU;
	mso-bidi-language:AR-SA;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
.MsoChpDefault
	{mso-style-type:export-only;
	mso-default-props:yes;
	font-size:10.0pt;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;}
@page WordSection1
	{size:595.3pt 841.9pt;
	margin:2.0cm 42.5pt 2.0cm 3.0cm;
	mso-header-margin:35.4pt;
	mso-footer-margin:35.4pt;
	mso-paper-source:0;}
div.WordSection1
	{page:WordSection1;}
 /* List Definitions */
 @list l0
	{mso-list-id:371538955;
	mso-list-template-ids:-1845837826;}
@list l0:level1
	{mso-level-tab-stop:18.0pt;
	mso-level-number-position:left;
	margin-left:18.0pt;
	text-indent:-18.0pt;}
@list l0:level2
	{mso-level-style-link:"\0417\0430\0433\043E\043B\043E\0432\043E\043A 2";
	mso-level-text:"%1\.%2";
	mso-level-tab-stop:28.8pt;
	mso-level-number-position:left;
	margin-left:28.8pt;
	text-indent:-28.8pt;}
@list l0:level3
	{mso-level-text:"%1\.%2\.%3";
	mso-level-tab-stop:36.0pt;
	mso-level-number-position:left;
	margin-left:36.0pt;
	text-indent:-36.0pt;}
@list l0:level4
	{mso-level-text:"%1\.%2\.%3\.%4";
	mso-level-tab-stop:21.65pt;
	mso-level-number-position:left;
	margin-left:21.65pt;
	text-indent:-43.2pt;}
@list l0:level5
	{mso-level-text:"%1\.%2\.%3\.%4\.%5";
	mso-level-tab-stop:28.85pt;
	mso-level-number-position:left;
	margin-left:28.85pt;
	text-indent:-50.4pt;}
@list l0:level6
	{mso-level-text:"%1\.%2\.%3\.%4\.%5\.%6";
	mso-level-tab-stop:36.05pt;
	mso-level-number-position:left;
	margin-left:36.05pt;
	text-indent:-57.6pt;}
@list l0:level7
	{mso-level-text:"%1\.%2\.%3\.%4\.%5\.%6\.%7";
	mso-level-tab-stop:43.25pt;
	mso-level-number-position:left;
	margin-left:43.25pt;
	text-indent:-64.8pt;}
@list l0:level8
	{mso-level-text:"%1\.%2\.%3\.%4\.%5\.%6\.%7\.%8";
	mso-level-tab-stop:50.45pt;
	mso-level-number-position:left;
	margin-left:50.45pt;
	text-indent:-72.0pt;}
@list l0:level9
	{mso-level-text:"%1\.%2\.%3\.%4\.%5\.%6\.%7\.%8\.%9";
	mso-level-tab-stop:57.65pt;
	mso-level-number-position:left;
	margin-left:57.65pt;
	text-indent:-79.2pt;}
ol
	{margin-bottom:0cm;}
ul
	{margin-bottom:0cm;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"\041E\0431\044B\0447\043D\0430\044F \0442\0430\0431\043B\=
0438\0446\0430";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-qformat:yes;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin:0cm;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman","serif";}
</style>
<![endif]--><!--[if gte mso 9]><xml>
 <o:shapedefaults v:ext=3D"edit" spidmax=3D"3074"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <o:shapelayout v:ext=3D"edit">
  <o:idmap v:ext=3D"edit" data=3D"1"/>
 </o:shapelayout></xml><![endif]-->
</head>

<body lang=3DRU style=3D''tab-interval:35.4pt''>

<div class=3DWordSection1>

<p class=3DMsoNormal align=3Dcenter style=3D''text-align:center''><span
style=3D''font-size:14.0pt''>&#1056;&#1077;&#1082;&#1086;&#1084;&#1077;&#1085=
;&#1076;&#1072;&#1094;&#1080;&#1080;
&#1087;&#1086;
&#1079;&#1072;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1102;
&#1092;&#1086;&#1088;&#1084;&#1099; &#1056;&#1057;&#1042;-1.<o:p></o:p></sp=
an></p>

<p class=3DMsoNormal style=3D''text-align:justify''><span style=3D''font-size:=
14.0pt''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify''><span style=3D''font-size:=
14.0pt''>&#1047;&#1077;&#1083;&#1077;&#1085;&#1099;&#1084;
&#1094;&#1074;&#1077;&#1090;&#1086;&#1084;
&#1074;&#1099;&#1076;&#1077;&#1083;&#1077;&#1085;&#1099;
&#1080;&#1090;&#1086;&#1075;&#1086;&#1074;&#1099;&#1077;
&#1103;&#1095;&#1077;&#1081;&#1082;&#1080;.<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify''><span style=3D''font-size:=
14.0pt''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify''><b style=3D''mso-bidi-font=
-weight:
normal''><span style=3D''font-size:14.0pt''>&#1056;&#1072;&#1079;&#1076;&#1077=
;&#1083;
1 <o:p></o:p></span></b></p>

<p class=3DMsoNormal style=3D''')

insert #F2 (File_ID, Orders, Body) values(116,4, 'text-align:justify''><span style=3D''font-size:=
14.0pt''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
100 &#1075;&#1088;. 3 - <span class=3DGramE>&#1088;&#1072;&#1074;&#1085;&#1=
072;</span>
&#1086;&#1089;&#1090;&#1072;&#1090;&#1082;&#1091; &#1085;&#1072;
&#1089;&#1095;&#1077;&#1090;&#1077; 1.303.10 &#1085;&#1072;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
100 &#1075;&#1088;. 3 - <span class=3DGramE>&#1088;&#1072;&#1074;&#1085;&#1=
072;</span>
&#1086;&#1089;&#1090;&#1072;&#1090;&#1082;&#1091; &#1085;&#1072;
&#1089;&#1095;&#1077;&#1090;&#1077; 1.303.11 &#1085;&#1072;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
100 &#1075;&#1088;. 3 - <span class=3DGramE>&#1088;&#1072;&#1074;&#1085;&#1=
072;</span>
&#1086;&#1089;&#1090;&#1072;&#1090;&#1082;&#1091; &#1085;&#1072;
&#1089;&#1095;&#1077;&#1090;&#1077; 1.303.07 &#1085;&#1072;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
100 &#1075;&#1088;. 3 - <span class=3DGramE>&#1088;&#1072;&#1074;&#1085;&#1=
072;</span>
&#1086;&#1089;&#1090;&#1072;&#1090;&#1082;&#1091; &#1085;&#1072;
&#1089;&#1095;&#1077;&#1090;&#1077; 1.303.08 &#1085;&#1072;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
141(142,143) &#1075;&#1088;. 3 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1080;&#1079; &#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1086;&#1082;
&#1044;&#1077;&#1073;&#1077;&#1090; 303.10 &#1050;&#1088;&#1077;&#1076;&#10=
80;&#1090;
304.05(201.01, 201.11, 201.27). </p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
141(142,143) &#1075;&#1088;. 4 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1080;&#1079; &#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1086;&#1082;
&#1044;&#1077;&#1073;&#1077;&#1090; 303.11 &#1050;&#1088;&#1077;&#1076;&#10=
80;&#1090;
304.05(201.01, 201.11, 201.27).</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
141(142,143)<span style=3D''mso-spacerun:yes''>&nbsp; </span>&#1075;&#1088;. =
5 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1080;&#1079; &#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1086;&#1082; &#1=
044;&#1077;&#1073;&#1077;&#1090;
303.07 &#1050;&#1088;&#1077;&#1076;&#1080;&#1090; 304.05(201.01, 201.11, 20=
1.27).</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.
141(142,143)<span style=3D''mso-spacerun:yes''>&nbsp; </span>&#1075;&#1088;. =
6 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1080;&#1079; &#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1086;&#1082; &#1=
044;&#1077;&#1073;&#1077;&#1090;
303.08 &#1050;&#1088;&#1077;&#1076;&#1080;&#1090; 304.05(201.01, 201.11, 20=
1.27).
</p>

<p class=3DMsoNormal style=3D''text-align:justify''><o:p>&nbsp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify''><b style=3D''mso-bidi-font=
-weight:
normal''><span style=3D''font-size:14.0pt''>&#1056;&#1072;&#1079;&#1076;&#1077=
;&#1083;
2<o:p></o:p></span></b></p>

<p class=3DMsoNormal style=3D''text-align:justify''><b style=3D''mso-bidi-font=
-weight:
normal''><span style=3D''font-size:14.0pt''><o:p>&nbsp;</o:p></span></b></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.201(202)
&#1075;&#1088;.3 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1074;&#1089;&#1077;
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1089; &#1085;&#1072;&#1095;&#1072;&#1=
083;&#1072;
&#1075;&#1086;&#1076;&#1072; &#1080;&#1079;
&#1078;&#1091;&#1088;&#1085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1089;
&#1088;&#1072;&#1079;&#1073;&#1080;&#1074;&#1082;&#1086;&#1081; &#1087;&#10=
86;
&#1075;&#1086;&#1076;&#1091;
&#1088;&#1086;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><span
style=3D''mso-spacerun:yes''>&nbsp;</span>&#1057;&#1090;&#1088;.201(202)
&#1075;&#1088;.4,5,6 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1080;&#1079;
&#1078;&#1091;&#1088;&#1085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1089;
&#1088;&#1072;&#1079;&#1073;&#1080;&#1074;&#1082;&#1086;&#1081; &#1087;&#10=
86;
&#1075;&#1086;&#1076;&#1091;
&#1088;&#1086;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103; &#1079;&#1072;
&#1082;&#1072;&#1078;&#1076;&#1099;&#1081; &#1084;&#1077;&#1089;&#1103;&#10=
94;
&#1082;&#1074;&#1072;&#1088;&#1090;&#1072;&#1083;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.211(212,214,215)
&#1075;&#1088;.3 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099;,
&#1085;&#1077;&#1086;&#1073;&#1083;&#1072;&#1075;&#1072;&#1077;&#1084;&#109=
9;&#1077;
&#1089;&#1090;&#1088;&#1072;&#1093;&#1086;&#1074;&#1099;&#1084;&#1080;
&#1074;&#1079;&#1085;&#1086;&#1089;&#1072;&#1084;&#1080;, &#1089;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1072; &#1075;&#1086;&#1076;&#1072;
&#1080;&#1079; &#1078;&#1091;&#1088;&#1085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1089;
&#1088;&#1072;&#1079;&#1073;&#1080;&#1074;&#1082;&#1086;&#1081; &#1087;&#10=
86;
&#1075;&#1086;&#1076;&#1091;
&#1088;&#1086;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103;.
&#1057;&#1091;&#1084;&#1084;&#1099; <span class=3DGramE>&#1073;&#1086;&#108=
3;&#1100;&#1085;&#1080;&#1095;&#1085;&#1099;&#1093;</span>,
&#1084;&#1072;&#1090;&#1077;&#1088;&#1080;&#1072;&#1083;&#1100;&#1085;&#108=
6;&#1081;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1080; &#1074;
&#1088;&#1072;&#1079;&#1084;&#1077;&#1088;&#1077; 4000 &#1088;&#1091;&#1073=
;.
&#1080; &#1090;.&#1076;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.211(212,214,215)
&#1075;&#1088;.4,5,6 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099;,
&#1085;&#1077;&#1086;&#1073;&#1083;&#1072;&#1075;&#1072;&#1077;&#1084;&#109=
9;&#1077;
&#1089;&#1090;&#1088;&#1072;&#1093;&#1086;&#1074;&#1099;&#1084;&#1080;
&#1074;&#1079;&#1085;&#1086;&#1089;&#1072;&#1084;&#1080;, &#1080;&#1079;
&#1078;&#1091;&#1088;&#1085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1089;
&#1088;&#1072;&#1079;&#1073;&#1080;&#1074;&#1082;&#1086;&#1081; &#1087;&#10=
86;
&#1075;&#1086;&#1076;&#1091;
&#1088;&#1086;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103; &#1079;&#1072;
&#1082;&#1072;&#1078;&#1076;&#1099;&#1081; &#1084;&#1077;&#1089;&#1103;&#10=
94;
&#1082;&#1074;&#1072;&#')

insert #F2 (File_ID, Orders, Body) values(116,5, '1088;&#1090;&#1072;&#1083;&#1072;.
&#1057;&#1091;&#1084;&#1084;&#1099; <span class=3DGramE>&#1073;&#1086;&#108=
3;&#1100;&#1085;&#1080;&#1095;&#1085;&#1099;&#1093;</span>,
&#1084;&#1072;&#1090;&#1077;&#1088;&#1080;&#1072;&#1083;&#1100;&#1085;&#108=
6;&#1081;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1080; &#1080; &#1090;.&#1076;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.217(218)
&#1075;&#1088;.3 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099;,
&#1087;&#1088;&#1077;&#1074;&#1099;&#1096;&#1072;&#1102;&#1097;&#1080;&#107=
7;
&#1087;&#1088;&#1077;&#1076;&#1077;&#1083;&#1100;&#1085;&#1091;&#1102;
&#1074;&#1077;&#1083;&#1080;&#1095;&#1080;&#1085;&#1091; 463000
&#1088;&#1091;&#1073;&#1083;&#1077;&#1081;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1082;&#1072;&#1078;&#1076;&#1086;&#1084;&#1091;
&#1089;&#1086;&#1090;&#1088;&#1091;&#1076;&#1085;&#1080;&#1082;&#1091; &#10=
89;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1072; &#1075;&#1086;&#1076;&#1072;. </=
p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.217(218)
&#1075;&#1088;.4,5,6 -
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099;,
&#1087;&#1088;&#1077;&#1074;&#1099;&#1096;&#1072;&#1102;&#1097;&#1080;&#107=
7; &#1087;&#1088;&#1077;&#1076;&#1077;&#1083;&#1100;&#1085;&#1091;&#1102;
&#1074;&#1077;&#1083;&#1080;&#1095;&#1080;&#1085;&#1091; 463000
&#1088;&#1091;&#1073;&#1083;&#1077;&#1081;, &#1085;&#1072;&#1095;&#1080;&#1=
089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1082;&#1072;&#1078;&#1076;&#1086;&#1084;&#1091;
&#1089;&#1086;&#1090;&#1088;&#1091;&#1076;&#1085;&#1080;&#1082;&#1091; &#10=
89;
&#1088;&#1072;&#1079;&#1073;&#1080;&#1074;&#1082;&#1086;&#1081; &#1087;&#10=
86;
&#1084;&#1077;&#1089;&#1103;&#1094;&#1072;&#1084;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1057;&=
#1090;&#1088;.241,242,243,244
&#1075;&#1088;.3,4,5,6 &#8211;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1089;&#1090;&#1088;&#1072;&#1093;&#10=
86;&#1074;&#1099;&#1093;
&#1074;&#1079;&#1085;&#1086;&#1089;&#1086;&#1074; &#1080;&#1079;
&#1088;&#1077;&#1078;&#1080;&#1084;&#1072;
&laquo;&#1056;&#1072;&#1089;&#1095;&#1077;&#1090; &#1089;&#1090;&#1088;&#10=
72;&#1093;&#1086;&#1074;&#1099;&#1093;
&#1074;&#1079;&#1085;&#1086;&#1089;&#1086;&#1074;&raquo;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><b
style=3D''mso-bidi-font-weight:normal''><span style=3D''font-size:14.0pt;line-=
height:
150%''>&#1056;&#1072;&#1079;&#1076;&#1077;&#1083; 3 <o:p></o:p></span></b></=
p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1047;&=
#1072;&#1087;&#1086;&#1083;&#1085;&#1103;&#1077;&#1090;&#1089;&#1103;
&#1087;&#1086; &#1080;&#1085;&#1074;&#1072;&#1083;&#1080;&#1076;&#1072;&#10=
84;
&#1080; &#1087;&#1086;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072;&#1084;, &#1086;&#1073;&#1=
083;&#1072;&#1075;&#1072;&#1077;&#1084;&#1099;&#1084;
&#1045;&#1053;&#1042;&#1044;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1047;&=
#1072;&#1087;&#1086;&#1083;&#1085;&#1103;&#1077;&#1090;&#1089;&#1103;
&#1072;&#1085;&#1072;&#1083;&#1086;&#1075;&#1080;&#1095;&#1085;&#1086;
&#1056;&#1072;&#1079;&#1076;&#1077;&#1083;&#1091; 2.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><b
style=3D''mso-bidi-font-weight:normal''><span style=3D''font-size:14.0pt;line-=
height:
150%''>&#1056;&#1072;&#1079;&#1076;&#1077;&#1083; 4.1<o:p></o:p></span></b><=
/p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1047;&=
#1072;&#1087;&#1086;&#1083;&#1085;&#1103;&#1077;&#1090;&#1089;&#1103;
&#1087;&#1086; &#1082;&#1072;&#1078;&#1076;&#1086;&#1084;&#1091;
&#1080;&#1085;&#1074;&#1072;&#1083;&#1080;&#1076;&#1091;. </p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1060;&=
#1048;&#1054;,
&#1057;&#1087;&#1088;&#1072;&#1074;&#1082;&#1072;
&#1073;&#1077;&#1088;&#1091;&#1090;&#1089;&#1103; &#1080;&#1079;
&#1051;&#1080;&#1095;&#1085;&#1086;&#1081;
&#1082;&#1072;&#1088;&#1090;&#1086;&#1095;&#1082;&#1080; &#1089;&#1086;&#10=
90;&#1088;&#1091;&#1076;&#1085;&#1080;&#1082;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1043;&=
#1088;.5
- &#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1077;&#1090;&#1089;&#1103;
&#1086;&#1073;&#1097;&#1072;&#1103;
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1072;&#110=
3;
&#1089;&#1091;&#1084;&#1084;&#1072; &#1080;&#1079;
&#1078;&#1091;&#1088;&#1085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1087;&#1086;
&#1089;&#1086;&#1090;&#1088;&#1091;&#1076;&#1085;&#1080;&#1082;&#1091; &#10=
89;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1072; &#1075;&#1086;&#1076;&#1072;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''>&#1043;&=
#1088;.
6,7,8 &#8211;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1080;&#1079; &#1078;&#1091;&#1088;&#1=
085;&#1072;&#1083;&#1072;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1081; &#1087;&#1086;
&#1089;&#1086;&#1090;&#1088;&#1091;&#1076;&#1085;&#1080;&#1082;&#1091;
&#1079;&#1072; &#1082;&#1072;&#1078;&#1076;&#1099;&#1081;
&#1084;&#1077;&#1089;&#1103;&#1094;.</p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

<p class=3DMsoNormal style=3D''text-align:justify;line-height:150%''><o:p>&nb=
sp;</o:p></p>

</div>

</body>

</html>

------=_NextPart_01CBF369.D8C55DC0
Content-Location: file:///C:/8E20CDD1/file4513.files/themedata.thmx
Content-Transfer-Encoding: base64
Content-Type: application/vnd.ms-officetheme

UEsDBBQABgAIAAAAIQCCirwT+gAAABwCAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbKyRy2rDMBBF
94X+g9C22HK6KKXYzqJJd30s0g8Y5LEtao+ENAnJ33fsuFC6CC10IxBizpl7Va6P46AOGJPzVOlV
XmiFZH3jqKv0++4pu9cqMVADgyes9AmTXtfXV+XuFDApmaZU6Z45PBiTbI8jpNwHJHlpfRyB5Ro7
E8B+QIfmtijujPXESJzxxNB1+SoLRNegeoPILzCKx7Cg8Pv5DCSAmAtYq8czYVqi0hDC4CywRDAH
an7oM9+2zmLj7X4UaT6DF9jNBDO/XGD1P+ov5wZb2A+stkfp4lx/xCH9LdtSay6Tc/7Uu5AuGC6X
t7Rh5r+tPwEAAP//AwBQSwMEFAAGAAgAAAAhAKXWp+fAAAAANgEAAAsAAABfcmVscy8ucmVsc4SP
z2rDMAyH74W9g9F9UdLDGCV2L6WQQy+jfQDhKH9oIhvbG+vbT8cGCrsIhKTv96k9/q6L+eGU5yAW
mqoGw+JDP8to4XY9v3+CyYWkpyUIW3hwhqN727VfvFDRozzNMRulSLYwlRIPiNlPvFKuQmTRyRDS
SkXbNGIkf6eRcV/XH5ieGeA2TNP1FlLXN2Cuj6jJ/7PDMMyeT8F/ryzlRQRuN5RMaeRioagv41O9
kKhlqtQe0LW4+db9AQAA//8DA')

insert #F2 (File_ID, Orders, Body) values(116,6, 'FBLAwQUAAYACAAAACEAa3mWFoMAAACKAAAAHAAAAHRoZW1lL3Ro
ZW1lL3RoZW1lTWFuYWdlci54bWwMzE0KwyAQQOF9oXeQ2TdjuyhFYrLLrrv2AEOcGkHHoNKf29fl
44M3zt8U1ZtLDVksnAcNimXNLoi38Hwspxuo2kgcxSxs4ccV5ul4GMm0jRPfSchzUX0j1ZCFrbXd
INa1K9Uh7yzdXrkkaj2LR1fo0/cp4kXrKyYKAjj9AQAA//8DAFBLAwQUAAYACAAAACEAoLwYxrUG
AACDGwAAFgAAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWzsWc9uG0UYvyPxDqO9t7ETO42jOFXs2A20
aaPYLepxvB7vTjO7s5oZJ/WtSo9IIERBHKgEXDggIFKLuLTv4D5DoAiK1Ffgm5ldeyfekKSNoILm
EHtnf9//P/PNeOXy3YihXSIk5XHdK18seYjEPu/TOKh7N7vtC0sekgrHfcx4TOreiEjv8uq776zg
ZRWSiCCgj+UyrnuhUsny3Jz0YRnLizwhMbwbcBFhBY8imOsLvAd8IzY3XyotzkWYxh6KcQRsx9+M
fxo/GR+gG4MB9Ym3mvFvMRASK6kXfCY6mjvJiL5+tj8+GD8dPx4fPLsH35/C58eGtr9T1hRyJJtM
oF3M6h6I7vO9LrmrPMSwVPCi7pXMnze3ujKHl1Mipo6hzdG1zV9KlxL0d+aNTBH0JkLL7Urt0vqE
vwEwNYtrtVrNVnnCzwCw74PlVpc8z0p7qdzIeOZA9uss72apWqq4+Bz/hRmda41Go1pLdbFMDch+
rczgl0qLlbV5B29AFl+dwVcaa83mooM3IItfnMG3L9UWKy7egEJG450ZtA5ou51yn0AGnG0UwpcA
vlRK4VMUZMMk27SIAY/VaXMvwne4aAOBJmRY0RipUUIG2IdEb+KoJyjWAvEywbk3dsmXM0taNpK+
oImqe+8nGIpmyu/lk+9fPnmEDvcfH+7/fHj//uH+j5aRQ7WB4yBP9eLbT/58eA/98eirFw8+K8bL
PP7XHz785emnxUAop6k6zz8/+O3xwfMvPvr9uwcF8DWBe3l4l0ZEoutkD23zCAwzXnE1Jz1xNopu
iGmeYi0OJI6xllLAv6VCB319hFkaHUePBnE9eEtAOykCXhnecRTuhGKoaIHkq2HkADc5Zw0uCr1w
VcvKubk7jINi4WKYx21jvFsku4ljJ76tYQJ9NUtLx/BmSBw1txiOFQ5ITBTS7/gOIQXW3abU8esm
9QWXfKDQbYoamBa6pEt7TjZNiTZoBHEZFdkM8XZ8s3kLNTgrsnqd7LpIqArMCpTvEua48QoeKhwV
seziiOUdfg2rsEjJzkj4eVxLKoh0QBhHrT6RsojmhgB7c0G/iqGDFYZ9k40iFykU3SnieQ1znkeu
851miKOkCNuhcZjHvid3IEUx2uKqCL7J3QrRzxAHHB8b7luUOOE+uRvcpIGj0jRB9Juh0LGE1u10
4IjGf9eOGYV+bHPg/NoxNMDnXz4syKw3tRGvwZ5UVAkbR9rvcbijTbfJRZ+++T13HQ/jLQJpPrvx
vG25b1uu959vucfV82kb7bS3QtvVc4Mdks3IHJ16Yh5QxjpqxMg1aYZmCftGvw2Lmo85UJLJiSoJ
4Wva5x1cILChQYKrD6gKOyFOYOAue5pJIFPWgUQJl3DwM8uFvDUehnZlj41VfaCw/UFitcn7dnlB
L2fnhgkbs/sE5rCaCVrQDE4rbOFSyhTMfhVhZa3UqaWVjWqm9TnSJiZDTGdNg8WJN2EgQTDGgJcX
4UivRcNBBTPS1363e3EWFhOF8wyRDHGfpDHSds/GqGyClOWKuTmA3CmIkT4EnuC1nLSaZvsa0k4T
pLy4yjHisui9TpSyDJ5GSdfxkXJkcb44WYz26l6tOl/1kI+TujeAMy58jRKIutQzIGYB3CX5Sti0
P7GYTZVPo1nLDHOLoAzXGNbvMwY7fSARUq1jGdrUMK/SFGCxlmT1n6+CW8/LAJvpr6DFwhIkw7+m
BfjRDS0ZDIiv8sHOrWjf2ce0lfKhIqIT9vdQjw3FNobw61QFe/pUwlWF6Qj6Ae7ZtLfNK7c5p0WX
v90yOLuOWRLitN3qEs0q2cJNHU90ME859cC2Qt2NcWc3xZT8OZmST+P/mSl6P4Gbg4W+joAPN78C
I12vdY8LFXLoQklI/baAQcL0DsgWuKuF15BUcP9sPgXZ1Z+25iwPU9ZwAFTbNECCwn6kQkHIFrQl
k30nMCune5dlyVJGJqNy6srEqt0ju4R1dQ9c1Hu7h0JIddNN0jZgcEfzz31OK6gX6CEnX29OD5ns
vbYG/unJxxYzGOX2YTPQZP6fqFiwq1p6Q57tvXlD9IvpmFXJqgKE5baCWlr2r6jCGbda27FmLJ6v
ZspBFGcthsXJQJTA/Q/S/2D/o8Jn9pcMvaF2+Tb0VgQ/RGhmkDaQ1Rfs4IF0g7SLPRic7KJNJs3K
ujYdnbTXss36nCfdidwjztaanSbeZ3T2ZDhzxTm1eJ7OTj3s+NquHetqiOzREoWlQXawMYExv4Ll
f6XivTsQ6HW47x8yJU0ywW9OAsPo2TF1AMVvJRrS1b8AAAD//wMAUEsDBBQABgAIAAAAIQAN0ZCf
tgAAABsBAAAnAAAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5hZ2VyLnhtbC5yZWxzhI9NCsIw
FIT3gncIb2/TuhCRJt2I0K3UA4TkNQ02PyRR7O0NriwILodhvplpu5edyRNjMt4xaKoaCDrplXGa
wW247I5AUhZOidk7ZLBggo5vN+0VZ5FLKE0mJFIoLjGYcg4nSpOc0IpU+YCuOKOPVuQio6ZByLvQ
SPd1faDxmwF8xSS9YhB71QAZllCa/7P9OBqJZy8fFl3+UUFz2YUFKKLGzOAjm6pMBMpburrE3wAA
AP//AwBQSwECLQAUAAYACAAAACEAgoq8E/oAAAAcAgAAEwAAAAAAAAAAAAAAAAAAAAAAW0NvbnRl
bnRfVHlwZXNdLnhtbFBLAQItABQABgAIAAAAIQCl1qfnwAAAADYBAAALAAAAAAAAAAAAAAAAACsB
AABfcmVscy8ucmVsc1BLAQItABQABgAIAAAAIQBreZYWgwAAAIoAAAAcAAAAAAAAAAAAAAAAABQC
AAB0aGVtZS90aGVtZS90aGVtZU1hbmFnZXIueG1sUEsBAi0AFAAGAAgAAAAhAKC8GMa1BgAAgxsA
ABYAAAAAAAAAAAAAAAAA0QIAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWxQSwECLQAUAAYACAAAACEA
DdGQn7YAAAAbAQAAJwAAAAAAAAAAAAAAAAC6CQAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5h
Z2VyLnhtbC5yZWxzUEsFBgAAAAAFAAUAXQEAALUKAAAAAA==

------=_NextPart_01CBF369.D8C55DC0
Content-Location: file:///C:/8E20CDD1/file4513.files/colorschememapping.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml

<?xml version=3D"1.0" encoding=3D"UTF-8" standalone=3D"yes"?>
<a:clrMap xmlns:a=3D"http://schemas.openxmlformats.org/drawingml/2006/main"=
 bg1=3D"lt1" tx1=3D"dk1" bg2=3D"lt2" tx2=3D"dk2" accent1=3D"accent1" accent=
2=3D"accent2" accent3=3D"accent3" accent4=3D"accent4" accent5=3D"accent5" a=
ccent6=3D"accent6" hlink=3D"hlink" folHlink=3D"folHlink"/>
------=_NextPart_01CBF369.D8C55DC0
Content-Location: file:///C:/8E20CDD1/file4513.files/filelist.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml; charset="utf-8"

<xml xmlns:o=3D"urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef=3D"../file4513.htm"/>
 <o:File HRef=3D"themedata.thmx"/>
 <o:File HRef=3D"colorschememapping.xml"/>
 <o:File HRef=3D"filelist.xml"/>
</xml>
------=_NextPart_01CBF369.D8C55DC0--
')

IF (SELECT COUNT(*) FROM #F2) <> 6
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F2',0)
END
ELSE
	exec dbo.RO_IMPORT_FORM_HINT @iLINK_FORM
drop table #F1
drop table #F2


GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (апр 23 2012  4:21:02:833PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20120101
-- Дата окончания действия :
-- Версия : 2012-04-23 16:21:02.833
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'РСВ-1' AND [START_DATE] = '20120101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2012-04-23 16:21:02.833',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + 'РСВ-1',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = 'РСВ-1'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20120101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_rsv_1_pfr_2012()','RSV_1_PFR_2012.bas','','KirRepMakerMultiSheet.XLS','RSV-1-PFR_2012.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Титульный лист', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество застрахованных лиц',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Среднесписочная численность',@iLINK_TABLE,1,0,4,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Титульный лист', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Страховые взносы на ОПС: страховая часть',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на ОПС: накопительная часть',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы на ОМС',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.1. Сведения, необходимые для применения понижен', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата выдачи справки',@iLINK_TABLE,0,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.1. Сведения, необходимые для применения понижен', @iLINK_FORM,5, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_12_PFR_INV @dateBeginPeriod, @dateEndPeriod, @depLink, 7, 1',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.2. Расчет соотв. условий на право пониж тарифа', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.2. Расчет соотв. условий на право пониж тарифа', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'P3.3.Расчет для пониж. тарифа для организаций, уст', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'P3.3.Расчет для пониж. тарифа для организаций, уст', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.4. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре  аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.4. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.5. Соответствие условиям п.7 ч.1 ст. 58  № 212-', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Наименование вида экономической деятельности с указанием кода ОКВЭД',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Доходы по виду экономической деятельности',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Доля дох. и поступ по данному виду эконом деят-ти в общей сумме доходо',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Дата внесения в реестр СМИ',@iLINK_TABLE,1,1,6,6,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'№ записи в реестре СМИ',@iLINK_TABLE,1,1,7,7,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.5. Соответствие условиям п.7 ч.1 ст. 58  № 212-', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.6. Соответсвие условиям п.8 ч.1. ст.58 ФЗ № 212', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,0,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.6. Соответсвие условиям п.8 ч.1. ст.58 ФЗ № 212', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.7.Соответствие сведениям п. 11 ч. 1 ст. 58  № 2', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.7.Соответствие сведениям п. 11 ч. 1 ст. 58  № 2', @iLINK_FORM,11, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.8. Соответствие условиям п. 13 ч. 1 ст. 58 № 21', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата получения положительного заключения',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№',@iLINK_TABLE,1,1,6,6,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.8. Соответствие условиям п. 13 ч. 1 ст. 58 № 21', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.Суммы доначисленных страховых взносов с начала', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Период, за который выявлены и доначислены страховые взносы, год',@iLINK_TABLE,1,1,2,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Период, за который выявлены и доначислены страховые взносы, месяц',@iLINK_TABLE,1,0,3,2,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на обязательное пенсионное страхование, страховая час',@iLINK_TABLE,1,0,4,4,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


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.Суммы доначисленных страховых взносов с начала', @iLINK_FORM,13, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5.Сведения, необходимые для применения п.1 ч.3 чт', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия, имя, отчество обучающегося',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения из справки (номер, дата), подтверждающие членство в студенчес',@iLINK_TABLE,1,1,3,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения из справки (номер, дата), подтверждающие очную форму обучения',@iLINK_TABLE,1,1,4,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'в том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'в том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'в том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5.Сведения, необходимые для применения п.1 ч.3 чт', @iLINK_FORM,14, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5_2.Сведения, необходимые для прим п.1 ч.3 чт', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата записи в реестре',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'№ записи в реестре',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5_2.Сведения, необходимые для прим п.1 ч.3 чт', @iLINK_FORM,15, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (1,2,0,1)
INSERT #R VALUES (2,2,0,1)
INSERT #R VALUES (3,2,0,1)
INSERT #R VALUES (4,2,0,1)
INSERT #R VALUES (5,2,0,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,0,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,0,1)
INSERT #R VALUES (10,2,0,1)
INSERT #R VALUES (11,2,0,1)
INSERT #R VALUES (12,2,0,1)
INSERT #R VALUES (13,2,1,1)
INSERT #R VALUES (14,2,0,1)
INSERT #R VALUES (15,2,0,1)
INSERT #R VALUES (2,3,0,1)
INSERT #R VALUES (3,3,0,1)
INSERT #R VALUES (5,3,0,1)
INSERT #R VALUES (6,3,0,1)
INSERT #R VALUES (7,3,0,1)
INSERT #R VALUES (8,3,0,1)
INSERT #R VALUES (1,3,0,1)
INSERT #R VALUES (4,3,0,1)
INSERT #R VALUES (9,3,0,1)
INSERT #R VALUES (11,3,0,1)
INSERT #R VALUES (12,3,0,1)
INSERT #R VALUES (13,3,0,1)
INSERT #R VALUES (14,3,1,1)
INSERT #R VALUES (15,3,1,1)
INSERT #R VALUES (16,3,0,1)
INSERT #R VALUES (17,3,0,1)
INSERT #R VALUES (18,3,0,1)
INSERT #R VALUES (19,3,0,1)
INSERT #R VALUES (20,3,0,1)
INSERT #R VALUES (21,3,0,1)
INSERT #R VALUES (22,3,0,1)
INSERT #R VALUES (23,3,0,1)
INSERT #R VALUES (24,3,2,1)
INSERT #R VALUES (25,3,0,1)
INSERT #R VALUES (2,4,0,1)
INSERT #R VALUES (3,4,0,1)
INSERT #R VALUES (5,4,0,1)
INSERT #R VALUES (6,4,0,1)
INSERT #R VALUES (7,4,0,1)
INSERT #R VALUES (8,4,0,1)
INSERT #R VALUES (1,4,0,1)
INSERT #R VALUES (4,4,0,1)
INSERT #R VALUES (9,4,0,1)
INSERT #R VALUES (11,4,0,1)
INSERT #R VALUES (12,4,0,1)
INSERT #R VALUES (13,4,0,1)
INSERT #R VALUES (14,4,1,1)
INSERT #R VALUES (15,4,1,1)
INSERT #R VALUES (16,4,0,1)
INSERT #R VALUES (17,4,0,1)
INSERT #R VALUES (18,4,0,1)
INSERT #R VALUES (19,4,0,1)
INSERT #R VALUES (20,4,0,1)
INSERT #R VALUES (21,4,0,1)
INSERT #R VALUES (22,4,0,1)
INSERT #R VALUES (23,4,0,1)
INSERT #R VALUES (24,4,2,1)
INSERT #R VALUES (25,4,0,1)
INSERT #R VALUES (1,6,0,1)
INSERT #R VALUES (2,6,0,1)
INSERT #R VALUES (3,6,1,1)
INSERT #R VALUES (1,7,0,1)
INSERT #R VALUES (2,7,0,1)
INSERT #R VALUES (3,7,1,1)
INSERT #R VALUES (4,7,0,1)
INSERT #R VALUES (5,7,0,1)
INSERT #R VALUES (6,7,1,1)
INSERT #R VALUES (1,8,0,1)
INSERT #R VALUES (2,8,0,1)
INSERT #R VALUES (3,8,1,1)
INSERT #R VALUES (4,8,0,1)
INSERT #R VALUES (5,8,0,1)
INSERT #R VALUES (1,9,0,1)
INSERT #R VALUES (2,9,0,1)
INSERT #R VALUES (3,9,0,1)
INSERT #R VALUES (4,9,0,1)
INSERT #R VALUES (5,9,0,1)
INSERT #R VALUES (6,9,0,1)
INSERT #R VALUES (7,9,0,1)
INSERT #R VALUES (8,9,0,1)
INSERT #R VALUES (9,9,0,1)
INSERT #R VALUES (10,9,0,1)
INSERT #R VALUES (11,9,1,1)
INSERT #R VALUES (12,9,0,1)
INSERT #R VALUES (1,10,0,1)
INSERT #R VALUES (2,10,0,1)
INSERT #R VALUES (3,10,1,1)
INSERT #R VALUES (1,11,0,1)
INSERT #R VALUES (2,11,0,1)
INSERT #R VALUES (3,11,0,1)
INSERT #R VALUES (4,11,0,1)
INSERT #R VALUES (5,11,1,1)
INSERT #R VALUES (1,12,0,1)
INSERT #R VALUES (2,12,0,1)
INSERT #R VALUES (3,12,1,1)
INSERT #R VALUES (4,12,0,1)
INSERT #R VALUES (5,12,0,1)
INSERT #R VALUES (1,15,0,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 104
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Показатель                                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,1,3,'РСВ1_12_УСТАНОВКА() + РСВ1_ЗНАЧЕНИЕ(К.СТР.,1)')
INSERT #F VALUES (1,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,2)')
INSERT #F VALUES (2,1,1,'Остаток страховых взносов, подлежащих уплате на начало расчетного периода
(+) задолженность, (-) переплата                                                                                                                                                   ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов с начала расчетного периода                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,1,'в том числе за последние три месяца отчетного периода : 1 месяц                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'         3 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,6,1,'Итого подлежит уплате за последние 3 месяца (с.111 + с.112 + с.113)                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,1,'Доначислено страховых взносов с начала расчетного периода                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,1,'Всего к уплате (с. 100 + с. 110 + с. 120)                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,1,'Уплачено с начала расчетного периода                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,10,1,'в том числе за последние три месяца отчетного периода: 1 месяц                                                                                                                                                                                                ')
INSERT #F VALUES (2,11,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,12,1,'        3 месяц                                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,13,1,'        итого (с. 141 + с. 142 + с. 143)                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,14,1,'в том числе за предыдущие расчетные периоды                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,15,1,'Остаток страховых взносов, подлежащих уплате
на конец отчетного периода (с.130 - с.140) (+) задолженность, (-) переплата                                                                                                                                     ')
INSERT #F VALUES (2,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,2,2,'110                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,3,2,'111                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,4,2,'112                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,5,2,'113                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,6,2,'114                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,2,'120                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,2,'130                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,9,2,'140                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,2,'141                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,11,2,'142                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,12,2,'143                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,13,2,'144                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,14,2,'145                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,15,2,'150                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,1,3,'КТСН("_.303.10","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,4,'КТСН("_.303.11","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,5,'КТСН("_.303.07","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,9,5,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,10,5,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,11,5,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,12,5,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<=''263''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (3,1,1,'Сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц (ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ): 1966 г.р. и старше                                                                                                                                    ')
INSERT #F VALUES (3,2,1,'      1967 г.р. и моложе                                                                                                                                                                                                                                      ')
INSERT #F VALUES (3,3,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'Суммы, не подлежащие обложению страх. взн. (ч. 1, 2 ст. 9): 1966 г.р. и старше                                                                                                                                                                                ')
INSERT #F VALUES (3,5,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,6,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (3,7,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ : 1966 г.р. и старше: 1966 г.р. и старше                                                                                                ')
INSERT #F VALUES (3,8,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,11,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                        ')
INSERT #F VALUES (3,12,1,'        1967 г.р. и моложе                                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,13,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (3,14,1,'База для начисления страховых взносов на обязательное пенсионное страхование: 1966 г.р. и старше (с. 201+ с. 203 - с. 211 - с. 213 - с. 221 - с. 231 - с. 233)                                                                                                ')
INSERT #F VALUES (3,15,1,'       1967 г.р. и моложе (с. 202 - с. 212 - с. 222 - с. 232)                                                                                                                                                                                                 ')
INSERT #F VALUES (3,24,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 271 - с. 272 - ст. 273 - ст. 274)                                                                                                                                           ')
INSERT #F VALUES (3,16,1,'Начислено страховых взносов на обяза-тельное пенсионное страхование: страховая часть                                                                                                                                                                          ')
INSERT #F VALUES (3,17,1,'       накопительная часть                                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,25,1,'Начислено страховых взносов на обяза-тельное медицинское страхование                                                                                                                                                                                          ')
INSERT #F VALUES (3,18,1,'       с сумм, превышающих предельную величину базы                                                                                                                                                                                                           ')
INSERT #F VALUES (3,19,1,'Количество физических лиц, по которым величина базы превысила предел, установленный статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (чел.)                                                                                                          ')
INSERT #F VALUES (3,20,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                      ')
INSERT #F VALUES (3,21,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                                 ')
INSERT #F VALUES (3,22,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ                                                                                                                                         ')
INSERT #F VALUES (3,23,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (3,9,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (3,1,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,2,2,'202                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,3,2,'203                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,4,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,5,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,6,2,'213                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,2,'222                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,11,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,12,2,'232                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,13,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,14,2,'240                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,15,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,24,2,'275                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,16,2,'250                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,17,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,25,2,'276                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,18,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,19,2,'260                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,20,2,'271                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,21,2,'272                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,22,2,'273                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,23,2,'274                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,9,2,'223                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,23,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,23,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,23,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,23,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,2,1,'      1967 г.р. и моложе                                                                                                                                                                                                                                      ')
INSERT #F VALUES (4,3,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (4,5,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (4,6,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (4,7,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ : 1966 г.р. и старше: 1966 г.р. и старше                                                                                                ')
INSERT #F VALUES (4,8,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (4,1,1,'Сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц (ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ): 1966 г.р. и старше                                                                                                                                    ')
INSERT #F VALUES (4,4,1,'Суммы, не подлежащие обложению страх. взн. (ч. 1, 2 ст. 9): 1966 г.р. и старше                                                                                                                                                                                ')
INSERT #F VALUES (4,9,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (4,11,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                        ')
INSERT #F VALUES (4,12,1,'        1967 г.р. и моложе                                                                                                                                                                                                                                    ')
INSERT #F VALUES (4,13,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (4,14,1,'База для начисления страховых взносов на обязательное пенсионное страхование: 1966 г.р. и старше (с. 201+ с. 203 - с. 211 - с. 213 - с. 221 - с. 231 - с. 233)                                                                                                ')
INSERT #F VALUES (4,15,1,'       1967 г.р. и моложе (с. 202 - с. 212 - с. 222 - с. 232)                                                                                                                                                                                                 ')
INSERT #F VALUES (4,16,1,'Начислено страховых взносов на обяза-тельное пенсионное страхование: страховая часть                                                                                                                                                                          ')
INSERT #F VALUES (4,17,1,'       накопительная часть                                                                                                                                                                                                                                    ')
INSERT #F VALUES (4,18,1,'       с сумм, превышающих предельную величину базы                                                                                                                                                                                                           ')
INSERT #F VALUES (4,19,1,'Количество физических лиц, по которым величина базы превысила предел, установленный статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (чел.)                                                                                                          ')
INSERT #F VALUES (4,20,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                      ')
INSERT #F VALUES (4,21,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                                 ')
INSERT #F VALUES (4,22,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ                                                                                                                                         ')
INSERT #F VALUES (4,23,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (4,24,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 271 - с. 272 - ст. 273 - ст. 274)                                                                                                                                           ')
INSERT #F VALUES (4,25,1,'Начислено страховых взносов на обяза-тельное медицинское страхование                                                                                                                                                                                          ')
INSERT #F VALUES (4,2,2,'2020                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,3,2,'2030                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,5,2,'2120                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,6,2,'2130                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,7,2,'2210                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,8,2,'2220                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,1,2,'2010                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,4,2,'2110                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,9,2,'2230                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,11,2,'2310                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,12,2,'2320                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,13,2,'2330                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,14,2,'2400                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,15,2,'2410                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,16,2,'2500                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,17,2,'2510                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,18,2,'2520                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,19,2,'2600                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,20,2,'2710                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,21,2,'2720                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,22,2,'2730                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,23,2,'2740                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,24,2,'2750                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,25,2,'2760                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,23,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,23,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,23,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,23,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (6,2,1,'       из них: численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                      ')
INSERT #F VALUES (6,3,1,'Удельный вес численности инвалидов и их законных представителей в численности членов организации (%)
(с. 322 / с. 321) х 100                                                                                                                                 ')
INSERT #F VALUES (6,1,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,2,2,'322                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,3,2,'323                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,1,1,'Среднесписочная численность, всего (чел.)                                                                                                                                                                                                                     ')
INSERT #F VALUES (7,2,1,'          из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                ')
INSERT #F VALUES (7,3,1,'Удельный вес инвалидов в среднесписочной численности (%)                                                                                                                                                                                                      ')
INSERT #F VALUES (7,4,1,'Фонд оплаты труда, всего (в рублях)                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,5,1,'         из них: заработная плата инвалидов (в рублях)                                                                                                                                                                                                        ')
INSERT #F VALUES (7,6,1,'Удельный вес заработной платы инвалидов (%) (с. 335 / с. 334) х 100                                                                                                                                                                                           ')
INSERT #F VALUES (7,1,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,2,2,'332                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,3,2,'333                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,4,2,'334                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,5,2,'335                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,6,2,'336                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                           ')
INSERT #F VALUES (8,2,1,'           из них: сумма доходов, определяемая исходя из критериев, указанных в пункте 2 части 2.1 или пункте  2 части 2.2 статьи 57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                               ')
INSERT #F VALUES (8,3,1,'Доля доходов, определяемая в целях применения части 5 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 342 / с. 341) х 100                                                                                                                  ')
INSERT #F VALUES (8,4,1,'Средняя численность работников*/
среднесписочная численность работников**(чел.)                                                                                                                                                                              ')
INSERT #F VALUES (8,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий*                                                                                                                                             ')
INSERT #F VALUES (8,1,2,'341                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,2,2,'342                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,3,2,'343                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,4,2,'344                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,5,2,'345                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (8,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,1,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,2,1,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,3,1,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,4,1,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,5,1,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,6,1,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,7,1,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,8,1,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,9,1,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,10,1,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (9,12,1,'Сведения из реестра СМИ**                                                                                                                                                                                                                                     ')
INSERT #F VALUES (9,11,2,'Итого по всем видам деятельности                                                                                                                                                                                                                              ')
INSERT #F VALUES (9,1,3,'350a                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,2,3,'350b                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,3,3,'350c                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,4,3,'350d                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,5,3,'350e                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,6,3,'350f                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,7,3,'350g                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,8,3,'350h                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,9,3,'350j                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,10,3,'350k                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,11,3,'350l                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (9,12,3,'351                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (9,11,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,2,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,3,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,4,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,5,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,6,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,7,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,8,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,9,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,10,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,11,6,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,1,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,2,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,3,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,4,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,5,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,6,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,7,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,8,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,9,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,10,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (9,11,7,'ЗАПРЕТ()                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (10,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                        ')
INSERT #F VALUES (10,2,1,'из них: сумма доходов, определяемая  в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                                                                        ')
INSERT #F VALUES (10,3,1,'Доля доходов, определяемая  в целях применения части 1.4  статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 362 / с. 361) х 100                                                                                                              ')
INSERT #F VALUES (10,1,2,'361                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,2,2,'362                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,3,2,'363                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,1,1,'Сумма доходов, всего (в рублях)                                                                                                                                                                                                                               ')
INSERT #F VALUES (11,2,1,'из них: сумма доходов в виде целевых поступлений на содержание некоммерческих организаций и ведение ими уставной деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                    ')
INSERT #F VALUES (11,3,1,'сумма доходов в виде грантов, получаемых для осуществления деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ, определяемых в соответствии с подпунктом 14 пункта 1 статьи 251                         ')
INSERT #F VALUES (11,4,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах р - ф, я.4 - я.6 пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. 
№ 212-ФЗ (в рублях)                                                              ')
INSERT #F VALUES (11,5,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 372 + с. 373 + с.374) / с. 371 х 100                                                                                               ')
INSERT #F VALUES (11,1,2,'371                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,2,2,'372                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,2,'373                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,4,2,'374                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,5,2,'375                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                           ')
INSERT #F VALUES (12,2,1,'из них: сумма доходов от реализации инжиниринговых услуг, определяемая в целях применения пункта 1 части 5.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                             ')
INSERT #F VALUES (12,3,1,'Доля доходов, определяемая в целях применения пункта 1 части 5.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 382 / с. 381) х 100                                                                                                       ')
INSERT #F VALUES (12,4,1,'Средняя численность работников (чел.)                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,5,1,'Сведения о получении положительного заключения экспертного совета по технико-внедренческим особым экономическим зонам*                                                                                                                                        ')
INSERT #F VALUES (12,1,2,'381                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,2,2,'382                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,3,2,'383                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,4,2,'384                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,5,2,'385                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (15,1,1,'Сведения из реестра молодежных и детских общественных объединений, пользующихся государственной поддержкой                                                                                                                                                    ')
INSERT #F VALUES (15,1,2,'501                                                                                                                                                                                                                                                           ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 428
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.114гр.3 =  т.2стр.111гр.3 +  т.2стр.112гр.3 +  т.2стр.113гр.3',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.114гр.4 =  т.2стр.111гр.4 +  т.2стр.112гр.4 +  т.2стр.113гр.4',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.114гр.5 =  т.2стр.111гр.5 +  т.2стр.112гр.5 +  т.2стр.113гр.5',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.130гр.3 =  т.2стр.100гр.3 +  т.2стр.110гр.3 +  т.2стр.120гр.3',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.130гр.4 =  т.2стр.100гр.4 +  т.2стр.110гр.4 +  т.2стр.120гр.4',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.130гр.5 =  т.2стр.100гр.5 +  т.2стр.110гр.5 +  т.2стр.120гр.5',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.144гр.3 =  т.2стр.141гр.3 +  т.2стр.142гр.3 +  т.2стр.143гр.3',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.144гр.4 =  т.2стр.141гр.4 +  т.2стр.142гр.4 +  т.2стр.143гр.4',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.150гр.3 =  т.2стр.130гр.3 -  т.2стр.140гр.3',1,12,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.150гр.4 =  т.2стр.130гр.4 -  т.2стр.140гр.4',1,12,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.150гр.5 =  т.2стр.130гр.5 -  т.2стр.140гр.5',1,12,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.3стр.240гр.3 =  т.3стр.201гр.3 +  т.3стр.203гр.3 -  т.3стр.211гр.3 -  т.3стр.213гр.3 -  т.3стр.221гр.3 -  т.3стр.231гр.3 -  т.3стр.233гр.3',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.3стр.240гр.4 =  т.3стр.201гр.4 +  т.3стр.203гр.4 -  т.3стр.211гр.4 -  т.3стр.213гр.4 -  т.3стр.221гр.4 -  т.3стр.231гр.4 -  т.3стр.233гр.4',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.3стр.240гр.5 =  т.3стр.201гр.5 +  т.3стр.203гр.5 -  т.3стр.211гр.5 -  т.3стр.213гр.5 -  т.3стр.221гр.5 -  т.3стр.231гр.5 -  т.3стр.233гр.5',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.3стр.241гр.3 =  т.3стр.202гр.3 -  т.3стр.212гр.3 -  т.3стр.222гр.3 -  т.3стр.232гр.3',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.3стр.241гр.4 =  т.3стр.202гр.4 -  т.3стр.212гр.4 -  т.3стр.222гр.4 -  т.3стр.232гр.4',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.3стр.241гр.5 =  т.3стр.202гр.5 -  т.3стр.212гр.5 -  т.3стр.222гр.5 -  т.3стр.232гр.5',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.3стр.275гр.3 =  т.3стр.271гр.3 -  т.3стр.272гр.3 -  т.3стр.273гр.3 -  т.3стр.274гр.3',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.3стр.275гр.4 =  т.3стр.271гр.4 -  т.3стр.272гр.4 -  т.3стр.273гр.4 -  т.3стр.274гр.4',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.3стр.275гр.5 =  т.3стр.271гр.5 -  т.3стр.272гр.5 -  т.3стр.273гр.5 -  т.3стр.274гр.5',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.6стр.323гр.3 =  т.6стр.322гр.3 /  т.6стр.321гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.6стр.323гр.4 =  т.6стр.322гр.4 /  т.6стр.321гр.4 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.6стр.323гр.5 =  т.6стр.322гр.5 /  т.6стр.321гр.5 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.7стр.333гр.3 =  т.7стр.332гр.3 /  т.7стр.331гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.7стр.333гр.4 =  т.7стр.332гр.4 /  т.7стр.331гр.4 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.7стр.333гр.5 =  т.7стр.332гр.5 /  т.7стр.331гр.5 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.7стр.336гр.3 =  т.7стр.335гр.3 /  т.7стр.334гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.7стр.336гр.4 =  т.7стр.335гр.4 /  т.7стр.334гр.4 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.7стр.336гр.5 =  т.7стр.335гр.5 /  т.7стр.334гр.5 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.8стр.343гр.3 =  т.8стр.342гр.3 /  т.8стр.341гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.8стр.343гр.4 =  т.8стр.342гр.4 /  т.8стр.341гр.4 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.3стр.240гр.6 =  т.3стр.201гр.6 +  т.3стр.203гр.6 -  т.3стр.211гр.6 -  т.3стр.213гр.6 -  т.3стр.221гр.6 -  т.3стр.231гр.6 -  т.3стр.233гр.6',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.3стр.241гр.6 =  т.3стр.202гр.6 -  т.3стр.212гр.6 -  т.3стр.222гр.6 -  т.3стр.232гр.6',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.3стр.275гр.6 =  т.3стр.271гр.6 -  т.3стр.272гр.6 -  т.3стр.273гр.6 -  т.3стр.274гр.6',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.6стр.323гр.6 =  т.6стр.322гр.6 /  т.6стр.321гр.6 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.7стр.333гр.6 =  т.7стр.332гр.6 /  т.7стр.331гр.6 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.7стр.336гр.6 =  т.7стр.335гр.6 /  т.7стр.334гр.6 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.9стр.350lгр.4 =  т.9стр.350aгр.4 +  т.9стр.350bгр.4 +  т.9стр.350cгр.4 +  т.9стр.350dгр.4 +  т.9стр.350eгр.4 +  т.9стр.350fгр.4 +  т.9стр.350gгр.4 +  т.9стр.350hгр.4 +  т.9стр.350jгр.4 +  т.9стр.350kгр.4',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.10стр.363гр.3 =  т.10стр.362гр.3 /  т.10стр.361гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.11стр.375гр.3 =  т.11стр.372гр.3 +  т.11стр.373гр.3 +  т.11стр.374гр.3 /  т.11стр.371гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.11стр.375гр.4 =  т.11стр.372гр.4 +  т.11стр.373гр.4 +  т.11стр.374гр.4 /  т.11стр.371гр.4 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.12стр.383гр.3 =  т.12стр.382гр.3 /  т.12стр.381гр.3 *  100',1,0,1,'20120410','','','','РСВ-1','20120101','','=',0,'')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.2стр.110гр.3 =  т.3стр.250гр.3 +  т.3стр.252гр.3 +  т.4стр.2500гр.3 +  т.4стр.2520гр.3',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.2стр.110гр.4 =  т.3стр.251гр.3 +  т.4стр.2510гр.3',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.2стр.110гр.5 =  т.3стр.276гр.3 +  т.4стр.2760гр.3',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.2стр.111гр.3 =  т.3стр.250гр.4 +  т.3стр.252гр.4 +  т.4стр.2500гр.4 +  т.4стр.2520гр.4',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.2стр.111гр.4 =  т.3стр.251гр.4 +  т.4стр.2510гр.4',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.2стр.111гр.5 =  т.3стр.276гр.4 +  т.4стр.2760гр.4',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.2стр.112гр.3 =  т.3стр.250гр.5 +  т.3стр.252гр.5 +  т.4стр.2500гр.5 +  т.4стр.2520гр.5',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.2стр.112гр.4 =  т.3стр.251гр.5 +  т.4стр.2510гр.5',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.2стр.112гр.5 =  т.3стр.276гр.5 +  т.4стр.2760гр.5',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.2стр.113гр.3 =  т.3стр.250гр.6 +  т.3стр.252гр.6 +  т.4стр.2500гр.6 +  т.4стр.2520гр.6',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.2стр.113гр.4 =  т.3стр.251гр.6 +  т.4стр.2510гр.6',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.2стр.113гр.5 =  т.3стр.276гр.6 +  т.4стр.2760гр.6',1,10,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.4стр.2400гр.3 =  т.4стр.2010гр.3 +  т.4стр.2030гр.3 -  т.4стр.2110гр.3 -  т.4стр.2130гр.3 -  т.4стр.2210гр.3 -  т.4стр.2310гр.3 -  т.4стр.2330гр.3',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.4стр.2400гр.4 =  т.4стр.2010гр.4 +  т.4стр.2030гр.4 -  т.4стр.2110гр.4 -  т.4стр.2130гр.4 -  т.4стр.2210гр.4 -  т.4стр.2310гр.4 -  т.4стр.2330гр.4',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.4стр.2400гр.5 =  т.4стр.2010гр.5 +  т.4стр.2030гр.5 -  т.4стр.2110гр.5 -  т.4стр.2130гр.5 -  т.4стр.2210гр.5 -  т.4стр.2310гр.5 -  т.4стр.2330гр.5',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.4стр.2400гр.6 =  т.4стр.2010гр.6 +  т.4стр.2030гр.6 -  т.4стр.2110гр.6 -  т.4стр.2130гр.6 -  т.4стр.2210гр.6 -  т.4стр.2310гр.6 -  т.4стр.2330гр.6',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.4стр.2410гр.3 =  т.4стр.2020гр.3 -  т.4стр.2120гр.3 -  т.4стр.2220гр.3 -  т.4стр.2320гр.3',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.4стр.2410гр.4 =  т.4стр.2020гр.4 -  т.4стр.2120гр.4 -  т.4стр.2220гр.4 -  т.4стр.2320гр.4',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.4стр.2410гр.5 =  т.4стр.2020гр.5 -  т.4стр.2120гр.5 -  т.4стр.2220гр.5 -  т.4стр.2320гр.5',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.4стр.2410гр.6 =  т.4стр.2020гр.6 -  т.4стр.2120гр.6 -  т.4стр.2220гр.6 -  т.4стр.2320гр.6',1,0,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.4стр.2750гр.3 =  т.4стр.2710гр.3 -  т.4стр.2720гр.3 -  т.4стр.2730гр.3 -  т.4стр.2740гр.3',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.4стр.2750гр.4 =  т.4стр.2710гр.4 -  т.4стр.2720гр.4 -  т.4стр.2730гр.4 -  т.4стр.2740гр.4',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.4стр.2750гр.5 =  т.4стр.2710гр.5 -  т.4стр.2720гр.5 -  т.4стр.2730гр.5 -  т.4стр.2740гр.5',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.4стр.2750гр.6 =  т.4стр.2710гр.6 -  т.4стр.2720гр.6 -  т.4стр.2730гр.6 -  т.4стр.2740гр.6',1,1,1,'20120410','','','','РСВ-1','20120101','','=',1,'')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 67
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]    FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','323','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','322','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','321','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','323','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','322','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','321','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','323','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','322','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','321','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','333','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','332','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','331','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','333','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','332','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','331','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','333','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','332','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','331','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','336','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','335','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','334','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','336','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','335','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','334','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','336','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','335','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','334','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','343','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','342','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','341','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','343','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','342','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','341','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','323','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','322','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','321','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','333','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','332','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','331','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','336','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','335','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','334','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350l','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350a','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350b','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350c','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350d','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350e','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350f','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350g','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350h','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350j','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','350k','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','375','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','372','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','373','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','374','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','371','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','372','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','373','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','374','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','371','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','383','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','382','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','381','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2740','4',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) <> 320
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2012-04-23 16:21:02.833',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 = '2012-04-23 16:21:02.833'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2012-04-23 16:21:02.833. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
IF OBJECT_ID('R_SPR_IST_1703_2011') IS NULL
BEGIN
   UPDATE dbo.report_coloumns
   SET dictionary = 'R_SPR_IST_17_2011'
   WHERE dictionary = 'R_SPR_IST_1703_2011'
END    
GO

GO
UPDATE rt
SET script_str = 'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''410G'',2)  
KEY_FOX=PADR(RTRIM(COL1),17,''0'')+PADR(RTRIM(COL2),6,''0'')+PADR(RTRIM(COL3),3,''0'')  
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''00000000000000000'',17)+LEFT(RTRIM(isnull(COL2,''''))+''000000'',6)+LEFT(RTRIM(ISNULL(COL3,''''))+''000'',3)  
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,17)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''000000'',18,6)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000'',24,3)  
DEPENDENT_COL=COL1#COL2#COL3  
DEPENDENT_RELATIONS=R_SPR_DEP_410rash_2011  
DEPENDENT_CALC=RzPr#Shet#EKR  
EXPORT_EXCLUDE_FILTER=CODE=''00000000000000000000960''  
AUTO_SPR_FORM=R_SPR_AUTO_410_02_2011  
AUTO_SPR_CHECK=exists(select top 1 * from R_SPR_RASH_410_2011  D where D.Code = LEFT(T.Code,17)) and exists(select top 1 * from R_SPR_410_cshet   D where D.Code = SUBSTRING(T.Code,18,6)) and (exists(select top 1 * from R_SPR_EKR_RASH_2011    D where D.Code = SUBSTRING(T.Code,24,3)) or SUBSTRING(T.Code,24,3)=''960'') and exists(select top 1 * from R_SPR_DEP_410rash_2011 D where D.RzPr= LEFT(T.Code,17) and D.Shet = SUBSTRING(T.Code,18,6) and D.EKR = SUBSTRING(T.Code,24,3))'
FROM 
dbo.[REPORT_TABLES] rt
JOIN dbo.report_forms rf ON rf.[Link_Form] = rt.[Link_Form]
WHERE rf.code LIKE '410G%' AND rt.orders = 2 AND rf.start_date = '20110101'
GO


UPDATE rt
SET script_str = 'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''410G'',1)
KEY_FOX=PADR(RTRIM(COL1),17,''0'')+PADR(RTRIM(COL2),6,''0'')+PADR(RTRIM(COL3),3,''0'')
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''00000000000000000'',17)+LEFT(RTRIM(isnull(COL2,''''))+''000000'',6)+LEFT(RTRIM(ISNULL(COL3,''''))+''000'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,17)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''000000'',18,6)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000'',24,3)
DEPENDENT_COL=COL1#COL2#COL3
DEPENDENT_RELATIONS=R_SPR_DEP_410_2011
DEPENDENT_CALC=DOH#ACC#SGU
EXPORT_EXCLUDE_FILTER=CODE=''00000000000000000000000850''
AUTO_SPR_FORM=R_SPR_410_01_2011 
AUTO_SPR_CHECK=exists(select top 1 * from R_SPR_DOH_410_2011  D where D.Code = LEFT(T.Code,17)) and exists(select top 1 * from R_SPR_410_cshet  D where D.Code = SUBSTRING(T.Code,18,6)) and (exists(select top 1 * from R_SPR_KOSGY_410_doh_2011   D where D.Code = SUBSTRING(T.Code,24,3)) or SUBSTRING(T.Code,24,3)=''850'') and exists(select top 1 * from R_SPR_DEP_410_2011 D where D.Doh = LEFT(T.Code,17) and D.Acc = SUBSTRING(T.Code,18,6) and D.SGU = SUBSTRING(T.Code,24,3))'
FROM 
dbo.[REPORT_TABLES] rt
JOIN dbo.report_forms rf ON rf.[Link_Form] = rt.[Link_Form]
WHERE rf.code LIKE '410G%' AND rt.orders = 1 AND rf.start_date = '20110101'
GO

GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_410_cshet',0,'Справочник счетов для 410 формы','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='USER_REPORT' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_410_cshet',@link_self,'Справочник счетов для 410 формы','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_410_cshet')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_410_cshet')
delete report_kbk where code_form= 'R_SPR_410_cshet'
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 '000000',0,'R_SPR_410_cshet',1,'',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '140120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '240120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740110',0,'R_SPR_410_cshet',1,'Доходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '740120',0,'R_SPR_410_cshet',1,'Расходы текущего финансового года',0,'',0,'','', NULL,NULL,0

insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20000101', '', ''
from dbo.report_kbk 
where code_form = 'R_SPR_410_cshet' and code = '740120' and begin_date  is NULL and end_date  is NULL
insert dbo.report_kbk_hist (Link_up, date, name, long_name)
select Link, '20120203', 'Расходы текущего финансового года', ''
from dbo.report_kbk 
where code_form = 'R_SPR_410_cshet' and code = '740120' and begin_date  is NULL and end_date  is NULL
exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_410_cshet'

GO


GO
UPDATE rav
SET str_val = 'деятельность по оказанию услуг (работ)'
FROM dbo.[REPORT_ATRIBUT_VALUES] rav
WHERE rav.[code_atr] = 'REPORTS_ATR_VID_NAME_773'
      AND str_val = 'деятельность по оказанию услуг (работ) (приносящая доход деятельность)'

UPDATE rav
SET str_val = 'деятельность с целевыми средствами'
FROM dbo.[REPORT_ATRIBUT_VALUES] rav
WHERE rav.[code_atr] = 'REPORTS_ATR_VID_NAME_773'
      AND str_val = 'деятельность с целевыми средствами, включающая'

UPDATE dbo.report_saved_forms
SET atr = dbo.[RN_GET_ATR_VAL](link_saved_form, 0, 0),
   atr_code = dbo.[RN_GET_ATR_VAL](link_saved_form, 0, 1)
WHERE link_form IN       
   (SELECT Link_Form FROM  report_forms 
   WHERE code = '0503773G')     
GO
   
GO
DECLARE @LF INT
SELECT @LF = LINK_FORM FROM dbo.report_forms WHERE code = '0503324M' AND START_DATE = '20110101'
UPDATE rc
SET [Dictionary] = 'R_SPR_CSR_FED_2011_324'
FROM dbo.[REPORT_COLOUMNS] rc
      JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] AND rc.[Orders] = 3 AND rt.[Orders] = 1 AND rt.[Link_Form] = @LF

SELECT @LF = LINK_FORM FROM dbo.report_forms WHERE code = '0503324G' AND START_DATE = '20110101'
UPDATE rc
SET [Dictionary] = 'R_SPR_CSR_FED_2011_324'
FROM dbo.[REPORT_COLOUMNS] rc
      JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] AND rc.[Orders] = 3 AND rt.[Orders] = 1 AND rt.[Link_Form] = @LF
GO

GO
if not exists(SELECT * FROM dbo.report_options WHERE [Razdel] = 'ECP' AND Code = 'NotDel')
BEGIN
   INSERT dbo.report_options ( [Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Int], [SID])
   VALUES ('ECP', 'NotDel',7,  'Запрещать удалять ЭЦП отчета', 1, 0, 0x01)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] 'ECP'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'ECP'
END 
GO

GO
UPDATE rc
SET [Dictionary_Where] = CASE WHEN isnull(rc.[Dictionary_Where], '') = '' THEN '%date%>=begin_date and %date%<=end_date' ELSE RTRIM(rc.[Dictionary_Where]) + ' AND %date%>=begin_date and %date%<=end_date' END   
FROM dbo.report_forms rf 
   LEFT JOIN dbo.report_tables rt ON rt.[Link_Form] = rf.[Link_Form]
   LEFT JOIN dbo.report_coloumns rc ON rc.[Link_Table] = rt.[Link_Table]
WHERE YEAR(START_DATE) = 2011 AND Code LIKE '[0-9]%[MG]%'
   AND isnull(rc.[Dictionary],'') <> ''
   AND EXISTS(SELECT * FROM dbo.report_spr S WHERE S.code = rc.[Dictionary] AND S.[IsSystem]=1)
   AND isnull(rc.[Dictionary_Where], '') NOT LIKE '%date% >= begin_date and %date% <= end_date%'
   AND isnull(rc.[Dictionary_Where], '') NOT LIKE '%date%'  

GO
                                                                                                                                                                                                                                                                                                                                                                                                                              
GO
GRANT ALL  ON dbo.[report_kbk_hist] TO PUBLIC
GRANT ALL  ON dbo.[report_kbk_cashe] TO PUBLIC
GO

GO
UPDATE report_forms
SET [Hint_File_Id] = NULL
WHERE [Hint_File_Id] NOT IN (SELECT id FROM dbo.[R_FILES] rf)
GO

GO
DECLARE @link INT 
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code = 'ARHIVE' AND code_form = 'HEADER')
BEGIN
   UPDATE dbo.report_kbk 
   SET ORDERS = ISNULL(ORDERS,1) + 2 
   WHERE code_form = 'HEADER' AND link_self = 0

   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name])
   VALUES ('ARHIVE', 0, 'HEADER', 0, 'Архив', 4, '', 0, '', 2, '')
   
   SET @Link = @@IDENTITY

   UPDATE dbo.report_kbk
   SET link_self = @link
   WHERE code IN ('YEAR_2007', 'YEAR_2008', 'YEAR_2009', 'YEAR_2010') AND Code_Form = 'HEADER'
   
   UPDATE dbo.report_kbk
   SET NAME = 'Бюджетная классификация', orders = 1 
   WHERE code = 'YEAR_2011' AND Code_Form = 'HEADER'
   
END    
GO

GO
/****** Объект: Список КБК******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_KBK_SPISOK_KBK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_KBK_SPISOK_KBK')
	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 = 'REPORT_KBK_SPISOK_KBK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_KBK_SPISOK_KBK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_KBK_SPISOK_KBK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_KBK_SPISOK_KBK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK', 'Список КБК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_VIEW'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK', NAME = 'Список КБК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_VIEW'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='REPORT_KBK_SPISOK_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_VIEW_FTP_MARKER_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_VIEW_FTP_MARKER_1', 'Поле-маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_VIEW_FTP_MARKER_1', NAME = 'Поле-маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_VIEW_FTP_MARKER_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_CODE', 'КОД', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_CODE', NAME = 'КОД', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_EXP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_EXP', 'Выгружаемый код', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_EXP', NAME = 'Выгружаемый код', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_EXP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_EXP_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_EXP_1', 'Всегда добавлять', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_EXP_1', NAME = 'Всегда добавлять', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_EXP_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_STR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_STR_CODE', 'Код строки', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_STR_CODE', NAME = 'Код строки', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_STR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_NAME', 'Наименование', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_NAME', NAME = 'Наименование', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_ADD_INFO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_ADD_INFO', 'Доп. информация', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_ADD_INFO', NAME = 'Доп. информация', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_ADD_INFO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_ADD_IN_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'Доп. информация', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', NAME = 'Доп. информация', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_ADD_IN_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_NAME2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_NAME2', 'Полное наименование', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_NAME2', NAME = 'Полное наименование', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_NAME2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_DB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_DB', 'Дата начала действия', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_DB', NAME = 'Дата начала действия', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_DB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_DE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_DE', 'Дата окончания действия', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_DE', NAME = 'Дата окончания действия', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_DE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK_CODE_F')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_KBK_SPISOK_KBK_CODE_F', 'КОД формы', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_KBK_SPISOK_KBK_CODE_F', NAME = 'КОД формы', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_KBK_SPISOK_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_KBK_SPISOK_KBK_CODE_F'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK', 'TITLE', 'Пользователи и роли'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK', 'SELECT_RECORDS_METHOD', 'SQL.EXEC("SELECT 0 as UPD,0 as CHECKED,''Нет'' EXPORT,''Нет'' ITOG ,LEFT(add_INFO,240) add_info_short,*, 0 as is_cross FROM REPORT_KBK WHERE 1=0" , m.cAlias)'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FTP_MARKER_1', 'TITLE', 'М'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FTP_MARKER_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FTP_MARKER_1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FTP_MARKER_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_VIEW_FTP_MARKER_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias + ''.CODE'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.CODE'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE', 'CONTROL_NAME_EDIT', 'txtName1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP', 'TITLE', 'Подитог'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP', 'CONTROLSOURCE', 'm.cAlias + ''.EXPORT'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.EXPORT'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP_1', 'TITLE', 'Итог'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP_1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP_1', 'CONTROLSOURCE', 'm.cAlias + ''.ITOG'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ITOG'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_EXP_1', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_STR_CODE', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_STR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_STR_CODE', 'CONTROLSOURCE', 'm.cAlias + ''.CODE_STR'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'CONTROLSOURCE', 'm.cAlias + ''.NAME'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.NAME'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME', 'CONTROL_NAME_EDIT', 'ASel_Spr5'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_INFO', 'TITLE', 'Доп. информация'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_INFO', 'CONTROLSOURCE', 'm.cAlias + ''.ADD_INFO'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_INFO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ADD_INFO'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_INFO', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'TITLE', 'Доп. информация'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'CONTROLSOURCE', 'm.cAlias + ''.ADD_INFO_SHORT'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ADD_INFO'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_ADD_IN_1', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'TITLE', 'Полное наименование'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'CONTROLSOURCE', 'm.cAlias + ''.LONG_NAME'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.LONG_NAME'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'CONTROL_NAME', 'Edit1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_NAME2', 'CONTROL_NAME_EDIT', 'ASel_Spr5'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'TITLE', 'Дата начала действия'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'CONTROLSOURCE', 'm.cAlias + ''.begin_date'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.begin_date'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DB', 'CONTROL_NAME', 'Text1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'TITLE', 'Дата окончания действия'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'CONTROLSOURCE', 'm.cAlias + ''.end_date'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.end_date'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_DE', 'CONTROL_NAME', 'Text1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'TITLE', 'Код формы'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'CONTROLSOURCE', 'm.cAlias + ''.CODE_FORM'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.CODE_FORM'''
GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK_CODE_F', 'CONTROL_NAME_EDIT', 'txtName1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORT_KBK_SPISOK_KBK', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORT_KBK_SPISOK_KBK', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO
EXEC X_SET_PROP 'REPORT_KBK_SPISOK_KBK', 'SELECT_RECORDS_METHOD', 'SQL.EXEC("SELECT 0 as UPD,0 as CHECKED,''Нет'' EXPORT,''Нет'' ITOG ,LEFT(add_INFO,240) add_info_short,*, 0 as is_cross FROM REPORT_KBK WHERE 1=0" , m.cAlias)'
GO


GO
UPDATE rc
SET rc.[Dictionary_Where] = '%date% >= date_begin and %date% <= date_end' 
FROM dbo.report_coloumns rc
WHERE [Dictionary] = 'RT_VIEW_DEPDICT_125'
   AND isnull(rc.[Dictionary_Where],'') NOT LIKE '%date% >= date_begin and %date% <= date_end%'                                                                                                                                                                                                               
GO
   
GO
UPDATE rc
SET val_len = 2000
FROM dbo.[REPORT_COLOUMNS] rc
JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] 
JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
WHERE rf.[Code] IN ('0503127G', '0503127M', '0503117M', '0503117G') AND YEAR(rf.[Start_Date]) = 2011 AND rt.orders = 3 AND rc.[Orders] = 1
GO
 
GO
UPDATE ro
SET PROPERTY = 1
FROM dbo.report_control_rows ro
   JOIN dbo.report_control_group cg ON cg.[Link_Rule] = ro.[Link_Rule]
   JOIN dbo.report_group_ks g ON g.[LINK_GROUP_KS] = cg.[Link_Group_KS]
   LEFT JOIN dbo.report_forms rf ON rf.[Link_Form] = ro.[Link_Form]
WHERE g.code IN ('884',
'906',
'944',
'968',
'981',
'982',
'983',
'984',
'985')
AND rf.code NOT LIKE '%130%'
GO


GO
IF NOT EXISTS(SELECT * FROM dbo.report_options WHERE razdel = 'COMMON' AND code = 'ITOG_117')
BEGIN
   INSERT dbo.[REPORT_OPTIONS] ([Razdel], [Code], [Name], [Val_Type], [Val_Int], [SID], orders)
   VALUES('COMMON', 'ITOG_117', 'Не проверять на наличие ЦСР и ВР в справочнике',  1, 0, 0x01, 18)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] 'COMMON'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'COMMON'
END
GO

UPDATE rt
SET rt.[Script_Str] = 
   LEFT(rt.[Script_Str], CHARINDEX('AUTO_SPR_CHECK=', rt.[Script_Str]) -1) +
   '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,7)) and exists(select * from dbo.R_SPR_VR_2011 where code = SUBSTRING(T.code,12,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'')
   ' + 
   SUBSTRING(rt.[Script_Str], CHARINDEX(CHAR(13), rt.[Script_Str],CHARINDEX('AUTO_SPR_CHECK=', rt.[Script_Str])), 8000)
    
FROM dbo.report_coloumns rc
   JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] AND rt.[Link_Code_Col] = rc.[Link_Col]
WHERE rc.[Dictionary] = 'R_SPR_RASH_117_2011' AND rt.[Doschet_Tree] = 1

UPDATE rt
SET rt.[Script_Str] = 
   LEFT(rt.[Script_Str], CHARINDEX('AUTO_SPR_CHECK=', rt.[Script_Str]) -1) +
   '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,7)) and exists(select * from dbo.R_SPR_VR_2011 where code = SUBSTRING(T.code,12,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'')
   ' + 
   SUBSTRING(rt.[Script_Str], CHARINDEX(CHAR(13), rt.[Script_Str],CHARINDEX('AUTO_SPR_CHECK=', rt.[Script_Str])), 8000)
    
FROM dbo.report_coloumns rc
   JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table] AND rt.[Link_Code_Col] = rc.[Link_Col]
WHERE rc.[Dictionary] = 'R_SPR_RASH_114_2011' AND rt.[Doschet_Tree] = 1
GO


GO
if not exists(SELECT * FROM dbo.report_options WHERE razdel = 'Form_125' AND Code = 'Mask')
BEGIN
   INSERT dbo.[REPORT_OPTIONS] ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Str], [SID])
   VALUES('Form_125', 'Mask', 2, 'Маска для сверки ФО-ГРБС', 3, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 0x01)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] 'Form_125'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'Form_125'
END    
GO
/****** Объект: Вкладка "125"******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_125')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RA_REP_OPTIONS_FORM_125')
	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 = 'RA_REP_OPTIONS_FORM_125')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RA_REP_OPTIONS_FORM_125')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_125'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RA_REP_OPTIONS_FORM_125')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_125', 'Вкладка "125"', 34, (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_125', NAME = 'Вкладка "125"', ORDERS = '34', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_125'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125B_VB_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_125B_VB_1', '125ВБ', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_125B_VB_1', NAME = '125ВБ', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_125B_VB_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125_MASK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RA_REP_OPTIONS_FORM_125_MASK', 'Маска для сверки ФО-ГРБС 125', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RA_REP_OPTIONS_FORM_125_MASK', NAME = 'Маска для сверки ФО-ГРБС 125', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_FORM_125'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RA_REP_OPTIONS_FORM_125_MASK'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125', 'SELECT_RECORDS_METHOD', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_FORM_125'', m.cAlias)'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_FORM_125'', m.cAlias)'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'CONTROLSOURCE', 'm.cAlias + ''.IMPORT_VB_125'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'SHORT_CODE_OBJ', 'IMPORT_VB_125'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.IMPORT_VB_125'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125B_VB_1', 'CONTROL_NAME_EDIT', 'txtIMPORT_VB_125'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'CONTROLSOURCE', 'm.cAlias + ''.Mask'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'SHORT_CODE_OBJ', 'Mask'
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.Mask'''
GO
EXEC X_SET_PROP 'RA_REP_OPTIONS_FORM_125_MASK', 'CONTROL_NAME_EDIT', 'AtxtMask125'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
if not exists(SELECT * FROM report_options WHERE [Razdel] = '86n' AND code = 'dir')
BEGIN 
   INSERT dbo.report_options ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Str], [SID])
   VALUES ('86n', 'dir', 1, 'Путь к папке, где находятся файлы для передачи', 3, '', 0x01)
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] '86n'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] '86n' 
END 
GO
IF not exists(SELECT * FROM [dbo].[REPORT_OPTIONS] ro WHERE ro.[Razdel] = '86n' AND Code = 'IS_STATUS')
BEGIN
   INSERT INTO [dbo].[REPORT_OPTIONS]
   (
      [Razdel],
      [Code],
      [Orders],
      [Name],
      [Val_Type],
      [Val_Int],
      [Val_Float],
      [Val_Str],
      [Val_Date],
      [Link_KAU],
      [SID]
   )
   VALUES
   (
      '86n',
      'IS_STATUS',
      2,
      'Отправлать только при наличии статуса отчета "Проверен"',
      1,
      0,
      0,
      '',
      NULL,
      NULL,
      0x01
   )
   
   EXEC [dbo].[I_REPORT_OPTIONS_CREATE_SAVE_PROC] '86n'
   EXEC [dbo].[I_REPORT_OPTIONS_CREATE_VIEW] '86n'
      
END    
GO
/****** Объект: Вкладка "86н"******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_86N')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_86N')
	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 = 'REP_OPTIONS_86N')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_86N')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_86N'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_86N')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REP_OPTIONS_86N', 'Вкладка "86н"', 40, (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REP_OPTIONS_86N', NAME = 'Вкладка "86н"', ORDERS = '40', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='I_REPORT_OPTIONS_4FSS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REP_OPTIONS_86N'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N_DIR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REP_OPTIONS_86N_DIR', 'Путь к папке', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REP_OPTIONS_86N_DIR', NAME = 'Путь к папке', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REP_OPTIONS_86N_DIR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N_IS_STATUS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REP_OPTIONS_86N_IS_STATUS', 'Отправлать только при наличии статуса отчета "Проверен"', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REP_OPTIONS_86N_IS_STATUS', NAME = 'Отправлать только при наличии статуса отчета "Проверен"', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REP_OPTIONS_86N'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REP_OPTIONS_86N_IS_STATUS'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N', 'SELECT_RECORDS_METHOD', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_86N'', m.cAlias)'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N', 'SELECT_RECORDS_METHOD_EDIT', 'sql.exec(''select * from dbo.I_REPORT_OPTIONS_86N'', m.cAlias)'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'CONTROLSOURCE', 'm.cAlias + ''.dir'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'SHORT_CODE_OBJ', 'dir'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.dir'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_DIR', 'CONTROL_NAME_EDIT', 'atxtDir'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'TITLE', 'Отправлать только при наличии статуса отчета "Проверен"'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'CONTROLSOURCE', 'm.cAlias + ''.IS_STATUS'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'SHORT_CODE_OBJ', 'IS_STATUS'
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.IS_STATUS'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_86N_IS_STATUS', 'CONTROL_NAME_EDIT', 'achkIS_STATUS'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/



GO
if not exists(SELECT * FROM dbo.[REPORT_OPTIONS] ro WHERE ro.[Razdel] = 'COMMON' AND ro.[Code] =  'ACCESS_STATUS')
BEGIN
   INSERT dbo.[REPORT_OPTIONS] ([Razdel], [Code], [Orders], [Name], [Val_Type], [Val_Int], [SID])
   VALUES('COMMON', 'ACCESS_STATUS', 19, 'Возможность всегда менять статусы у нижележащих отчетов', 1, 0, 0x01)
   
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_SAVE_PROC] 'COMMON'
   EXEC dbo.[I_REPORT_OPTIONS_CREATE_VIEW] 'COMMON'
END 
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[I_REPORT_OPTIONS_SAVE_COMMON]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[I_REPORT_OPTIONS_SAVE_COMMON]

GO
CREATE  PROCEDURE dbo.I_REPORT_OPTIONS_SAVE_COMMON
	@varKSEXPORT_TOTALS	int,
	@varKSALL_VERS_IN_THIN_CLI	int,
	@varKSCHIEF_SOC_POST	varchar(250),
	@varKSCHIEF_SOC_FIO	varchar(250),
	@varKSPERFORMER_SOC_POST	varchar(250),
	@varKSPERFORMER_SOC_FIO	varchar(250),
	@varKSPERFORMER_SOC_PHONE	varchar(250),
	@varKSINVISIBLE_CALCULATE	int,
	@varKSIMPORT_REPORT	int,
	@varKSNEW_REPORT	int,
	@varKSRELATE_DICTION	int,
	@varKSRepMaker	int,
	@varKSRepMakerFormat	int,
	@varKSNOT_VKL_V_SVOD	int,
	@varKSGOTOV_K_PROV	int,
	@varKSRETURN_STATUS	int,
	@varKSITOG_117	int,
	@varKSACCESS_STATUS	int
AS
-- Процедурa сформирована с помощью I_REPORT_OPTIONS_CREATE_SAVE_PROC (Федоров И.В.)
--Apr 28 2012  4:01PM           

	if exists (select * from report_options where razdel = 'COMMON' and code = 'EXPORT_TOTALS')
		update report_options
			SET val_int = @varKSEXPORT_TOTALS
			WHERE razdel = 'COMMON' and code = 'EXPORT_TOTALS'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'ALL_VERS_IN_THIN_CLI')
		update report_options
			SET val_int = @varKSALL_VERS_IN_THIN_CLI
			WHERE razdel = 'COMMON' and code = 'ALL_VERS_IN_THIN_CLI'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'CHIEF_SOC_POST')
		update report_options
			SET val_str = @varKSCHIEF_SOC_POST
			WHERE razdel = 'COMMON' and code = 'CHIEF_SOC_POST'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'CHIEF_SOC_FIO')
		update report_options
			SET val_str = @varKSCHIEF_SOC_FIO
			WHERE razdel = 'COMMON' and code = 'CHIEF_SOC_FIO'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'PERFORMER_SOC_POST')
		update report_options
			SET val_str = @varKSPERFORMER_SOC_POST
			WHERE razdel = 'COMMON' and code = 'PERFORMER_SOC_POST'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'PERFORMER_SOC_FIO')
		update report_options
			SET val_str = @varKSPERFORMER_SOC_FIO
			WHERE razdel = 'COMMON' and code = 'PERFORMER_SOC_FIO'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'PERFORMER_SOC_PHONE')
		update report_options
			SET val_str = @varKSPERFORMER_SOC_PHONE
			WHERE razdel = 'COMMON' and code = 'PERFORMER_SOC_PHONE'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'INVISIBLE_CALCULATE')
		update report_options
			SET val_int = @varKSINVISIBLE_CALCULATE
			WHERE razdel = 'COMMON' and code = 'INVISIBLE_CALCULATE'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'IMPORT_REPORT')
		update report_options
			SET val_int = @varKSIMPORT_REPORT
			WHERE razdel = 'COMMON' and code = 'IMPORT_REPORT'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'NEW_REPORT')
		update report_options
			SET val_int = @varKSNEW_REPORT
			WHERE razdel = 'COMMON' and code = 'NEW_REPORT'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'RELATE_DICTION')
		update report_options
			SET val_int = @varKSRELATE_DICTION
			WHERE razdel = 'COMMON' and code = 'RELATE_DICTION'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'RepMaker')
		update report_options
			SET val_int = @varKSRepMaker
			WHERE razdel = 'COMMON' and code = 'RepMaker'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'RepMakerFormat')
		update report_options
			SET val_int = @varKSRepMakerFormat
			WHERE razdel = 'COMMON' and code = 'RepMakerFormat'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'NOT_VKL_V_SVOD')
		update report_options
			SET val_int = @varKSNOT_VKL_V_SVOD
			WHERE razdel = 'COMMON' and code = 'NOT_VKL_V_SVOD'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'GOTOV_K_PROV')
		update report_options
			SET val_int = @varKSGOTOV_K_PROV
			WHERE razdel = 'COMMON' and code = 'GOTOV_K_PROV'

	if exists (select * from report_options where razdel = 'COMMON' and code = 'RETURN_STATUS')
		update report_options
			SET val_int = @varKSRETURN_STATUS
			WHERE razdel = 'COMMON' and code = 'RETURN_STATUS'

      
    IF     @varKSITOG_117 = 1 AND ISNULL((select Val_INT from report_options where razdel = 'COMMON' and code = 'ITOG_117'), 0) = 0
    BEGIN
	      update report_options
		   SET val_int = @varKSITOG_117
		   WHERE razdel = 'COMMON' and code = 'ITOG_117'
         
         BEGIN TRANSACTION

         DELETE dbo.report_kbk
         WHERE code_form = 'R_SPR_RASH_117_2011'


         EXEC [dbo].[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_RASH_117_2011'

         exec dbo.droptemptable  '#t_CodeRow'
         CREATE TABLE #t_CodeRow (Code VARCHAR(50)) 
         exec dbo.droptemptable  '#LSF'
         CREATE TABLE #LSF (lsf int) 

         UPDATE STATISTICS report_kbk

         DECLARE @code VARCHAR(100), @LSF INT, @OT TINYINT, @LF INT, @LT int 

         DECLARE cur CURSOR LOCAL STATIC FOR 
         SELECT S.code, rt.orders,MAX(rsf.link_saved_form) link_saved_form FROM dbo.report_spr S
            JOIN dbo.report_coloumns rc ON S.code = rc.[Dictionary]
            JOIN dbo.report_tables rt ON rt.[Link_Table] = rc.[Link_Table]
            JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
            LEFT JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
         WHERE S.NAME LIKE '%автозаполн%' AND S.code LIKE '%2011%'  AND charindex('AUTO_SPR_PARENT',rt.script_str)>0
            AND S.Code = 'R_SPR_RASH_117_2011'
         GROUP BY S.code, rt.orders

         OPEN cur

          FETCH NEXT FROM cur INTO @code, @OT, @LSF

         WHILE @@FETCH_STATUS = 0
         BEGIN
            INSERT #LSF (lsf)
            SELECT rsf.link_saved_form
            FROM dbo.report_spr S
               JOIN dbo.report_coloumns rc ON S.code = rc.[Dictionary]
               JOIN dbo.report_tables rt ON rt.[Link_Table] = rc.[Link_Table]
               JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
               JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
            WHERE rt.orders = @OT AND S.code = @code --AND rf.code LIKE '%G%'
                  AND charindex('AUTO_SPR_PARENT',rt.script_str)>0

            
            SELECT @LF = link_form FROM dbo.report_saved_forms rsf JOIN #lsf ON lsf = rsf.[Link_Saved_Form]

           
            INSERT #t_CodeRow
            SELECT DISTINCT rd.Code_row
            FROM dbo.report_dinamics rd
               JOIN #lsf ON lsf = rd.link_sf
               JOIN dbo.report_coloumns rc ON rc.[Link_Col] = rd.[Link_Col]
               JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table]
            WHERE RT.[orders] = @OT
            
            EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, @OT
            
            
            TRUNCATE TABLE #t_CodeRow
            TRUNCATE TABLE #LSF  
            
            FETCH NEXT FROM cur INTO @code, @OT, @LSF
         END
         UPDATE STATISTICS report_kbk

         COMMIT          
    END     
    ELSE
    BEGIN
  	      update report_options
		   SET val_int = @varKSITOG_117
		   WHERE razdel = 'COMMON' and code = 'ITOG_117'

    END       


	if exists (select * from report_options where razdel = 'COMMON' and code = 'ACCESS_STATUS')
		update report_options
			SET val_int = @varKSACCESS_STATUS
			WHERE razdel = 'COMMON' and code = 'ACCESS_STATUS'

GO


GRANT EXECUTE ON dbo.[I_REPORT_OPTIONS_SAVE_COMMON] TO PUBLIC

GO

GO
/****** Объект: Не проверять на наличие ЦСР и ВР в справочнике******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ITOG_117')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_COM_ITOG_117')
	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 = 'REP_OPTIONS_COM_ITOG_117')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REP_OPTIONS_COM_ITOG_117')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ITOG_117'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REP_OPTIONS_COM_ITOG_117')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REP_OPTIONS_COM_ITOG_117')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REP_OPTIONS_COM_ITOG_117', 'Не проверять на наличие ЦСР и ВР в справочнике', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_COMMON'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REP_OPTIONS_COM_ITOG_117', NAME = 'Не проверять на наличие ЦСР и ВР в справочнике', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RA_REP_OPTIONS_COMMON'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REP_OPTIONS_COM_ITOG_117'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'TITLE', 'Не проверять на наличие ЦСР и ВР в справочнике'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'CONTROLSOURCE', 'm.cAlias + ''.ITOG_117'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'STORAGE', 'REPORT_OPTION'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'SHORT_CODE_OBJ', 'ITOG_117'
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.ITOG_117'''
GO
EXEC X_SET_PROP 'REP_OPTIONS_COM_ITOG_117', 'CONTROL_NAME_EDIT', 'achkITOG_117'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
if left(convert(char(2), serverproperty('productversion')), 2)<>N'8.'
execute ('GRANT VIEW DEFINITION TO public')
GO

GO
/****** Объект: Роль******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_ROUTE_USERS_GROUP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_ROUTE_USERS_GROUP')
	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 = 'REPORT_ROUTE_USERS_GROUP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_ROUTE_USERS_GROUP')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_ROUTE_USERS_GROUP'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_ROUTE_USERS_GROUP')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_ROUTE_USERS_GROUP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_ROUTE_USERS_GROUP', 'Роль', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ROUTE_USERS_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_ROUTE_USERS_GROUP', NAME = 'Роль', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_ROUTE_USERS_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_ROUTE_USERS_GROUP'
GO
EXEC X_SET_PROP 'REPORT_ROUTE_USERS_GROUP', 'TITLE', 'Роль'
GO
EXEC X_SET_PROP 'REPORT_ROUTE_USERS_GROUP', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'REPORT_ROUTE_USERS_GROUP', 'CONTROLSOURCE', 'm.cAlias + ".Name_group"'
GO
EXEC X_SET_PROP 'REPORT_ROUTE_USERS_GROUP', 'EDITABLE', '1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
--- наименование поменялись:
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.52.@@РС-А-5200'
SET @Name = 'утверждение схем территориального планирования субъекта Российской Федерации, утверждение документации по планировке территории для размещения объектов капитального строительства регионального значения, утверждение региональных нормативов градостроительного проектирования, выдачи разрешения на строительство объекта капитального строительства в случаях, предусмотренных Градостроительным кодексом Российской Федерации'

SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130512')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130512', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
--- наименование поменялись:
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.15.@@РС-А-1500'
SET @Name = 'организация транспортного обслуживания населения воздушным, водным, автомобильным транспортом, включая легковое такси, в межмуниципальном и пригородном сообщении и железнодорожным транспортом в пригородном сообщении, осуществления регионального государственного контроля в сфере перевозок пассажиров и багажа легковым такси'

SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130512')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130512', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
-- новые
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО' AND code = '1.@@РС-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012

set @LS = ISNULL(@LS, 0)

IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО' AND code = '1.99.@@РС-А-9900')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.99.@@РС-А-9900', @LS, 'РРО', 0, LEFT('финансового обеспечения получения гражданами дошкольного, начального общего, основного общего и среднего (полного) общего образования в имеющих государственную аккредитацию негосударственных общеобразовательных учреждениях в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда педагогических работников, расходов на учебники и учебные, учебно-наглядные пособия, технические средства обучения, игры, игрушки, расходные материалы в соответствии с нормативами финансового обеспечения образовательной деятельности государственных образовательных учреждений субъектов Российской Федерации и муниципальных образовательных учреждений', 250),
   0, '', 0, '', 0, 'финансового обеспечения получения гражданами дошкольного, начального общего, основного общего и среднего (полного) общего образования в имеющих государственную аккредитацию негосударственных общеобразовательных учреждениях в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда педагогических работников, расходов на учебники и учебные, учебно-наглядные пособия, технические средства обучения, игры, игрушки, расходные материалы в соответствии с нормативами финансового обеспечения образовательной деятельности государственных образовательных учреждений субъектов Российской Федерации и муниципальных образовательных учреждений',
   '20130512', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO

--- наименование поменялись:
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.29.@@РП-А-2900'
SET @Name = 'утверждение генеральных планов поселения, правил землепользования и застройки, утверждение подготовленной на основе генеральных планов поселения документации по планировке территории, выдача разрешений на строительство (за исключением случаев, предусмотренных Градостроительным кодексом Российской Федерации, иными федеральными законами), разрешений на ввод объектов в эксплуатацию при осуществлении муниципального строительства, реконструкции объектов капитального строительства, расположенных на территории поселения, утверждение местных нормативов градостроительного проектирования поселений, резервирование земель и изъятие, в том числе путем выкупа, земельных участков в границах поселения для муниципальных нужд, осуществление земельного контроля за использованием земель поселения, осуществление в случаях, предусмотренных Градостроительным кодексом Российской Федерации, осмотров зданий, сооружений и выдача рекомендаций об устранении выявленных в ходе таких осмотров нарушений'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130530')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130530', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
--- наименование поменялись:
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.34.@@РГ-А-3400'
SET @Name = 'утверждение генеральных планов городского округа, правил землепользования и застройки, утверждение подготовленной на основе генеральных планов городского округа документации по планировке территории, выдача разрешений на строительство (за исключением случаев, предусмотренных Градостроительным кодексом Российской Федерации, иными федеральными законами), разрешений на ввод объектов в эксплуатацию при осуществлении муниципального строительства, реконструкции объектов капитального строительства, расположенных на территории городского округа, утверждение местных нормативов градостроительного проектирования городского округа, ведение информационной системы обеспечения градостроительной деятельности, осуществляемой на территории городского округа, резервирование земель и изъятие, в том числе путем выкупа, земельных участков в границах городского округа для муниципальных нужд, осуществление земельного контроля за использованием земель городского округа,  осуществление в случаях, предусмотренных Градостроительным кодексом Российской Федерации, осмотров зданий, сооружений и выдача рекомендаций об устранении выявленных в ходе таких осмотров нарушений'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130530')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130530', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
-- новые
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.48.@@РП-А-4800')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.48.@@РП-А-4800', @LS, 'РРО2', 0, LEFT('предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции', 250),
   0, '', 0, '', 0, 'предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.49.@@РП-А-4900')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.49.@@РП-А-4900', @LS, 'РРО2', 0, LEFT('до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности', 250),
   0, '', 0, '', 0, 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.83.@@РП-А-8300')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.83.@@РП-А-8300', @LS, 'РРО2', 0, LEFT('установление официальных символов муниципального образования', 250),
   0, '', 0, '', 0, 'установление официальных символов муниципального образования',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.84.@@РП-А-8400')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.84.@@РП-А-8400', @LS, 'РРО2', 0, LEFT('установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами', 250),
   0, '', 0, '', 0, 'установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.85.@@РП-А-8500')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.85.@@РП-А-8500', @LS, 'РРО2', 0, LEFT('полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении', 250),
   0, '', 0, '', 0, 'полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.86.@@РП-А-8600')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.86.@@РП-А-8600', @LS, 'РРО2', 0, LEFT('принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации', 250),
   0, '', 0, '', 0, 'принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.@@РП-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '1.1.87.@@РП-А-8700')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.1.87.@@РП-А-8700', @LS, 'РРО2', 0, LEFT('осуществление международных и внешнеэкономических связей в соответствии с федеральными законами', 250),
   0, '', 0, '', 0, 'осуществление международных и внешнеэкономических связей в соответствии с федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.44.@@РМ-А-4400')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.44.@@РМ-А-4400', @LS, 'РРО2', 0, LEFT('предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции', 250),
   0, '', 0, '', 0, 'предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.45.@@РМ-А-4500')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.45.@@РМ-А-4500', @LS, 'РРО2', 0, LEFT('до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности', 250),
   0, '', 0, '', 0, 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.83.@@РМ-А-8300')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.83.@@РМ-А-8300', @LS, 'РРО2', 0, LEFT('установление официальных символов муниципального образования', 250),
   0, '', 0, '', 0, 'установление официальных символов муниципального образования',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 


GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.84.@@РМ-А-8400')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.84.@@РМ-А-8400', @LS, 'РРО2', 0, LEFT('установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами', 250),
   0, '', 0, '', 0, 'установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO

DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.85.@@РМ-А-8500')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.85.@@РМ-А-8500', @LS, 'РРО2', 0, LEFT('полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении', 250),
   0, '', 0, '', 0, 'полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO

DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.86.@@РМ-А-8600')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.86.@@РМ-А-8600', @LS, 'РРО2', 0, LEFT('принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации', 250),
   0, '', 0, '', 0, 'принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.@@РМ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '2.1.87.@@РМ-А-8700')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('2.1.87.@@РМ-А-8700', @LS, 'РРО2', 0, LEFT('осуществление международных и внешнеэкономических связей в соответствии с федеральными законами', 250),
   0, '', 0, '', 0, 'осуществление международных и внешнеэкономических связей в соответствии с федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.52.@@РГ-А-5200')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.52.@@РГ-А-5200', @LS, 'РРО2', 0, LEFT('предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции', 250),
   0, '', 0, '', 0, 'предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.53.@@РГ-А-5300')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.53.@@РГ-А-5300', @LS, 'РРО2', 0, LEFT('до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности', 250),
   0, '', 0, '', 0, 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO

DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.83.@@РГ-А-8300')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.83.@@РГ-А-8300', @LS, 'РРО2', 0, LEFT('установление официальных символов муниципального образования', 250),
   0, '', 0, '', 0, 'установление официальных символов муниципального образования',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO

DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.84.@@РГ-А-8400')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.84.@@РГ-А-8400', @LS, 'РРО2', 0, LEFT('установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами', 250),
   0, '', 0, '', 0, 'установление тарифов на услуги, предоставляемые муниципальными предприятиями и учреждениями, и работы, выполняемые муниципальными предприятиями и учреждениями, если иное не предусмотрено федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.85.@@РГ-А-8500')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.85.@@РГ-А-8500', @LS, 'РРО2', 0, LEFT('полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении', 250),
   0, '', 0, '', 0, 'полномочиями в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.86.@@РГ-А-8600')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.86.@@РГ-А-8600', @LS, 'РРО2', 0, LEFT('принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации', 250),
   0, '', 0, '', 0, 'принятие и организация выполнения планов и программ комплексного социально-экономического развития муниципального образования, а также организация сбора статистических показателей, характеризующих состояние экономики и социальной сферы муниципального образования, и предоставление указанных данных органам государственной власти в порядке, установленном Правительством Российской Федерации',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.@@РГ-А' AND YEAR(ISNULL([end_date], '30000101')) > 2012
set @LS = ISNULL(@LS, 0)
IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО2' AND code = '3.1.87.@@РГ-А-8700')
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('3.1.87.@@РГ-А-8700', @LS, 'РРО2', 0, LEFT('осуществление международных и внешнеэкономических связей в соответствии с федеральными законами', 250),
   0, '', 0, '', 0, 'осуществление международных и внешнеэкономических связей в соответствии с федеральными законами',
   '20130530', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO
--- наименование поменялись:
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.14.@@РС-А-1400'
SET @Name = 'осуществление дорожной деятельности в отношении автомобильных дорог регионального или межмуниципального значения и обеспечения безопасности дорожного движения на них, включая создание и обеспечение функционирования парковок (парковочных мест), предоставляемых на платной основе или без взимания платы'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-1401'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-1501'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.17.@@РС-А-1700'
SET @Name = 'обеспечение государственных гарантий прав граждан на получение общедоступного и бесплатного дошкольного, начального общего, основного общего, среднего (полного) общего образования, а также дополнительного образования в общеобразовательных учреждениях путем выделения субвенций местным бюджетам в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда работников общеобразовательных учреждений, расходов на учебники и учебные пособия, технические средства обучения, расходные материалы и хозяйственные нужды (за исключением расходов на содержание зданий и коммунальных расходов, осуществляемых из местных бюджетов) в соответствии с нормативами, установленными законами субъекта Российской Федерации'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-1701'
SET @Name = 'безвозмездные и безвозвратные перечисления бюджетам'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-2201'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-2401'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-2501'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.27.@@РС-А-2700'
SET @Name = 'организация оказания медицинской помощи на территории субъекта Российской Федерации в соответствии с территориальной программой государственных гарантий оказания гражданам Российской Федерации бесплатной медицинской помощи (за исключением медицинской помощи, оказываемой в федеральных медицинских учреждениях, перечень которых утверждается уполномоченным Правительством Российской Федерации федеральным органом исполнительной власти)'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-2701'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-2901'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-3001'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-3301'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.37.@@РС-А-3700'
SET @Name = 'материально-технического и финансового обеспечение оказания юридической помощи адвокатами в труднодоступных и малонаселенных местностях в соответствии с Федеральным законом от 31 мая 2002 года N 63-ФЗ "Об адвокатской деятельности и адвокатуре в Российской Федерации", определение размера, порядка оплаты труда адвокатов, оказывающих бесплатную юридическую помощь гражданам Российской Федерации в рамках государственной системы бесплатной юридической помощи, и компенсаций их расходов на оказание такой помощи, а также учреждения, материально-технического и финансового обеспечения деятельности государственных юридических бюро в соответствии с Федеральным законом "О бесплатной юридической помощи в Российской Федерации"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-3701'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-3901'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-4001'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.52.@@РС-А-5200'
SET @Name = 'утверждение схем территориального планирования субъекта Российской Федерации, утверждения документации по планировке территории для размещения объектов капитального строительства регионального значения, утверждения региональных нормативов градостроительного проектирования, выдачи разрешения на строительство объекта капитального строительства в случаях, предусмотренных Градостроительным кодексом Российской Федерации'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-5401'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-6901'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-7001'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '@@РС-А-7201'
SET @Name = 'оплата труда и начисления на нее'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.84.@@РС-А-8400'
SET @Name = 'поддержка социально ориентированных некоммерческих организаций, благотворительной деятельности и добровольчества, организация и осуществление региональных и межмуниципальных программ поддержки социально ориентированных некоммерческих организаций, благотворительной деятельности и добровольчества'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.85.@@РС-А-8500'
SET @Name = 'создание благоприятных условий для развития туризма в субъекте Российской Федерации'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.86.@@РС-А-8600'
SET @Name = 'реализация полномочий в сфере теплоснабжения, предусмотренных Федеральным законом "О теплоснабжении"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.87.@@РС-А-8700'
SET @Name = 'обеспечение гарантий равенства политических партий, представленных в законодательном (представительном) органе государственной власти субъекта Российской Федерации, при освещении их деятельности региональными телеканалами и радиоканалами'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.88.@@РС-А-8800'
SET @Name = 'реализация государственной политики в области торговой деятельности на территории субъекта Российской Федерации, проведение информационно-аналитического наблюдения за состоянием рынка определенного товара и осуществлением торговой деятельности на территории субъекта Российской Федерации, разработка и реализация мероприятий, содействующих развитию торговой деятельности на территории субъекта Российской Федерации и осуществление полномочий, предусмотренных Федеральным законом от 28 декабря 2009 года N 381-ФЗ "Об основах государственного регулирования торговой деятельности в Российской Федерации"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.89.@@РС-А-8900'
SET @Name = 'осуществление регионального государственного надзора в области охраны и использования особо охраняемых природных территорий'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.90.@@РС-А-9000'
SET @Name = 'осуществление регионального государственного надзора за сохранностью автомобильных дорог регионального и межмуниципального значения'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.91.@@РС-А-9100'
SET @Name = 'осуществление регионального государственного строительного надзора в случаях, предусмотренных Градостроительным кодексом Российской Федерации'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.92.@@РС-А-9200'
SET @Name = 'осуществление регионального государственного ветеринарного надзора'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.93.@@РС-А-9300'
SET @Name = 'осуществление регионального государственного надзора за применением подлежащих государственному регулированию цен (тарифов) на товары (услуги) в соответствии с законодательством Российской Федерации'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.94.@@РС-А-9400'
SET @Name = 'осуществление регионального государственного надзора за проведением региональных лотерей'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.95.@@РС-А-9500'
SET @Name = 'создание искусственного земельного участка в соответствии с федеральным законом'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.96.@@РС-А-9600'
SET @Name = 'принятие мер по организации проведения технического осмотра транспортных средств в соответствии с законодательством в области технического осмотра транспортных средств'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.97.@@РС-А-9700'
SET @Name = 'утверждение нормативов минимальной обеспеченности населения пунктами технического осмотра для субъектов Российской Федерации и для входящих в их состав муниципальных образований'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.98.@@РС-А-9800'
SET @Name = 'осуществление полномочий в области содействия занятости населения, предусмотренных Законом Российской Федерации от 19 апреля 1991 года N 1032-1 "О занятости населения в Российской Федерации"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.99.@@РС-А-9900'
SET @Name = 'финансового обеспечения получения гражданами дошкольного, начального общего, основного общего и среднего (полного) общего образования в имеющих государственную аккредитацию негосударственных общеобразовательных учреждениях в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда педагогических работников, расходов на учебники и учебные, учебно-наглядные пособия, технические средства обучения, игры, игрушки, расходные материалы в соответствии с нормативами финансового обеспечения образовательной деятельности государственных образовательных учреждений субъектов Российской Федерации и муниципальных образовательных учреждений'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO

DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.43.@@РП-А-4300'
SET @Name = 'оказание поддержки социально ориентированным некоммерческим организациям в пределах полномочий, установленных статьями 31.1 и 31.3 Федералнього закона от 12 января 1996 года № 7-ФЗ "О некоммерческих организациях"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.48.@@РП-А-4800'
SET @Name = 'предоставление помещения для работы на обслуживаемом административном участке поселения сотруднику, замещающему должность участкового уполномоченного полиции'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.49.@@РП-А-4900'
SET @Name = 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.85.@@РП-А-8500'
SET @Name = 'полномочия в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '1.1.87.@@РП-А-8700'
SET @Name = 'Осуществление международных и внешнеэкономических связей в соответствии с федеральными законами'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '2.1.44.@@РМ-А-4400'
SET @Name = 'предоставление помещения для работы на обслуживаемом административном участке муниципального района сотруднику, замещающему должность участкового уполномоченного полиции'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '2.1.45.@@РМ-А-4500'
SET @Name = 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '2.1.85.@@РМ-А-8500'
SET @Name = 'полномочия в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '2.1.87.@@РМ-А-8700'
SET @Name = 'осуществление международных и внешнеэкономических связей в соответствии с федеральными законами'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.30.@@РГ-А-3000'
SET @Name = 'формирование муниципального архива'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.52.@@РГ-А-5200'
SET @Name = 'предоставление помещения для работы на обслуживаемом административном участке городского округа сотруднику, замещающему должность участкового уполномоченного полиции'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.53.@@РГ-А-5300'
SET @Name = 'до 1 января 2017 года предоставление сотруднику, замещающему должность участкового уполномоченного полиции, и членам его семьи жилого помещения на период выполнения сотрудником обязанностей по указанной должности'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.85.@@РГ-А-8500'
SET @Name = 'полномочия в сфере водоснабжения и водоотведения, предусмотренными Федеральным законом "О водоснабжении и водоотведении"'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @Code VARCHAR(50),
@Name VARCHAR(8000), @link INT , @link_self int
SET @Code = '3.1.87.@@РГ-А-8700'
SET @Name = 'осуществление международных и внешнеэкономических связей в соответствии с федеральными законами'
SET @Link = NULL
SELECT @Link = Link
FROM dbo.report_kbk 
WHERE code_form = 'РРО2' AND code = @code AND isnull(end_date, '20990101') >= '20990101'

IF @Link IS NOT NULL AND NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @Link AND date ='20130609')  
BEGIN 
   INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
   SELECT @Link, '20130609', LEFT(@Name, 250), @Name
   
   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link
END
GO
DECLARE @LS INT, @link INT 
SELECT @LS = Link FROM dbo.report_kbk WHERE code_form = 'РРО' AND code = '1.@@РС-А' AND YEAR(ISNULL([end_date], '20990101')) > 2012

IF NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = 'РРО' AND code = '1.75.@@РС-А-7500' AND YEAR(ISNULL([end_date], '20990101')) > 2012)
BEGIN  
   INSERT dbo.report_kbk ([Code], [Link_self], [Code_Form], [Childrens], [Name], [ImageIndex], [Code_str], [property], [add_info], [orders], [Long_name], [begin_date], [end_date])
   VALUES ('1.75.@@РС-А-7500', @LS, 'РРО', 0, LEFT('обеспечение государственных гарантий прав граждан на получение общедоступного и бесплатного дошкольного, начального общего, основного общего, среднего (полного) общего образования, а также дополнительного образования в общеобразовательных учреждениях путем выделения субвенций местным бюджетам в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда работников общеобразовательных учреждений, расходов на учебники и учебные пособия, технические средства обучения, расходные материалы и хозяйственные нужды (за исключением расходов на содержание зданий и коммунальных расходов, осуществляемых из местных бюджетов) в соответствии с нормативами, установленными законами субъекта Российской Федерации', 250),
   0, '', 0, '', 0, 'обеспечение государственных гарантий прав граждан на получение общедоступного и бесплатного дошкольного, начального общего, основного общего, среднего (полного) общего образования, а также дополнительного образования в общеобразовательных учреждениях путем выделения субвенций местным бюджетам в размере, необходимом для реализации основных общеобразовательных программ в части финансирования расходов на оплату труда работников общеобразовательных учреждений, расходов на учебники и учебные пособия, технические средства обучения, расходные материалы и хозяйственные нужды (за исключением расходов на содержание зданий и коммунальных расходов, осуществляемых из местных бюджетов) в соответствии с нормативами, установленными законами субъекта Российской Федерации',
   '20130609', NULL)

   SET @link = @@identity

   EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK = @Link


END 
GO


EXEC [dbo].[RT_RRO_REORDER_DICT_RO] 0
EXEC [dbo].[RT_RRO_REORDER_DICT_RO] 1
GO

GO
UPDATE K
SET end_date = (SELECT end_date FROM dbo.report_kbk K1 WHERE K1.link = K.link_self)
from dbo.report_kbk K 
WHERE EXISTS(SELECT * FROM dbo.report_kbk K1 WHERE K1.link = K.link_self AND isnull(K.[end_date], '20990101') > isnull(K1.[end_date], '20990101'))
      AND code_form LIKE 'РРО%'

GO

GO
/****** Объект: Протокол проверки ЭЦП******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_SIGN_CHECK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_SIGN_CHECK')
	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 = 'REPORT_SIGN_CHECK')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'REPORT_SIGN_CHECK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_SIGN_CHECK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_SIGN_CHECK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK', 'Протокол проверки ЭЦП', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS__1_1_1_1_1_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_SQLTREE_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK', NAME = 'Протокол проверки ЭЦП', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORTS__1_1_1_1_1_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_SQLTREE_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_1', 'Поле-маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_1', NAME = 'Поле-маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_2', 'Код формы', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_2', NAME = 'Код формы', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_8')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_8', 'Результат', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_8', NAME = 'Результат', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_8'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_9')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_9', 'Автор подписи', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_9', NAME = 'Автор подписи', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_9'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_3', 'Период формы', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_3', NAME = 'Период формы', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_4', 'Наименование формы', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_4', NAME = 'Наименование формы', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_6')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_6', 'КОД БП', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_6', NAME = 'КОД БП', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_6'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_7')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_7', 'Бюджет', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_7', NAME = 'Бюджет', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_7'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK_10')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_CHECK_10', 'Данные сертификата', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_CHECK_10', NAME = 'Данные сертификата', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_CHECK_10'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORT_SIGN_DATA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORT_SIGN_DATA', 'Дата подписания', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REPORT_SIGN_DATA', NAME = 'Дата подписания', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_SIGN_CHECK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REPORT_SIGN_DATA'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK', 'TITLE', 'Протокол проверки ЭЦП'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK', 'HELP_TOPIC', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'ROWSOURCE', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_1', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_2', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_2', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_2', 'CONTROLSOURCE', 'm.cAlias + ".form_code"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_2', 'FIELD_DATA', 'form_code'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_8', 'TITLE', 'Результат'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_8', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_8', 'CONTROLSOURCE', 'm.cAlias + ".sign_res"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_8', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_8', 'FIELD_DATA', 'sign_res'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_9', 'TITLE', 'Автор подписи'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_9', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_9', 'CONTROLSOURCE', 'm.cAlias + ".sign_who"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_9', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_9', 'FIELD_DATA', 'sign_who'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_3', 'TITLE', 'Период'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_3', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_3', 'CONTROLSOURCE', 'm.cAlias + ".form_per"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_3', 'FIELD_DATA', 'form_per'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_4', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_4', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_4', 'CONTROLSOURCE', 'm.cAlias + ".form_name"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_4', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_4', 'FIELD_DATA', 'form_name'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_6', 'TITLE', 'КБП'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_6', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_6', 'CONTROLSOURCE', 'm.cAlias + ".form_kbp"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_6', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_6', 'FIELD_DATA', 'form_kbp'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_7', 'TITLE', 'Бюджет'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_7', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_7', 'CONTROLSOURCE', 'm.cAlias + ".form_type"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_7', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_7', 'FIELD_DATA', 'form_type'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_10', 'TITLE', 'Данные сертификата'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_10', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_10', 'CONTROLSOURCE', 'm.cAlias + ".sign_det"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_10', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_CHECK_10', 'FIELD_DATA', 'sign_det'
GO
EXEC X_SET_PROP 'REPORT_SIGN_DATA', 'TITLE', 'Дата подписания'
GO
EXEC X_SET_PROP 'REPORT_SIGN_DATA', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'REPORT_SIGN_DATA', 'CONTROLSOURCE', 'm.cAlias + ".date"'
GO
EXEC X_SET_PROP 'REPORT_SIGN_DATA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'REPORT_SIGN_DATA', 'FIELD_DATA', 'date'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORT_SIGN_CHECK', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORT_SIGN_CHECK', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


GO

UPDATE rc
SET [Dictionary_Where] = CASE WHEN isnull(rc.[Dictionary_Where], '') = '' THEN '%date%>=begin_date and %date%<=end_date' ELSE RTRIM(rc.[Dictionary_Where]) + ' AND %date%>=begin_date and %date%<=end_date' END   
FROM dbo.report_forms rf 
   LEFT JOIN dbo.report_tables rt ON rt.[Link_Form] = rf.[Link_Form]
   LEFT JOIN dbo.report_coloumns rc ON rc.[Link_Table] = rt.[Link_Table]
WHERE YEAR(START_DATE) = 2011 AND Code LIKE '[0-9]%[MG]%'
   AND isnull(rc.[Dictionary],'') <> ''
   AND COL_LENGTH(rc.[Dictionary], 'begin_date') IS NOT NULL
   AND COL_LENGTH(rc.[Dictionary], 'end_date') IS NOT NULL   
   AND isnull(rc.[Dictionary_Where], '') NOT LIKE '%date% >= begin_date and %date% <= end_date%'
   AND isnull(rc.[Dictionary_Where], '') NOT LIKE '%date%'  

GO
                           
                           
                    
GO
exec RN_SAVE_REPORT_KBK 0,'R_SPR_ATR_VID_773',0,'Справочник видов финансового обеспечения (деятельности)','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_ATR_VID_773',@link_self,'Справочник видов финансового обеспечения (деятельности)','HEADER'
GO
delete report_control_protokol
delete report_kbk where code_form= 'R_SPR_ATR_VID_773'
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 'b',0,'R_SPR_ATR_VID_773',1,'деятельность с целевыми средствами',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select 't',0,'R_SPR_ATR_VID_773',1,'средства во временном распоряжении',0,'',0,'','', '19000101','19000101',0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select 'v',0,'R_SPR_ATR_VID_773',1,'деятельность по оказанию услуг (работ)',0,'',0,'','', '19000101','19000101',0


GO


GO
-- Отчет "Сведения о доходах физических лиц"

/*** Сам отчет ***/

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(@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(8000)	/* Признак */,
	@nCheck2 int	/* Определить перечисленную сумму по проводкам */,
	@cText5 varchar(8000)	/* Перечисленная сумма НДФЛ за период */,
	@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(@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'),
		'Группа настроек',3, 
		(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'),
					'Расчетный год',4, 
					(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'),
							'2010'
						
						
						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'),
							'2010'
						
						
						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'),
							'2010'
						
						
						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'),
							'2010'
						
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'),
					'Показать реестр',5, 
					(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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
							'Вкл.'
						
						
						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'),
					'Номер файла (реестра)',6, 
					(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(2)'
						
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'
						
						
						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'),
					'Начинать нумерацию справок с',7, 
					(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'
						
						
						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'),
					'Признак',8, 
					(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'),
							'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_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'),
							'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_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'),
							''
						
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(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_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'
						
						
						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'
						
						
						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'
						
						
						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_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'),
					'Определить перечисленную сумму по проводкам',9, 
					(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'),
							'Выкл.'
						
						
						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'),
					'Перечисленная сумма НДФЛ за период',10, 
					(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(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_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'),
							''
						
						
						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




-- Отчет "Справка 2-НДФЛ для физлиц с договорами ГПХ"

/*** Сам отчет ***/

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)	/* Перечисленная сумма НДФЛ за период */
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'
						
						
						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'),
							'17059'
						
						
						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'),
							'17411'
						
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'),
							''
						
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'),
							'2011'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_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'),
							'2011'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_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'),
							'Текущий месяц'
						
						
						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'
						
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'),
					'Определить перечисленную сумму по проводкам',7, 
					(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'),
					'Перечисленная сумма НДФЛ за период',8, 
					(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


GO
update rt set script_str = 'KEY_SVOD=''xxx'' + isnull(COL(2),'''') + isnull(COL(3),'''') + isnull(COL(4),'''')' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т1         ' and start_date = '20081231' and rt.orders = 1
update rt set script_str = 'KEY_SVOD=''xxx'' + isnull(COL(2),'''') + isnull(COL(3),'''') + isnull(COL(4),'''') + isnull(COL(5),'''') + isnull(COL(6),'''')
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т2         ' and start_date = '20081231' and rt.orders = 1
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),1,''0'')+PADR(RTRIM(COL3),3,''0'')
KEY_WEB=LEFT(RTRIM(isnull(COL1,''''))+''0'',1)+LEFT(RTRIM(ISNULL(COL3,''''))+''0000'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''0000'',1,1)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''0000'',2,3)
KEY_SVOD=LEFT(CODE_ROW,1) + ''xxx'' + isnull(COL(2),'''') + isnull(COL(4),'''') + isnull(COL(5),'''')+ isnull(COL(6),'''')
KEY_SVOD_KS=3' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т5         ' and start_date = '20101231' and rt.orders = 1
update rt set script_str = 'CALC_SMETA=sql.call(''rv_pz_inventar'',m.cAlias,  0x0, @lsf, dateEndPeriod)
KEY_SVOD=''xxx'' +  isnull(COL(2),'''') + isnull(COL(3),'''')+ isnull(COL(4),'''')+ isnull(COL(5),'''')+ isnull(COL(6),'''')+ isnull(COL(8),'''')
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т6         ' and start_date = '20081231' and rt.orders = 1
update rt set script_str = 'KEY_SVOD=''xxx'' + isnull(COL(2),'''') + isnull(COL(3),'''')+ isnull(COL(4),'''')+ isnull(COL(5),'''')+ isnull(COL(6),'''')
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т7         ' and start_date = '20081231' and rt.orders = 1
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),14,''0'')+PADR(RTRIM(COL3),9,''0'')+LEFT(RTRIM(COL4)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''0000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',14)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL4,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,14)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',18,9)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(7),'''') + isnull(COL(8),'''') + isnull(COL(9),'''') + isnull(COL(10),'''') + isnull(COL(11),'''')
KEY_SVOD_KS=4
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503172G            ' and start_date = '20110101' and rt.orders = 1
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),4,''0'')+PADR(RTRIM(COL3),7,''0'')+PADR(RTRIM(COL4),3,''0'')+PADR(RTRIM(COL5),9,''0'')+LEFT(RTRIM(COL6)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',4)+LEFT(RTRIM(isnull(COL3,''''))+''0000000'',7)+LEFT(RTRIM(isnull(COL4,''''))+''000'',3)+LEFT(RTRIM(isnull(COL5,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL6,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,4)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',8,7)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',15,3)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',18,9)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(9),'''') + isnull(COL(10),'''') + isnull(COL(11),'''') + isnull(COL(12),'''') + isnull(COL(13),'''')
KEY_SVOD_KS=6
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503172G            ' and start_date = '20110101' and rt.orders = 2
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),14,''0'')+PADR(RTRIM(COL3),9,''0'')+LEFT(RTRIM(COL4)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''0000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',14)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL4,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,14)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',18,9)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
AUTOFILL_MASK=000XXXXXXXXXXXXXXXXXXXXXXXXXX
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(7),'''') 
KEY_SVOD_KS=4
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503372G            ' and start_date = '20110101' and rt.orders = 1
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),4,''0'')+PADR(RTRIM(COL3),7,''0'')+PADR(RTRIM(COL4),3,''0'')+PADR(RTRIM(COL5),9,''0'')+LEFT(RTRIM(COL6)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',4)+LEFT(RTRIM(isnull(COL3,''''))+''0000000'',7)+LEFT(RTRIM(isnull(COL4,''''))+''000'',3)+LEFT(RTRIM(isnull(COL5,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL6,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,4)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',8,7)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',15,3)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',18,9)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
AUTOFILL_MASK=000XXXX0000000000XXXXXXXXXXXX
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(7),'''') + isnull(COL(8),'''') + isnull(COL(9),'''') 
KEY_SVOD_KS=6

' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503372G            ' and start_date = '20110101' and rt.orders = 2
update rt set script_str = 'CALC_SMETA=exec dbo.RB_CALC_FORM_0503171G09 1,@depLink, @dateEndPeriod
KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),14,''0'')+PADR(RTRIM(COL3),9,''0'')+LEFT(RTRIM(COL4)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''0000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',14)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL4,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,14)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',18,9)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(6),'''') + isnull(COL(7),'''')
KEY_SVOD_KS=4
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503171G            ' and start_date = '20110301' and rt.orders = 1
update rt set script_str = 'CALC_SMETA=exec dbo.RB_CALC_FORM_0503171G09 2,@depLink, @dateEndPeriod
KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),4,''0'')+PADR(RTRIM(COL3),7,''0'')+PADR(RTRIM(COL4),3,''0'')+PADR(RTRIM(COL5),9,''0'')+LEFT(RTRIM(COL6)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',4)+LEFT(RTRIM(isnull(COL3,''''))+''0000000'',7)+LEFT(RTRIM(isnull(COL4,''''))+''000'',3)+LEFT(RTRIM(isnull(COL5,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL6,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,4)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',8,7)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',15,3)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',18,9)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(8),'''') + isnull(COL(9),'''')
KEY_SVOD_KS=6' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503171G            ' and start_date = '20110301' and rt.orders = 2
update rt set script_str = 'CALC_SKELET=sql.call("dbo.RO_CALC_SKELET",m.cAlias,0x0,''0503167G'',1,''20081231'')
KEY_SVOD=''xxx'' + isnull(COL(1),'''') + isnull(COL(2),'''') + isnull(COL(3),'''') + isnull(COL(4),'''') 
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503167G            ' and start_date = '20110101' and rt.orders = 1
update rt set script_str = 'KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),4,''0'')+PADR(RTRIM(COL3),7,''0'')+PADR(RTRIM(COL4),3,''0'')
KEY_WEB=LEFT(RTRIM(isnull(COL1,''''))+''0000'',3)+LEFT(RTRIM(ISNULL(COL2,''''))+''00000000000'',4)+LEFT(RTRIM(ISNULL(COL3,''''))+''00000000000000'',7)+LEFT(RTRIM(ISNULL(COL4,''''))+''00000000000000'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',4,4)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',8,7)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',15,3)
KEY_SVOD=LEFT(code_row, 14) + ''xxx'' + isnull(COL(5),'''') + isnull(COL(6),'''') 
KEY_SVOD_KS=4' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503162G            ' and start_date = '20110101' and rt.orders = 1
update rt set script_str = 'CALC_SMETA=exec dbo.RB_CALC_FORM_0503371G09 @depLink, @dateEndPeriod
KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),14,''0'')+PADR(RTRIM(COL3),9,''0'')+LEFT(RTRIM(COL4)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''0000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',14)+LEFT(RTRIM(isnull(COL3,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL4,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,14)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',18,9)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
AUTOFILL_MASK=000XXXXXXXXXXXXXXXXXXXXXXXXXX
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(6),'''') + isnull(COL(7),'''') 
KEY_SVOD_KS=4
' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503371G            ' and start_date = '20110101' and rt.orders = 1
update rt set script_str = 'CALC_SMETA=exec dbo.RB_CALC_FORM_0503371G09 @depLink, @dateEndPeriod
KEY_FOX=PADR(RTRIM(COL1),3,''0'')+PADR(RTRIM(COL2),4,''0'')+PADR(RTRIM(COL3),7,''0'')+PADR(RTRIM(COL4),3,''0'')+PADR(RTRIM(COL5),9,''0'')+LEFT(RTRIM(COL6)+''001'',3)
KEY_WEB=LEFT(RTRIM(ISNULL(COL1,''''))+''000'',3)+LEFT(RTRIM(isnull(COL2,''''))+''00000000000000'',4)+LEFT(RTRIM(isnull(COL3,''''))+''0000000'',7)+LEFT(RTRIM(isnull(COL4,''''))+''000'',3)+LEFT(RTRIM(isnull(COL5,''''))+''00000000000'',9)+LEFT(RTRIM(isnull(COL6,''''))+''001'',3)
SPLIT=COL1=SUBSTRING(RTRIM(CODE_ROW)+''00000000000000000'',1,3)#COL2=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000'',4,4)#COL3=SUBSTRING(RTRIM(CODE_ROW)+''000000000000000000000000000000'',8,7)#COL4=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',15,3)#COL5=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',18,9)#COL6=SUBSTRING(RTRIM(CODE_ROW)+''0000000000000000000000000000000'',27,3)
AUTOFILL_MASK=000XXXX0000000000XXXXXXXXXXXX
KEY_SVOD=LEFT(CODE_ROW,26)+''xxx'' + isnull(COL(8),'''') + isnull(COL(9),'''')
KEY_SVOD_KS=6

' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503371G            ' and start_date = '20110101' and rt.orders = 2
update rt set script_str = 'KEY_SVOD=''xxx'' + isnull(COL(2),'''') + isnull(COL(3),'''') + isnull(COL(4),'''')' from dbo.report_tables rt join dbo.report_forms rf on rt.link_form = rf.link_form where rf.code = '0503160G_т3         ' and start_date = '20110101' and rt.orders = 1
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 (4717.00, 'Форма № Т-8 (приказ об увольнении)', 2688.00, 'SYS_T8_REPORT', 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 (496.00, 'Причина2', 2689.00, 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', NULL, 999.00, 4717.00, 499.00, 'SQUERY_CALC_FIELD', 'SYS_T8_REPORT', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1493.00, 'Причина1', 2689.00, '11150D66-5722-4BD0-A525-EB0366F67E58', NULL, 999.00, 4717.00, 499.00, 'SQUERY_CALC_FIELD', 'SYS_T8_REPORT', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2728.00, 'Приказ об увольнении', 2686.00, '9CA46765-7113-4068-8D54-35015F1AA6CB', NULL, 999.00, 4717.00, 3664.00, 'SQUERY_FIELD', 'SYS_T8_REPORT', 'SYS_ED538252-298D-4234-8ACD-18505C04C640', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2856.00, 'Одиночный/групповой', 2700.00, 'ORDER_DIS_FACE1_MAIN_PARAM', NULL, 3.00, 4717.00, 45.00, 'SQUERY_LINK_NASTR', 'SYS_T8_REPORT', 'SYS_2452195_0I40N0PAI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3250.00, 'Приказ', 2686.00, '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', NULL, 999.00, 4717.00, 3565.00, 'SQUERY_FIELD', 'SYS_T8_REPORT', 'SYS_5EA1DEDD-F03B-4285-AFCC-3E0657166FBE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7397.00, 'Ссылка на документ', 2698.00, 'ORDER_DIS_FACE_MAIN_PARAM', NULL, 1.00, 4717.00, 7392.00, 'SQUERY_NASTR', 'SYS_T8_REPORT', 'SYS_2452562_0SD0H9SSG', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7482.00, 'Организация', 2686.00, '2452562_0SD0SJB1F', NULL, 999.00, 4717.00, 7214.00, 'SQUERY_FIELD', 'SYS_T8_REPORT', '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 (10899.00, 'Показывать "Решение проф. орг"', 2700.00, '2452909_1220P23L2', NULL, 2.00, 4717.00, 49.00, 'SQUERY_LINK_NASTR', 'SYS_T8_REPORT', 'SYS_2452195_0I40N8IJQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (22691.00, 'Показывать дату приема на работу', 2700.00, 'F7CDE295-51B1-496A-92F7-6B480DFB491B', NULL, 4.00, 4717.00, 49.00, 'SQUERY_LINK_NASTR', 'SYS_T8_REPORT', 'SYS_2452195_0I40N8IJQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (837.00, '', 2693.00, 'DBAE3115-960A-43E1-9826-4ED74327FCD9', NULL, 0.00, 1493.00, 499.00, 'SQUERY_LINK_BASE', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (838.00, '', 2693.00, 'C15CC9FE-E028-4E22-A081-4792A96B9DD7', NULL, 0.00, 496.00, 499.00, 'SQUERY_LINK_BASE', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (975.00, '', 2691.00, '69BC329C-0459-4433-AE50-19862CFB0D8B', NULL, 0.00, 1493.00, 499.00, 'SQUERY_LINK_SOURCE', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (979.00, '', 2691.00, 'EB36A079-8336-45AF-B681-006AFDB50680', NULL, 0.00, 496.00, 499.00, 'SQUERY_LINK_SOURCE', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1027.00, '', 2695.00, 'CD9FA874-4C12-4854-B43C-75AAC0DBE42C', NULL, 0.00, 496.00, 4717.00, 'SQUERY_LINK_SQUERY', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1031.00, '', 2695.00, '6638D4EC-2692-4812-B50B-35933D0E12B8', NULL, 0.00, 1493.00, 4717.00, 'SQUERY_LINK_SQUERY', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2721.00, 'Номер приказа', 2686.00, '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', NULL, 999.00, 3250.00, 3568.00, 'SQUERY_FIELD', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_8079EE82-29C0-4298-8E5A-33C7150A3045', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2725.00, '', 2694.00, 'C1816145-F586-4307-98F3-3860CE184D98', NULL, 0.00, 3250.00, 3575.00, 'SQUERY_LINK_STATE', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_2F599A1F-3B8D-4552-8E86-A5073F28432E', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2726.00, '', 2694.00, 'F397559F-A17D-46A1-A52E-250198950B96', NULL, 1.00, 3250.00, 3605.00, 'SQUERY_LINK_STATE', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_824D2059-3306-475B-82DA-101FCBF54AB2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2727.00, '', 2694.00, '9A049521-9855-4FA6-A8C7-8213058ADF6E', NULL, 2.00, 3250.00, 3687.00, 'SQUERY_LINK_STATE', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_1B732E13-F88D-4E0E-90CC-CF5E624E5644', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2729.00, '', 2693.00, 'DD120736-F13A-415C-AE70-B680C1D5516B', NULL, 0.00, 2728.00, 3664.00, 'SQUERY_LINK_BASE', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_ED538252-298D-4234-8ACD-18505C04C640', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2730.00, '', 2691.00, '88CEA2D7-64F2-4656-A4C3-940A20D2403E', NULL, 0.00, 2728.00, 3664.00, 'SQUERY_LINK_SOURCE', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_ED538252-298D-4234-8ACD-18505C04C640', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2731.00, '', 2695.00, '152E84A5-A2E9-4DEF-9CDF-D9759712F2C4', NULL, 0.00, 2728.00, 4717.00, 'SQUERY_LINK_SQUERY', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2732.00, 'Дата увольнения', 2686.00, '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', NULL, 999.00, 2728.00, 3672.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_893603F9-4786-4117-A909-1949202F95F2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2736.00, 'Должность (по документу)', 2686.00, '5549F590-E1D6-46F2-BC9C-892235C1D6B8', NULL, 999.00, 2728.00, 3671.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_A71ECB7D-C781-45FC-9F9E-323002F96CA5', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2740.00, 'Подразделение (по документу)', 2686.00, '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', NULL, 999.00, 2728.00, 3670.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_AB3A37D7-9AD6-43B8-923A-A0C88C514559', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2744.00, '', 2694.00, 'BC7EE87D-D266-406A-A9FF-5DF0E2E9F2FE', NULL, 0.00, 2728.00, 6862.00, 'SQUERY_LINK_STATE', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_2452532_0RJ0OBNJG', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2745.00, 'ФИО (по документу)', 2686.00, '8FAA1305-7322-409F-93C4-FF7C015ED3AF', NULL, 999.00, 2728.00, 3669.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_781AA113-0E94-4449-969B-D55E81D49B57', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2749.00, 'Табельный номер (по документу)', 2686.00, 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', NULL, 999.00, 2728.00, 3668.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_460EE753-C248-4A7D-8A02-257AB22A9391', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2753.00, 'Причина увольнения', 2686.00, '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', NULL, 999.00, 2728.00, 3673.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_35ADEC2C-8205-4C14-B162-FA36A04F7158', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2757.00, 'Решение профсоюзного органа  - номер', 2686.00, 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', NULL, 999.00, 2728.00, 3677.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_42B4A7C0-CF06-4105-8FBB-39F5BE1059BA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2761.00, 'Решение профсоюзного органа - дата', 2686.00, '537B8C7D-E25D-4D01-8D92-A654AF1974D3', NULL, 999.00, 2728.00, 3676.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_F6DDC2D8-EFD9-40AF-ADF4-BD2B335D45C9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2864.00, 'Основание увольнения', 2686.00, '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', NULL, 999.00, 2728.00, 2861.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_3258C915-0778-4ECE-A53E-56AA74EFEA0B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2868.00, 'Трудовой договор - дата', 2686.00, 'A8563833-D7E3-4919-8E89-0A1BBB81815A', NULL, 999.00, 2728.00, 2862.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_9FA3C73A-44F8-4A58-B08F-C99352E54AB4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2872.00, 'Трудовой договор - номер', 2686.00, 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', NULL, 999.00, 2728.00, 2863.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_5DAEC686-77E8-46C1-854E-A2A4C666B809', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3251.00, '', 2693.00, '9DD8AEE4-9508-41BB-8357-DF849C905AD7', NULL, 0.00, 3250.00, 3565.00, 'SQUERY_LINK_BASE', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_5EA1DEDD-F03B-4285-AFCC-3E0657166FBE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3252.00, '', 2691.00, '601738CB-7577-47C3-9253-BD5AE9CD4DDB', NULL, 0.00, 3250.00, 3565.00, 'SQUERY_LINK_SOURCE', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_5EA1DEDD-F03B-4285-AFCC-3E0657166FBE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3253.00, '', 2695.00, 'C4D98BA8-C779-440F-8DC3-56D946231925', NULL, 0.00, 3250.00, 4717.00, 'SQUERY_LINK_SQUERY', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3254.00, 'Дата приказа', 2686.00, '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', NULL, 999.00, 3250.00, 3569.00, 'SQUERY_FIELD', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SYS_DA64EB5D-A583-4D23-B261-75AC03C76BE7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7483.00, '', 2693.00, '2452562_0SD0SJB8Z', NULL, 0.00, 7482.00, 7214.00, 'SQUERY_LINK_BASE', '2452562_0SD0SJB1F', '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 (7484.00, '', 2691.00, '2452562_0SD0SJB99', NULL, 0.00, 7482.00, 7214.00, 'SQUERY_LINK_SOURCE', '2452562_0SD0SJB1F', '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 (7485.00, '', 2695.00, '2452562_0SD0SJB9S', NULL, 0.00, 7482.00, 4717.00, 'SQUERY_LINK_SQUERY', '2452562_0SD0SJB1F', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7486.00, 'Наименование', 2686.00, '2452562_0SD0SJBBQ', NULL, 999.00, 7482.00, 7216.00, 'SQUERY_FIELD', '2452562_0SD0SJB1F', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7490.00, 'ОКПО', 2686.00, '2452562_0SD0SJCV4', NULL, 999.00, 7482.00, 7221.00, 'SQUERY_FIELD', '2452562_0SD0SJB1F', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7494.00, '', 2694.00, '2452562_0SD0SJUGS', NULL, 0.00, 7482.00, 7228.00, 'SQUERY_LINK_STATE', '2452562_0SD0SJB1F', 'SYS_2452558_0S90YOTTN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (25941.00, 'Расчет отпускных на', 2686.00, '15662658-9C36-4490-A7A3-34CC2A534FCA', NULL, 999.00, 2728.00, 25940.00, 'SQUERY_FIELD', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SYS_141E5D0C-14AD-43AD-BF5D-456FC5A36058', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2718.00, '', 2693.00, '86F993C0-5A26-41B8-ADFE-0135CBF683B9', NULL, 0.00, 3254.00, 3569.00, 'SQUERY_LINK_BASE', '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', 'SYS_DA64EB5D-A583-4D23-B261-75AC03C76BE7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2719.00, '', 2691.00, '563B9E8F-B641-49CA-AE48-6D40454F78F8', NULL, 0.00, 3254.00, 3569.00, 'SQUERY_LINK_SOURCE', '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', 'SYS_DA64EB5D-A583-4D23-B261-75AC03C76BE7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2720.00, '', 2695.00, '2E49DADB-202C-4208-A129-4870B96C230F', NULL, 0.00, 3254.00, 4717.00, 'SQUERY_LINK_SQUERY', '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2722.00, '', 2693.00, '0B9792BB-F241-4F06-B599-14104325ECB9', NULL, 0.00, 2721.00, 3568.00, 'SQUERY_LINK_BASE', '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', 'SYS_8079EE82-29C0-4298-8E5A-33C7150A3045', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2723.00, '', 2691.00, '79DFAFDB-CD27-4CA2-8456-976AB388A74C', NULL, 0.00, 2721.00, 3568.00, 'SQUERY_LINK_SOURCE', '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', 'SYS_8079EE82-29C0-4298-8E5A-33C7150A3045', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2724.00, '', 2695.00, '377AD769-9972-461F-A6B6-91DAAB885334', NULL, 0.00, 2721.00, 4717.00, 'SQUERY_LINK_SQUERY', '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2733.00, '', 2693.00, '4AB84431-60F4-4D32-9D8D-D3850DA3E305', NULL, 0.00, 2732.00, 3672.00, 'SQUERY_LINK_BASE', '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', 'SYS_893603F9-4786-4117-A909-1949202F95F2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2734.00, '', 2691.00, '90DCF187-6EB2-41FB-BD12-AA80F62D622E', NULL, 0.00, 2732.00, 3672.00, 'SQUERY_LINK_SOURCE', '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', 'SYS_893603F9-4786-4117-A909-1949202F95F2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2735.00, '', 2695.00, '7155F15A-860D-49BA-914C-7699644838C0', NULL, 0.00, 2732.00, 4717.00, 'SQUERY_LINK_SQUERY', '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2737.00, '', 2693.00, 'ACAD105F-2182-4590-85FD-5F6BF23CCE4C', NULL, 0.00, 2736.00, 3671.00, 'SQUERY_LINK_BASE', '5549F590-E1D6-46F2-BC9C-892235C1D6B8', 'SYS_A71ECB7D-C781-45FC-9F9E-323002F96CA5', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2738.00, '', 2691.00, '8B17B029-5093-48B0-9CD6-453836285259', NULL, 0.00, 2736.00, 3671.00, 'SQUERY_LINK_SOURCE', '5549F590-E1D6-46F2-BC9C-892235C1D6B8', 'SYS_A71ECB7D-C781-45FC-9F9E-323002F96CA5', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2739.00, '', 2695.00, '3F0F3782-34DE-480B-B5FC-43106EA1125D', NULL, 0.00, 2736.00, 4717.00, 'SQUERY_LINK_SQUERY', '5549F590-E1D6-46F2-BC9C-892235C1D6B8', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2741.00, '', 2693.00, '2A56898E-8516-4E85-A4ED-89B869D05FA8', NULL, 0.00, 2740.00, 3670.00, 'SQUERY_LINK_BASE', '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', 'SYS_AB3A37D7-9AD6-43B8-923A-A0C88C514559', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2742.00, '', 2691.00, 'EEC13500-C10F-473B-A157-43D6B040EE04', NULL, 0.00, 2740.00, 3670.00, 'SQUERY_LINK_SOURCE', '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', 'SYS_AB3A37D7-9AD6-43B8-923A-A0C88C514559', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2743.00, '', 2695.00, 'BA932714-7E0B-4E89-BB2A-100332229AC7', NULL, 0.00, 2740.00, 4717.00, 'SQUERY_LINK_SQUERY', '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2746.00, '', 2693.00, 'BB388956-8200-46B9-B64D-695E8F0FE44B', NULL, 0.00, 2745.00, 3669.00, 'SQUERY_LINK_BASE', '8FAA1305-7322-409F-93C4-FF7C015ED3AF', 'SYS_781AA113-0E94-4449-969B-D55E81D49B57', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2747.00, '', 2691.00, 'E16D81B4-1B9A-4DFC-A01B-420A2D6772BB', NULL, 0.00, 2745.00, 3669.00, 'SQUERY_LINK_SOURCE', '8FAA1305-7322-409F-93C4-FF7C015ED3AF', 'SYS_781AA113-0E94-4449-969B-D55E81D49B57', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2748.00, '', 2695.00, '1A650A74-EE49-44BB-97A7-211E05DDC917', NULL, 0.00, 2745.00, 4717.00, 'SQUERY_LINK_SQUERY', '8FAA1305-7322-409F-93C4-FF7C015ED3AF', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2750.00, '', 2693.00, '834685BE-2665-4A97-83BB-0B0BD337C21C', NULL, 0.00, 2749.00, 3668.00, 'SQUERY_LINK_BASE', 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', 'SYS_460EE753-C248-4A7D-8A02-257AB22A9391', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2751.00, '', 2691.00, 'AC8682A9-B11B-4C9A-B8A8-C939CF2BE21A', NULL, 0.00, 2749.00, 3668.00, 'SQUERY_LINK_SOURCE', 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', 'SYS_460EE753-C248-4A7D-8A02-257AB22A9391', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2752.00, '', 2695.00, 'EFCB34B4-0EB3-4E0A-A032-EA3D6AEAC2F2', NULL, 0.00, 2749.00, 4717.00, 'SQUERY_LINK_SQUERY', 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2754.00, '', 2693.00, '47928F18-0542-4032-A337-C27C4074D084', NULL, 0.00, 2753.00, 3673.00, 'SQUERY_LINK_BASE', '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', 'SYS_35ADEC2C-8205-4C14-B162-FA36A04F7158', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2755.00, '', 2691.00, 'BF2407D2-4C6A-4270-AAFF-37B212F06A3C', NULL, 0.00, 2753.00, 3673.00, 'SQUERY_LINK_SOURCE', '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', 'SYS_35ADEC2C-8205-4C14-B162-FA36A04F7158', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2756.00, '', 2695.00, '2C0D17DC-1ACC-4F80-A172-5DCCA7D211A3', NULL, 0.00, 2753.00, 4717.00, 'SQUERY_LINK_SQUERY', '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2758.00, '', 2693.00, '8112AD62-09C4-4986-9EBE-148F3C35C553', NULL, 0.00, 2757.00, 3677.00, 'SQUERY_LINK_BASE', 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', 'SYS_42B4A7C0-CF06-4105-8FBB-39F5BE1059BA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2759.00, '', 2691.00, 'EC3E2618-6A84-4EE0-9D1A-1680B542AE81', NULL, 0.00, 2757.00, 3677.00, 'SQUERY_LINK_SOURCE', 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', 'SYS_42B4A7C0-CF06-4105-8FBB-39F5BE1059BA', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2760.00, '', 2695.00, 'DA586F07-F649-4CA7-9605-6A963BA2343B', NULL, 0.00, 2757.00, 4717.00, 'SQUERY_LINK_SQUERY', 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2762.00, '', 2693.00, '48B502A5-10BF-481E-A1A8-A10B0DACB9E6', NULL, 0.00, 2761.00, 3676.00, 'SQUERY_LINK_BASE', '537B8C7D-E25D-4D01-8D92-A654AF1974D3', 'SYS_F6DDC2D8-EFD9-40AF-ADF4-BD2B335D45C9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2763.00, '', 2691.00, '1965CAE1-29F1-44A1-A86C-733A40E42EE0', NULL, 0.00, 2761.00, 3676.00, 'SQUERY_LINK_SOURCE', '537B8C7D-E25D-4D01-8D92-A654AF1974D3', 'SYS_F6DDC2D8-EFD9-40AF-ADF4-BD2B335D45C9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2764.00, '', 2695.00, 'B5373FE2-B6F0-4817-85E3-A1415ED78EEC', NULL, 0.00, 2761.00, 4717.00, 'SQUERY_LINK_SQUERY', '537B8C7D-E25D-4D01-8D92-A654AF1974D3', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2865.00, '', 2693.00, '979AC617-D113-4208-B7FC-24615BB58BC7', NULL, 0.00, 2864.00, 2861.00, 'SQUERY_LINK_BASE', '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', 'SYS_3258C915-0778-4ECE-A53E-56AA74EFEA0B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2866.00, '', 2691.00, '101F8599-6284-4CDD-AA1B-D2B1A3089F5F', NULL, 0.00, 2864.00, 2861.00, 'SQUERY_LINK_SOURCE', '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', 'SYS_3258C915-0778-4ECE-A53E-56AA74EFEA0B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2867.00, '', 2695.00, '0E9B9A56-BE3C-45C3-9079-E687EF079987', NULL, 0.00, 2864.00, 4717.00, 'SQUERY_LINK_SQUERY', '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2869.00, '', 2693.00, '14C52035-B8AD-4BD8-AA6A-EEA556293865', NULL, 0.00, 2868.00, 2862.00, 'SQUERY_LINK_BASE', 'A8563833-D7E3-4919-8E89-0A1BBB81815A', 'SYS_9FA3C73A-44F8-4A58-B08F-C99352E54AB4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2870.00, '', 2691.00, '396B074A-4DB1-4C5A-BFB3-35081CA0E35A', NULL, 0.00, 2868.00, 2862.00, 'SQUERY_LINK_SOURCE', 'A8563833-D7E3-4919-8E89-0A1BBB81815A', 'SYS_9FA3C73A-44F8-4A58-B08F-C99352E54AB4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2871.00, '', 2695.00, 'D3E4F255-8260-4526-AFCE-129EF0004213', NULL, 0.00, 2868.00, 4717.00, 'SQUERY_LINK_SQUERY', 'A8563833-D7E3-4919-8E89-0A1BBB81815A', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2873.00, '', 2693.00, '4333F8FF-75FF-4D9B-BFED-90DDE52797D0', NULL, 0.00, 2872.00, 2863.00, 'SQUERY_LINK_BASE', 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', 'SYS_5DAEC686-77E8-46C1-854E-A2A4C666B809', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2874.00, '', 2691.00, '977836FC-1DE3-4FBC-8BB2-96186C97F9D2', NULL, 0.00, 2872.00, 2863.00, 'SQUERY_LINK_SOURCE', 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', 'SYS_5DAEC686-77E8-46C1-854E-A2A4C666B809', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2875.00, '', 2695.00, '20FE2AFE-BBD1-4024-AB8F-1DF62A2657BA', NULL, 0.00, 2872.00, 4717.00, 'SQUERY_LINK_SQUERY', 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7487.00, '', 2693.00, '2452562_0SD0SJBDE', NULL, 0.00, 7486.00, 7216.00, 'SQUERY_LINK_BASE', '2452562_0SD0SJBBQ', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7488.00, '', 2691.00, '2452562_0SD0SJBDP', NULL, 0.00, 7486.00, 7216.00, 'SQUERY_LINK_SOURCE', '2452562_0SD0SJBBQ', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7489.00, '', 2695.00, '2452562_0SD0SJBE9', NULL, 0.00, 7486.00, 4717.00, 'SQUERY_LINK_SQUERY', '2452562_0SD0SJBBQ', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7491.00, '', 2693.00, '2452562_0SD0SJCWI', NULL, 0.00, 7490.00, 7221.00, 'SQUERY_LINK_BASE', '2452562_0SD0SJCV4', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7492.00, '', 2691.00, '2452562_0SD0SJCWT', NULL, 0.00, 7490.00, 7221.00, 'SQUERY_LINK_SOURCE', '2452562_0SD0SJCV4', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (7493.00, '', 2695.00, '2452562_0SD0SJCXC', NULL, 0.00, 7490.00, 4717.00, 'SQUERY_LINK_SQUERY', '2452562_0SD0SJCV4', 'SYS_T8_REPORT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (25942.00, '', 2693.00, '2CCFC31C-0E97-4A49-8B16-CC8AF7201F59', NULL, 0.00, 25941.00, 25940.00, 'SQUERY_LINK_BASE', '15662658-9C36-4490-A7A3-34CC2A534FCA', 'SYS_141E5D0C-14AD-43AD-BF5D-456FC5A36058', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (25943.00, '', 2691.00, 'F27FCDCE-B064-4437-8C8F-A02702E2A69C', NULL, 0.00, 25941.00, 25940.00, 'SQUERY_LINK_SOURCE', '15662658-9C36-4490-A7A3-34CC2A534FCA', 'SYS_141E5D0C-14AD-43AD-BF5D-456FC5A36058', 0)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (25944.00, '', 2695.00, '1CC1D982-3EAA-44C7-99F6-031AC68DB6A8', NULL, 0.00, 25941.00, 4717.00, 'SQUERY_LINK_SQUERY', '15662658-9C36-4490-A7A3-34CC2A534FCA', 'SYS_T8_REPORT', 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 (496.00, 139.00, NULL, NULL, 'STR2', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (496.00, 152.00, NULL, NULL, 'VARCHAR(254)', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (496.00, 155.00, NULL, NULL, '4', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (496.00, 158.00, NULL, NULL, 'SUBSTRING(REASON, 71, 254)', 'F5BB0E87-F6A0-4C4C-9F6F-B49B1B17611F', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1493.00, 139.00, NULL, NULL, 'STR1', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1493.00, 147.00, NULL, NULL, '', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1493.00, 152.00, NULL, NULL, 'VARCHAR(70)', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1493.00, 155.00, NULL, NULL, '4', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1493.00, 158.00, NULL, NULL, 'LEFT(LTRIM(RTRIM(REASON)), 70)', '11150D66-5722-4BD0-A525-EB0366F67E58', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2721.00, 139.00, NULL, NULL, 'DOC_NUM', '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2721.00, 155.00, NULL, NULL, '3', '931E0E21-0B3E-4CB8-8DBA-F15F44F23652', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2728.00, 139.00, NULL, NULL, 'S_35760', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2728.00, 155.00, NULL, NULL, '1', '9CA46765-7113-4068-8D54-35015F1AA6CB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2732.00, 139.00, NULL, NULL, 'DATE_DIS', '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2732.00, 155.00, NULL, NULL, '1', '5BEF2D03-CD8A-41B4-9F71-FE0F24EE3E0E', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2736.00, 139.00, NULL, NULL, 'POST', '5549F590-E1D6-46F2-BC9C-892235C1D6B8', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2736.00, 155.00, NULL, NULL, '1', '5549F590-E1D6-46F2-BC9C-892235C1D6B8', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2740.00, 139.00, NULL, NULL, 'SUBDIV', '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2740.00, 155.00, NULL, NULL, '1', '43BABD0D-AAE0-4286-BB52-A39DCB2FC958', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2745.00, 139.00, NULL, NULL, 'FIO', '8FAA1305-7322-409F-93C4-FF7C015ED3AF', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2745.00, 155.00, NULL, NULL, '1', '8FAA1305-7322-409F-93C4-FF7C015ED3AF', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2749.00, 139.00, NULL, NULL, 'TN', 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2749.00, 155.00, NULL, NULL, '1', 'FD9361C7-8DAF-40DA-9320-E67DFD48BFF0', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2753.00, 139.00, NULL, NULL, 'REASON', '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2753.00, 155.00, NULL, NULL, '1', '44BEF59C-B2FA-4374-9C2F-6082A52BFCA4', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2757.00, 139.00, NULL, NULL, 'PROF_NUM', 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2757.00, 155.00, NULL, NULL, '1', 'EFDB8865-2A4F-4E79-A7E9-5AECE386877F', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2761.00, 139.00, NULL, NULL, 'PROF_DATE', '537B8C7D-E25D-4D01-8D92-A654AF1974D3', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2761.00, 155.00, NULL, NULL, '1', '537B8C7D-E25D-4D01-8D92-A654AF1974D3', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2856.00, 1.00, NULL, NULL, '1', 'ORDER_DIS_FACE1_MAIN_PARAM', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2856.00, 163.00, NULL, NULL, '@cText_3', 'ORDER_DIS_FACE1_MAIN_PARAM', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2856.00, 166.00, NULL, NULL, '1', 'ORDER_DIS_FACE1_MAIN_PARAM', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2856.00, 217.00, NULL, NULL, '1', 'ORDER_DIS_FACE1_MAIN_PARAM', 'SQUERY_NASTR_NON_VISIBLE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2864.00, 139.00, NULL, NULL, 'STR3', '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2864.00, 155.00, NULL, NULL, '1', '2F0B1F96-6C3F-4B88-B37C-F3C266F23733', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2868.00, 139.00, NULL, NULL, 'KON_DATE', 'A8563833-D7E3-4919-8E89-0A1BBB81815A', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2868.00, 155.00, NULL, NULL, '1', 'A8563833-D7E3-4919-8E89-0A1BBB81815A', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2872.00, 139.00, NULL, NULL, 'KON_NUM', 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2872.00, 155.00, NULL, NULL, '1', 'B4C9E4DB-3975-4796-BA0C-F37C8176D543', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3250.00, 139.00, NULL, NULL, 'S_35744', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3250.00, 155.00, NULL, NULL, '1', '75E1D6E4-3290-4C4A-93C2-DBCD53803C35', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3254.00, 139.00, NULL, NULL, 'DOC_DATE', '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3254.00, 155.00, NULL, NULL, '3', '742D89A0-4499-4D18-8CC7-3FAEF2FC8CB7', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 137.00, NULL, NULL, '', 'SYS_T8_REPORT', 'SQUERY_CHANGED')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 159.00, NULL, NULL, 'KIRREPMAKER.XLS', 'SYS_T8_REPORT', 'SQUERY_GENERATOR')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 173.00, NULL, NULL, '', 'SYS_T8_REPORT', 'SQUERY_PATH')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 174.00, NULL, NULL, 'IIF(@cText_3 = "1","FORM-T8.XLT",IIF(@cText_3 = "2","FORM-T8A.XLT",""))', 'SYS_T8_REPORT', 'SQUERY_REPORT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 175.00, NULL, NULL, '(1 > 0)

EXEC KIR_GET_OTV_FACES', 'SYS_T8_REPORT', 'SQUERY_RES_WHERE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 1.00, 'CREATE PROCEDURE #P_SQUERY
		@cText_3 VARCHAR(4000) /*Одиночный/групповой*/,
		@nCheck_2 INT /*Показывать "Решение проф. орг"*/,
		@nCheck_4 INT /*Показывать дату приема на работу*/,
		@nNumber001 INT /*Ссылка на документ (основная)*/,
		@varKScTableInto varchar(20) = ''''
AS
BEGIN

	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
', 'SYS_T8_REPORT', 'SQUERY_SQL')

		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (8495.00, 176.00, NULL, 6.00, '
	UPDATE #T_RES
	SET	work_nastr = (select convert(int,value) from s_options where object = (select link from s_objects where code = ''kadry_opt9'')) /*Дата приема (настройка)*/ FROM #T_RES T  WHERE SQUERY=4717
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (8495.00, 176.00, NULL, 7.00, '
	UPDATE #T_RES
	SET	work_date = (select date_begin from item_move where new_face = 1 and active = 1 and empl_link = (select link from empl where rtrim(ltrim(tab)) = rtrim(ltrim(TN)) and dep_link = S_19351)) /*Дата приема*/ FROM #T_RES T  WHERE SQUERY=4717
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 2.00, '
	CREATE TABLE #T_RES (DATE_DIS DATETIME /*Дата увольнения*/,
		DOC_DATE DATETIME /*Дата приказа*/,
		DOC_NUM VARCHAR(30) /*Номер приказа*/,
		FIO VARCHAR(254) /*ФИО (по документу)*/,
		KON_DATE DATETIME /*Трудовой договор - дата*/,
		KON_NUM VARCHAR(20) /*Трудовой договор - номер*/,
		LONGNAME VARCHAR(254) /*Наименование*/,
		OKPO VARCHAR(20) /*ОКПО*/,
		POST VARCHAR(254) /*Должность (по документу)*/,
		PROF_DATE DATETIME /*Решение профсоюзного органа - дата*/,
		PROF_NUM VARCHAR(15) /*Решение профсоюзного органа  - номер*/,
		REASON VARCHAR(254) /*Причина увольнения*/,
		S_19351 INT /*Организация*/,
		S_35744 INT /*Приказ*/,
		S_35760 INT /*Приказ об увольнении*/,
		STR1 VARCHAR(70) /*Причина1*/,
		STR2 VARCHAR(254) /*Причина2*/,
		STR3 VARCHAR(254) /*Основание увольнения*/,
		SUBDIV VARCHAR(254) /*Подразделение (по документу)*/,
		TN VARCHAR(15) /*Табельный номер (по документу)*/,
		VAC_DAY NUMERIC(6,2) /*Расчет отпускных на*/,
		work_date datetime /*Дата приема*/,
		work_nastr int /*Дата приема (настройка)*/, SQUERY int)
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 3.00, '
	INSERT #T_RES (FIO, TN, REASON, PROF_NUM, PROF_DATE, STR3, KON_DATE, KON_NUM, VAC_DAY, DATE_DIS, POST, SUBDIV, S_35760, S_35744, S_19351, SQUERY) /*Организация*/
	SELECT ITDF.FIO, ITDF.TAB_NUM, (SELECT NAME FROM DICTIONARY_PUV WHERE LINK = ITDF.REASON_LINK), ITDF.PROF_NUM, ITDF.PROF_DATE, ITDF.OSN, (select  kontr_date from item_move where empl_link = itdf.empl_link and new_face = 1 and active = 1), (select  kontr_num from item_move where empl_link = itdf.empl_link and new_face = 1 and active = 1), ITDF.VAC_KOMPENS_DAY, ITDF.DIS_DATE, ITDF.POST, ITDF.SUBDIV, ITDF.LINK, ORD3.LINK, DEP.LINK, 4717
	FROM ORDERS ORD3, DIS_FACE ITDF, DICTIONARY_DEPARTMENT DEP
	WHERE (ORD3.LINK=@nNumber001)
		AND ORD3.DEP_LINK = DEP.LINK
		AND ORD3.LINK = ITDF.ORDER_LINK
		AND ORD3.TYPE IN (3, 103)
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 4.00, '
	UPDATE #T_RES
	SET	STR2 = SUBSTRING(REASON, 71, 254) /*Причина2*/ FROM #T_RES T  WHERE SQUERY=4717
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 5.00, '
	UPDATE #T_RES
	SET	STR1 = LEFT(LTRIM(RTRIM(REASON)), 70) /*Причина1*/ FROM #T_RES T  WHERE SQUERY=4717
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 6.00, '
	UPDATE #T_RES
	SET	DOC_NUM = (SELECT NUMBER FROM ORDERS WHERE LINK = S_35744) /*Номер приказа*/ FROM #T_RES T 
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 7.00, '
	UPDATE #T_RES
	SET	DOC_DATE = (SELECT [DATE] FROM ORDERS WHERE LINK = S_35744) /*Дата приказа*/ FROM #T_RES T 
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 8.00, '
	UPDATE #T_RES
	SET	LONGNAME = (SELECT FULL_NAME FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19351) /*Наименование*/ FROM #T_RES T 
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 9.00, '
	UPDATE #T_RES
	SET	OKPO = (SELECT OKPO FROM DICTIONARY_DEPARTMENT WHERE LINK=S_19351) /*ОКПО*/ FROM #T_RES T 
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 10.00, '
	SELECT STR2 AS STR2 /*Причина2*/,
		STR1 AS STR1 /*Причина1*/,
		DOC_NUM AS DOC_NUM /*Номер приказа*/,
		S_35760 AS S_35760 /*Приказ об увольнении*/,
		DATE_DIS AS DATE_DIS /*Дата увольнения*/,
		POST AS POST /*Должность (по документу)*/,
		SUBDIV AS SUBDIV /*Подразделение (по документу)*/,
		FIO AS FIO /*ФИО (по документу)*/,
		TN AS TN /*Табельный номер (по документу)*/,
		REASON AS REASON /*Причина увольнения*/,
		PROF_NUM AS PROF_NUM /*Решение профсоюзного органа  - номер*/,
		PROF_DATE AS PROF_DATE /*Решение профсоюзного органа - дата*/,
		STR3 AS STR3 /*Основание увольнения*/,
		KON_DATE AS KON_DATE /*Трудовой договор - дата*/,
		KON_NUM AS KON_NUM /*Трудовой договор - номер*/,
		S_35744 AS S_35744 /*Приказ*/,
		DOC_DATE AS DOC_DATE /*Дата приказа*/,
		S_19351 AS S_19351 /*Организация*/,
		LONGNAME AS LONGNAME /*Наименование*/,
		OKPO AS OKPO /*ОКПО*/,
		work_nastr AS work_nastr /*Дата приема (настройка)*/,
		work_date AS work_date /*Дата приема*/,
		VAC_DAY AS VAC_DAY /*Расчет отпускных на*/
	INTO #T_RES2
	FROM #T_RES T
	GROUP BY STR2, STR1, DOC_NUM, S_35760, DATE_DIS, POST, SUBDIV, FIO, TN, REASON, PROF_NUM, PROF_DATE, STR3, KON_DATE, KON_NUM, S_35744, DOC_DATE, S_19351, LONGNAME, OKPO, work_nastr, work_date, VAC_DAY


', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 11.00, '	
SELECT * FROM #T_RES2 
	WHERE (1 > 0)

EXEC KIR_GET_OTV_FACES

', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 12.00, '
	
	DROP TABLE #T_RES
', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 176.00, NULL, 13.00, '
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED

END', 'SYS_T8_REPORT', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (4717.00, 347.00, NULL, NULL, 'KIRREPT8.BAS', 'SYS_T8_REPORT', 'QUERY_ADD_MODULE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 1.00, NULL, NULL, '0', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 1.00, NULL, NULL, '0', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 166.00, NULL, NULL, '1', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 166.00, NULL, NULL, '1', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 168.00, NULL, NULL, '', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 217.00, NULL, NULL, '1', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_NON_VISIBLE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7397.00, 217.00, NULL, NULL, '1', 'ORDER_DIS_FACE_MAIN_PARAM', 'SQUERY_NASTR_NON_VISIBLE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7482.00, 139.00, NULL, NULL, 'S_19351', '2452562_0SD0SJB1F', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7482.00, 155.00, NULL, NULL, '1', '2452562_0SD0SJB1F', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7486.00, 139.00, NULL, NULL, 'LONGNAME', '2452562_0SD0SJBBQ', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7486.00, 155.00, NULL, NULL, '3', '2452562_0SD0SJBBQ', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7490.00, 139.00, NULL, NULL, 'OKPO', '2452562_0SD0SJCV4', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (7490.00, 155.00, NULL, NULL, '3', '2452562_0SD0SJCV4', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10899.00, 1.00, NULL, NULL, '1', '2452909_1220P23L2', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10899.00, 163.00, NULL, NULL, '@nCheck_2', '2452909_1220P23L2', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10899.00, 166.00, NULL, NULL, '1', '2452909_1220P23L2', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10899.00, 168.00, NULL, NULL, 'Вкл.', '2452909_1220P23L2', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (22691.00, 163.00, NULL, NULL, '@nCheck_4', 'F7CDE295-51B1-496A-92F7-6B480DFB491B', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (22691.00, 166.00, NULL, NULL, '1', 'F7CDE295-51B1-496A-92F7-6B480DFB491B', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (22691.00, 168.00, NULL, NULL, 'Вкл.', 'F7CDE295-51B1-496A-92F7-6B480DFB491B', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (25941.00, 139.00, NULL, NULL, 'VAC_DAY', '15662658-9C36-4490-A7A3-34CC2A534FCA', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (25941.00, 155.00, NULL, NULL, '1', '15662658-9C36-4490-A7A3-34CC2A534FCA', 'SQUERY_FIELD_TYPE')

GO

		CREATE TABLE #T_NAVIGATOR (CODE VARCHAR(50), NAME VARCHAR(254), ORDERS INT, SYS INT, CODE_SELF VARCHAR(50), CODE_OBJ VARCHAR(30), SQ_CODE VARCHAR(60), IMAGE_KEY VARCHAR(30) )
		exec KIR_UPGRADE_OV 0 
GO

		DROP TABLE #T_OV
GO

		DROP TABLE #T_OVV
GO

		DROP TABLE #T_NAVIGATOR
GO


GO
DELETE  dbo.report_kbk
WHERE code_form = 'HEADER' AND link_self = 0
      AND code IN ( 'mdks_125', 'SEND', 'SEND_XML', 'LABEL', 'R_SPR_Proizvod', 'R_SPR_naim_hoz', 'R_SPR_naim_KFH', 'R_SPR_naim_hoz_naselenia')
      
GO

GO
w_sperm_write @CodeObject = 'RO_VR_USER_2011_WEB', @UserName = 'Свод-КС', @Permitted = 63, @Restricted = 0
GO
w_sperm_write @CodeObject = 'RO_VR_USER_2011_WEB', @UserName = 'Свод-КС - получатель', @Permitted = 63, @Restricted = 0
GO

GO
/****** Объект: Справочник региональных видом расходов (общий для всех организаций)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'RO_VR_USER_2011_WEB')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'RO_VR_USER_2011_WEB')
	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 = 'RO_VR_USER_2011_WEB')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'RO_VR_USER_2011_WEB')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'RO_VR_USER_2011_WEB'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RO_VR_USER_2011_WEB')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_VR_USER_2011_WEB', 'Справочник региональных видом расходов (общий для всех организаций)', 121, (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_VR_USER_2011_WEB', NAME = 'Справочник региональных видом расходов (общий для всех организаций)', ORDERS = '121', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='REPORT_DICTIONARY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_VR_USER_2011_WEB'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_CSR_USER_2011_WEB_M_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_CSR_USER_2011_WEB_M_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_CSR_USER_2011_WEB_M_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_CSR_USER_2011_WEB_M_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_CSR_USER_2011_WEB_CODE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_CSR_USER_2011_WEB_CODE_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_CSR_USER_2011_WEB_CODE_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_CSR_USER_2011_WEB_CODE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_CSR_USER_2011_WEB_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_CSR_USER_2011_WEB_NAME_1', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_CSR_USER_2011_WEB_NAME_1', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_CSR_USER_2011_WEB_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RO_CSR_USER_2011_WEB_LONG_NA_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'Полное наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RO_CSR_USER_2011_WEB_LONG_NA_1', NAME = 'Полное наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RO_VR_USER_2011_WEB'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RO_CSR_USER_2011_WEB_LONG_NA_1'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'TITLE', 'Справочник региональных видов расходов'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_VR_USER_2011_2'')'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'SERVER_TABLE_NAME', 'R_SPR_VR_USER_2011_2'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'EDIT_OBJECT_METHOD_SQL', 'RO_WEB_VR_USER_2011_EDIT  @cObject = ''RO_VR_USER_2011_WEB'''
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'SELECT_RECORDS_METHOD_SQL', 'RO_WEB_VR_USER_2011'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'SAVE_OBJECT_METHOD_SQL', 'RO_WEB_VR_USER_2011_SAVE'
GO
EXEC X_SET_PROP 'RO_VR_USER_2011_WEB', 'WEB_TOOLBAR', 'SPISOK_TOOLBAR_ONLY_EDIT'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_M_1', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_M_1', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_M_1', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 250px; POSITION: absolute; TOP: 16px""
Width="500px" 
ReadOnly="True"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_CODE_1', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 250px; POSITION: absolute; TOP: 46px""
Width="500px"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 46px"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_NAME_1', 'WIDTH', '300'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'TITLE', 'Полное наименование'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'CONTROLSOURCE', 'm.cAlias + ".Long_Name"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'ATTRIBUTES', 'style="Z-INDEX: 102; LEFT: 250px; POSITION: absolute; TOP: 76px""
Width="500px"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 76px"'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'FIELD_DATA', 'Long_Name'
GO
EXEC X_SET_PROP 'RO_CSR_USER_2011_WEB_LONG_NA_1', 'WIDTH', '300'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Региональный справочник видов расходов"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'web_spr')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'RO_VR_USER_2011_WEB')

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 = 'web_spr'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'web_spr_vr'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'web_spr_vr', 'Региональный справочник видов расходов', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


GO
update dbo.report_forms set end_date = '20081230' where code = '0503122' and start_date = '20070822'
update dbo.report_forms set end_date = '20090831' where code = '0606010' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503127' and start_date = '19810101'
update dbo.report_forms set end_date = '20081230' where code = '0503v27' and start_date = '19810101'
update dbo.report_forms set end_date = '20100101' where code = 'AV_ESN' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503123' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503126' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503129' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '050312s' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '050313s' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503140' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503150' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '050316_' and start_date = '20070822'
update dbo.report_forms set end_date = '20081231' where code = '0503160' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503s74' and start_date = '20070822'
update dbo.report_forms set end_date = '20081231' where code = '0617004' and start_date = '20070822'
update dbo.report_forms set end_date = '20100101' where code = 'AV_PFR' and start_date = '20070822'
update dbo.report_forms set end_date = '20100101' where code = 'ND_ESN' and start_date = '20070822'
update dbo.report_forms set end_date = '20100101' where code = 'ND_PFR' and start_date = '20070822'
update dbo.report_forms set end_date = '20091230' where code = '015' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503127' and start_date = '19820101'
update dbo.report_forms set end_date = '20081230' where code = '0503v27' and start_date = '19820101'
update dbo.report_forms set end_date = '20081230' where code = '0503130' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503120' and start_date = '20070820'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070817'
update dbo.report_forms set end_date = '20081230' where code = '429old' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0505130' and start_date = '20070819'
update dbo.report_forms set end_date = '20081230' where code = '0503121' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '050317_' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '428G' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503169' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503125' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '430Z' and start_date = '20070822'
update dbo.report_forms set end_date = '20081231' where code = '0503387' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503120' and start_date = '20070821'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070818'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070819'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070820'
update dbo.report_forms set end_date = '20081230' where code = '0505130' and start_date = '20070820'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070821'
update dbo.report_forms set end_date = '20081230' where code = '0505130' and start_date = '20070821'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0505130' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '428' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '428V' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '429G' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '429M' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503128' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503120' and start_date = '20070822'
update dbo.report_forms set end_date = '20101231' where code = '0503074' and start_date = '20071201'
update dbo.report_forms set end_date = '20081230' where code = '0503127' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503110' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503v27' and start_date = '20070822'
update dbo.report_forms set end_date = '20090327' where code = '4fss' and start_date = '20070821'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503114' and start_date = '20070918'
update dbo.report_forms set end_date = '20081230' where code = '430M' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '430' and start_date = '20070822'
update dbo.report_forms set end_date = '20081230' where code = '0503128' and start_date = '20070926'
update dbo.report_forms set end_date = '20081230' where code = '05030mo' and start_date = '20071201'
update dbo.report_forms set end_date = '20081230' where code = '0503v28' and start_date = '20071009'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503120' and start_date = '20070823'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503125' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503121' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503117' and start_date = '20070919'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503124' and start_date = '20070920'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503130' and start_date = '20070823'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503134' and start_date = '20070921'
update dbo.report_forms set end_date = '20081230' where code = '0503150' and start_date = '20070823'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503150' and start_date = '20070824'
update dbo.report_forms set end_date = '20081230' where code = '(137н)0503125' and start_date = '20071003'
update dbo.report_forms set end_date = '20081230' where code = '0503317' and start_date = '20070823'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503317G' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503320' and start_date = '20070824'
update dbo.report_forms set end_date = '20081230' where code = '0503v27' and start_date = '20070925'
update dbo.report_forms set end_date = '20081230' where code = '0503127' and start_date = '20070917'
update dbo.report_forms set end_date = '20081230' where code = '(72Н)0503323' and start_date = '20071003'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503123' and start_date = '20071002'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503314' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503321' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503160' and start_date = '20071128'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503161' and start_date = '20071129'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503162' and start_date = '20071129'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503163' and start_date = '20071130'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503169_БД' and start_date = '20071130'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503166' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503167' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503171' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503176' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503177' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503178_Б' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503140' and start_date = '20071205'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503364' and start_date = '20070921'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503369_БК' and start_date = '20071201'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503371' and start_date = '20071204'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503372' and start_date = '20071204'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503369_ВБК' and start_date = '20071202'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503369_БД' and start_date = '20081231'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503369_ВБД' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503373V' and start_date = '20071205'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503376' and start_date = '20071204'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503379' and start_date = '20070922'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503382' and start_date = '20070922'
update dbo.report_forms set end_date = '20081230' where code = '625' and start_date = '20071213'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503178_ВБ' and start_date = '20071205'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503178_СВ' and start_date = '20071205'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503120V' and start_date = '20070823'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0521441' and start_date = '20071002'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503173V' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503373' and start_date = '20071204'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503173' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503172_OLD' and start_date = '20071203'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503182M' and start_date = '20070921'
update dbo.report_forms set end_date = '20081230' where code = '625' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)425' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503164' and start_date = '20070920'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503169_ВБД' and start_date = '20071201'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503169_ВБК' and start_date = '20071202'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503314G' and start_date = '20071001'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503169_БК' and start_date = '20071201'
update dbo.report_forms set end_date = '20081230' where code = '(72н)410' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0521443' and start_date = '20080116'
update dbo.report_forms set end_date = '20081230' where code = '(72н)410f' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)410m' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)410s' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503168_МАТ' and start_date = '20071005'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503168_НМА' and start_date = '20071005'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503168_НПА' and start_date = '20071003'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503168_ОСН' and start_date = '20071004'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503368_МАТ' and start_date = '20071007'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503368_НМА' and start_date = '20071006'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503368_НПА' and start_date = '20071006'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503368_ОСН' and start_date = '20071005'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503172' and start_date = '20071203'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503364f' and start_date = '20070921'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503379f' and start_date = '20070922'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0521429M' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503125М' and start_date = '20080203'
update dbo.report_forms set end_date = '20081231' where code = '(72н)425M' and start_date = '20071001'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503127M' and start_date = '20071020'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503179G' and start_date = '20081001'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503314M' and start_date = '20071001'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503317M' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503117M' and start_date = '20070919'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503127' and start_date = '20071020'
update dbo.report_forms set end_date = '20081231' where code = '0503387' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503373f' and start_date = '20071204'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503137M' and start_date = '20070918'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0521429' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503137' and start_date = '20070918'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503164M' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503125МБР' and start_date = '20080203'
update dbo.report_forms set end_date = '20081230' where code = 'MONITOR' and start_date = '20070823'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503364M' and start_date = '20080301'
update dbo.report_forms set end_date = '20081230' where code = 'MONITOR' and start_date = '20080402'
update dbo.report_forms set end_date = '20111231' where code = '585' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503364Mf' and start_date = '20080101'
update dbo.report_forms set end_date = '20111230' where code = 'AV_ASS' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503114M' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '0505130' and start_date = '20080101'
update dbo.report_forms set end_date = '20081230' where code = '0505140' and start_date = '20080101'
update dbo.report_forms set end_date = '20101230' where code = '0503074G' and start_date = '20080101'
update dbo.report_forms set end_date = '20101231' where code = '0503074G_MO' and start_date = '20071201'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503364Mf' and start_date = '20080301'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503182' and start_date = '20070921'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503382M' and start_date = '20080718'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503230' and start_date = '20080828'
update dbo.report_forms set end_date = '20111231' where code = 'AV_F1152028' and start_date = '20080101'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503151' and start_date = '20080909'
update dbo.report_forms set end_date = '20081231' where code = '(72н)0503152' and start_date = '20080909'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503110' and start_date = '20081013'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)550' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)555' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)547' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)549' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)551' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)552' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)553' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)554' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)557' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)558' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)559' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)560' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)561' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)562' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)564' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)565' and start_date = '20081020'
update dbo.report_forms set end_date = '20081231' where code = '(131-ФЗ)548' and start_date = '20081020'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503124' and start_date = '20081023'
update dbo.report_forms set end_date = '20081230' where code = '(72н)0503172' and start_date = '20081027'
update dbo.report_forms set end_date = '20091230' where code = '0503114G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503127G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503117G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503120G' and start_date = '20090101'
update dbo.report_forms set end_date = '20081231' where code = '0503121G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503123G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503124G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503130G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503134G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503137G' and start_date = '20081231'
update dbo.report_forms set end_date = '20081231' where code = '0503140G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503161G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503162G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503163G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503166G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503167G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503171G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503172G' and start_date = '20081231'
update dbo.report_forms set end_date = '20071201' where code = '0503173G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503176G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503177G' and start_date = '20081231'
update dbo.report_forms set end_date = '20081231' where code = 'OPKB_2008' and start_date = '20080101'
update dbo.report_forms set end_date = '20101231' where code = '0503178G_Б' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503178G_ВБ' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503178G_СВ' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503179G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503182G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503164G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503168G_МАТ' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503168G_НМА' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503168G_НПА' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503168G_ОСН' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503169G_БД' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503169G_БК' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503169G_ВБД' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '0503169G_ВБК' and start_date = '20081231'
update dbo.report_forms set end_date = '20081231' where code = '0503230G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503317G' and start_date = '20081231'
update dbo.report_forms set end_date = '20081231' where code = '0503320G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503321G' and start_date = '20090101'
update dbo.report_forms set end_date = '20091230' where code = '0503323G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503364G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503364GF' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503368G_МАТ' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503368G_НМА' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503368G_НПА' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503368G_ОСН' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503369G_БД' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503369G_БК' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503369G_ВБД' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503369G_ВБК' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503371G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503372G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503373G' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503376G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503379G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503382G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503379GF' and start_date = '20081231'
update dbo.report_forms set end_date = '20071231' where code = '0503382GF' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503373GV' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0521441G' and start_date = '20081231'
update dbo.report_forms set end_date = '20070101' where code = '0521443G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0521445G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503110G' and start_date = '20081231'
update dbo.report_forms set end_date = '20081230' where code = '0503151G' and start_date = '20081231'
update dbo.report_forms set end_date = '20081230' where code = '0503152G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503314G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '410G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '410Gf' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '410Gs' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '410Gm' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503160G_т3' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503317G_C' and start_date = '20081231'
update dbo.report_forms set end_date = '20091130' where code = '0503125G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503173G_Б' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503173G_ВБ' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503173G_СВ' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = 'OPKB' and start_date = '20090101'
update dbo.report_forms set end_date = '20091130' where code = '425G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = 'OPKB_MINREGION' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503074mo' and start_date = '20090101'
update dbo.report_forms set end_date = '20091229' where code = '625' and start_date = '20081231'
update dbo.report_forms set end_date = '20091130' where code = '0503125M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091130' where code = '425M' and start_date = '20090101'
update dbo.report_forms set end_date = '20090331' where code = '0503387M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503117M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503124M' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = '0503127M' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = '0503317M' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503152M' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503151M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503314M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503114M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503137M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503164M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503364M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503364MF' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503140M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503182M' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503382M' and start_date = '20090101'
update dbo.report_forms set end_date = '20090629' where code = '0503324M' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503178M_Б' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503178M_СВ' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503178M_ВБ' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503317M_ФК' and start_date = '20090101'
update dbo.report_forms set end_date = '20081231' where code = '(19н)621' and start_date = '20071201'
update dbo.report_forms set end_date = '20091231' where code = '571' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '575' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '572' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '573' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '576' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '574' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '577' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '578' and start_date = '20090101'
update dbo.report_forms set end_date = '20090630' where code = '0503387M' and start_date = '20090401'
update dbo.report_forms set end_date = '20091231' where code = '0505130' and start_date = '20081231'
update dbo.report_forms set end_date = '20101231' where code = '0503134M' and start_date = '20090101'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)561' and start_date = '20090602'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)551' and start_date = '20090602'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)553' and start_date = '20090602'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)552' and start_date = '20090602'
update dbo.report_forms set end_date = '20100930' where code = '(131-ФЗ)557' and start_date = '20100401'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)558' and start_date = '20100401'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)559' and start_date = '20090602'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)549' and start_date = '20090602'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)562' and start_date = '20090602'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)547' and start_date = '20090602'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)560' and start_date = '20090602'
update dbo.report_forms set end_date = '20091231' where code = '0503324M' and start_date = '20090629'
update dbo.report_forms set end_date = '20091231' where code = '4fss' and start_date = '20090330'
update dbo.report_forms set end_date = '20090930' where code = '0503387M' and start_date = '20090701'
update dbo.report_forms set end_date = '20091031' where code = '63' and start_date = '20090629'
update dbo.report_forms set end_date = '20090731' where code = '56Н' and start_date = '20070822'
update dbo.report_forms set end_date = '20091230' where code = '0503121G' and start_date = '20090101'
update dbo.report_forms set end_date = '20081231' where code = '0503321G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091230' where code = '0503230G' and start_date = '20090101'
update dbo.report_forms set end_date = '20091230' where code = '0503320G' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503230Gf' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503230Gm' and start_date = '20090101'
update dbo.report_forms set end_date = '20091231' where code = '0503230Gs' and start_date = '20090102'
update dbo.report_forms set end_date = '20081231' where code = '0503120G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = '0503184M' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = '0503387M' and start_date = '20091001'
update dbo.report_forms set end_date = '20091231' where code = '0503387M_vn' and start_date = '20091001'
update dbo.report_forms set end_date = '20101230' where code = '0503168G_БД' and start_date = '20091231'
update dbo.report_forms set end_date = '20100227' where code = '2-БФ(Р)' and start_date = '20090101'
update dbo.report_forms set end_date = '20101230' where code = '0503168G_ВБД' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503161G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503130G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503121G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503120G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503123G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503140G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503164G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503182G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503230G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503128G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503117G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503177G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503125M' and start_date = '20091201'
update dbo.report_forms set end_date = '20101230' where code = '0503125G' and start_date = '20091201'
update dbo.report_forms set end_date = '20091231' where code = '425M' and start_date = '20091201'
update dbo.report_forms set end_date = '20101230' where code = '0503138G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503110G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503124G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503127G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503134G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503137G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503173G_Б' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503373G' and start_date = '20091231'
update dbo.report_forms set end_date = '20111230' where code = '0503373GV' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503173G_ВБ' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503173G_СВ' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '0503320G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503114G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503317G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091230' where code = '0503164G_1' and start_date = '20081231'
update dbo.report_forms set end_date = '20101230' where code = '425G' and start_date = '20091201'
update dbo.report_forms set end_date = '20101230' where code = '0503364G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503321G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503323G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503368G_БД' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503368G_ВБД' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503314G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503324G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503377G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503377Gf' and start_date = '20091231'
update dbo.report_forms set end_date = '20100331' where code = 'OPKB_MINREGION' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503382G' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '410Gs' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503361G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503361Gf' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503364GF' and start_date = '20091231'
update dbo.report_forms set end_date = '20091230' where code = '0503162G' and start_date = '20081231'
update dbo.report_forms set end_date = '20091231' where code = '410Gf' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '410Gm' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '410Gt' and start_date = '20091231'
update dbo.report_forms set end_date = '20091231' where code = '410G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503151G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503317G_ФК' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503387G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '625' and start_date = '20091231'
update dbo.report_forms set end_date = '20100429' where code = '0503387M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503371G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101230' where code = '0503372G' and start_date = '20091231'
update dbo.report_forms set end_date = '20101231' where code = '0503114M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503117M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503124M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503127M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503137M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503184M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503314M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503317M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503317M_ФК' and start_date = '20100101'
update dbo.report_forms set end_date = '20101031' where code = '0503324M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503125M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '425M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '484M' and start_date = '20100101'
update dbo.report_forms set end_date = '20100330' where code = '0503387M_vn' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '015' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = 'РСВ-1' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503177M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503377M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503377Mf' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503164M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503364M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503364MF' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503182M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503382M' and start_date = '20100101'
update dbo.report_forms set end_date = '20100430' where code = '0503387M' and start_date = '20100430'
update dbo.report_forms set end_date = '20100430' where code = '0503387M_vn' and start_date = '20100331'
update dbo.report_forms set end_date = '20101230' where code = '0503230G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '577' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503128M' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '574' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503230Gf' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503230Gm' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503230Gs' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '572' and start_date = '20100101'
update dbo.report_forms set end_date = '20101030' where code = '0503324M_RA' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '573' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '571' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '4fss' and start_date = '20100101'
update dbo.report_forms set end_date = '20101031' where code = '0503387M' and start_date = '20100501'
update dbo.report_forms set end_date = '20101130' where code = '0503387M_vn' and start_date = '20100501'
update dbo.report_forms set end_date = '20101231' where code = '0617004' and start_date = '20090101'
update dbo.report_forms set end_date = '20101231' where code = '0503138M' and start_date = '20100101'
update dbo.report_forms set end_date = '20091231' where code = '0607006' and start_date = '20090820'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)553' and start_date = '20100401'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)558' and start_date = '20090602'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)562' and start_date = '20100401'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)557' and start_date = '20090602'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)550' and start_date = '20100401'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)549' and start_date = '20100401'
update dbo.report_forms set end_date = '20100930' where code = '(131-ФЗ)551' and start_date = '20100401'
update dbo.report_forms set end_date = '20100331' where code = '(131-ФЗ)550' and start_date = '20090602'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)560' and start_date = '20100101'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)559' and start_date = '20100401'
update dbo.report_forms set end_date = '20101230' where code = '0503120G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503320G' and start_date = '20100101'
update dbo.report_forms set end_date = '20111230' where code = '0503127G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101230' where code = '0503110G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '410G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '410Gf' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '410Gm' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '410Gs' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '410Gt' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503324M' and start_date = '20101101'
update dbo.report_forms set end_date = '20101231' where code = 'FIN_HELP' and start_date = '20101101'
update dbo.report_forms set end_date = '20111230' where code = '0602002' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503164G' and start_date = '20100101'
update dbo.report_forms set end_date = '20101231' where code = '0503168G_БД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503168G_ВБД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503368G_БД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503368G_ВБД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503130G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503110G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503114G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503117G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503124G' and start_date = '20101231'
update dbo.report_forms set end_date = '20111230' where code = '0503125G' and start_date = '20101231'
update dbo.report_forms set end_date = '20111230' where code = '0503128G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503134G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503120G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503137G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503138G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503162G' and start_date = '20101230'
update dbo.report_forms set end_date = '20101231' where code = '0503163G' and start_date = '20101230'
update dbo.report_forms set end_date = '20110201' where code = '0503171G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503172G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503177G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503387M' and start_date = '20101201'
update dbo.report_forms set end_date = '20101231' where code = '0503182G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503314G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503387M_vn' and start_date = '20101201'
update dbo.report_forms set end_date = '20101231' where code = '0503317G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503317G_ФК' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503324G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503364G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503364GF' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503371G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503372G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503320G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503377G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503377Gf' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503382G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '425G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503230G' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503169G_БД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503169G_БК' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503169G_ВБД' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503169G_ВБК' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503387G' and start_date = '20101231'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)551' and start_date = '20101001'
update dbo.report_forms set end_date = '20120331' where code = '(131-ФЗ)557' and start_date = '20101001'
update dbo.report_forms set end_date = '20111231' where code = '426' and start_date = '20110101'
update dbo.report_forms set end_date = '20110430' where code = '0503387M' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '625' and start_date = '20101231'
update dbo.report_forms set end_date = '20111230' where code = '624' and start_date = '20101231'
update dbo.report_forms set end_date = '20101231' where code = '0503230G_1' and start_date = '20101231'
update dbo.report_forms set end_date = '20111231' where code = '4fss' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = 'РСВ-1' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503737' and start_date = '20110101'
update dbo.report_forms set end_date = '20110601' where code = '0503725' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = '571' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = '576' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = '577' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = '574' and start_date = '20110101'
update dbo.report_forms set end_date = '20111231' where code = '573' and start_date = '20110101'
update dbo.report_forms set end_date = '20121231' where code = '0503725M' and start_date = '20110101'
update dbo.report_forms set end_date = '20111031' where code = '0503387M' and start_date = '20110501'
update dbo.report_forms set end_date = '20110102' where code = 'obr_m_sk_int' and start_date = '20110101'
update dbo.report_forms set end_date = '20110102' where code = 'obr_m_vnesk' and start_date = '20110101'
update dbo.report_forms set end_date = '20110102' where code = 'obr_m_spec' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503710G' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503730G_B' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503769G_Д' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503773G' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503769G_K' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503173G_Б' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503173G_ВБ' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503173G_СВ' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503373G' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503373GV' and start_date = '20110101'
update dbo.report_forms set end_date = '20110731' where code = '999РХ' and start_date = '20110601'
update dbo.report_forms set end_date = '20111230' where code = '0503321G' and start_date = '20110101'
update dbo.report_forms set end_date = '20111230' where code = '0503323G' and start_date = '20110101'
update dbo.report_forms set end_date = '20101231' where code = '0503368G_БД_1' and start_date = '20101231'
update dbo.report_forms set end_date = '20111031' where code = '(86н)001' and start_date = '20110901'
update dbo.report_forms set end_date = '20101231' where code = 'ispoln_doh_rash' and start_date = '20101230'
update dbo.report_forms set end_date = '20111031' where code = '(86н)002' and start_date = '20110901'
update dbo.report_forms set end_date = '20111231' where code = '0503737_1' and start_date = '20110101'
update dbo.report_forms set end_date = '20120331' where code = '0503387M' and start_date = '20111101'
update dbo.report_forms set end_date = '20110831' where code = '0503324M_RS' and start_date = '20090630'
update dbo.report_forms set end_date = '20111230' where code = '0503725G' and start_date = '20110101'
update dbo.report_forms set end_date = '20120229' where code = 'KK04_PlanFHD_7_1' and start_date = '20111201'
update dbo.report_forms set end_date = '20120101' where code = '0503737_NN' and start_date = '20120101'
update dbo.report_forms set end_date = '20120430' where code = '0503387M' and start_date = '20120401'
GO

GO
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '001'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '004'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'U001'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '008'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'U002'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '010'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '011'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '015'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'U01'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '017'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '018'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '016'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '019'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '118'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '012'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '005'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '215'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '006'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '041'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '054'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '003'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '022'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '002'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '023'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '009'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '013'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '014'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '119'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '112'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '026'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '027'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '021'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '055'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '120'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '040'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '216'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '354'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '030'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '031'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '032'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '033'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '034'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '035'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '037'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '038'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '039'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '025'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '069'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '045'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '046'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '053'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '048'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '049'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '121'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '051'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '052'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'U004'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '042'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '047'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '056'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '082'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '043'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '057'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '058'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '059'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '060'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '061'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '062'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '063'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '064'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '065'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '066'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '067'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '044'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '070'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '071'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '072'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '073'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '074'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '075'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '076'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '077'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '078'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '083'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '084'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '085'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '086'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '068'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '087'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '088'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '089'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '090'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '079'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '080'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '081'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '091'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '094'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '093'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '095'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '96'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '096'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '097'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '098'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '099'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '100'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '101'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '102'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '103'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '104'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '122'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '106'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '113'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '114'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '115'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '116'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '117'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '123'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '124'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '125'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '126'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '214'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '266'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '267'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '285'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '241'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'U323'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '291'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '153'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '035u'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '248'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = 'K002'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '200'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '201'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '202'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '203'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '204'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '205'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '206'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '207'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '208'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '209'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '212'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '213'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '221'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '250'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '402'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '252'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '253'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '254'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '256'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '257'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '259'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '255'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '260'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '261'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '262'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '263'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '264'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '265'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '268'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '269'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '249'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '271'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '272'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '273'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '274'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '275'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '276'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '277'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '278'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '279'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '280'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '281'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '282'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '283'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '238'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '239'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '286'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '289'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '293'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '294'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '295'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '244'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '245'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '305'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '307'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '308'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '309'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '323'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '331'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '363'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '400'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '210'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '237'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '287'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '290'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '301'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '302'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '314'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091130' where code = '316'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '340'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '341'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '346'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '348'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '322'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '324'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '325'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '326'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '327'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '328'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '329'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '332'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '333'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '337'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '338'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '339'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '342'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '357'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '350'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '352'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '352f'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '353f'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '353m'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '353s'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '550'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '551'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '484'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '351'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '353'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '128'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '028'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '130'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '107'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '352m'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '108'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '152'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '132'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '151'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '156'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '242'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '243'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '311'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '312'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '352s'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '320'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '361'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '405'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '406'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '407'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '408'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '404'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '409'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '411'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '412'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '413'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '414'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '415'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '417'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '418'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '211'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '217'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '218'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '219'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '220'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '230'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '231'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '232'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '233'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '234'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '355'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '330'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '284'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '240'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '296'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '297'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '298'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '356'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '300'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '358'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '359'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '360'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '426'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '427'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '432'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '433'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '434'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '435'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '436'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '438'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '439'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '440'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '450'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '451'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '452'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '453'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '455'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '478'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '471'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '526'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '222'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '223'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '224'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '225'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '226'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '227'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '228'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '229'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '246'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '247'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '303'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '306'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '410'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '428'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '437'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '441'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '443'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '444'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '445'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '458'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '459'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '462'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '463'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '465'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '466'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '467'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '468'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '469'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '480'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '447'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '216f'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111031' where code = '868'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111031' where code = '875'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '877'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110101' where code = '890'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = 'vet_882_2011'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = 'vet_883_2011'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '900'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '851'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '852'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '893'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '916'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '917'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = 'vet_885_2011'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '934'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '935'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '942'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '943'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '947'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120331' where code = '952'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1054'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '991'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '992'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '993'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120430' where code = '1139'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120430' where code = '1140'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1083'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1084'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1085'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1086'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '1087'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120430' where code = '1141'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110102' where code = '967_smol'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '288'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '313'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '334'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '335'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '482'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '419'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '420'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '421'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '422'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '423'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '424'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '425'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '552'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '483'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '486'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '556'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '557'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '558'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '559'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '470'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '560'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '489'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '491'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '562'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '563'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '492'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '493'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '494'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '495'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '496'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100401' where code = '497'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '498'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100401' where code = '499'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100330' where code = '500'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '566'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '292'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '299'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '304'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '315'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '319'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '343'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091230' where code = '344'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100331' where code = '347'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '401'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '416'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '488'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '501'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '502'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '503'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '504'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '505'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '506'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '507'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '508'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '581'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '510'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '511'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '512'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '513'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '514'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '515'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '516'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '517'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '582'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100430' where code = '534'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101031' where code = '538'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '539'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '540'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '542'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '545'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '336'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '403'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '565'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '456'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '485'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '569'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '572'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '573'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '216m'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20081231' where code = '216s'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '522'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '524'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '527'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '528'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '529'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '531'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101130' where code = '547'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101130' where code = '548'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101130' where code = '549'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '321'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '446'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '448'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '449'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '553'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '554'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '555'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '543'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '574'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '532'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '533'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '546'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101130' where code = '583'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '584'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '585'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '586'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '587'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '429'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '460'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '476'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '477'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '481'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110101' where code = '523'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '590'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '591'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100930' where code = '593'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101031' where code = '594'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '596'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '601'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100101' where code = '597'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '599'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '603'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '604'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '605'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '606'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '609'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '610'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '454'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '464'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '479'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '564'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '579'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '592'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101031' where code = '595'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '598'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '611'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '613'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '614'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '612'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '615'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '626'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '633'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '634'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '635'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '636'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '637'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '638'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '625'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '639'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101031' where code = '640'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101031' where code = '641'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '645'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '646'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '651'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '652'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '490'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '561'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '541'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '570'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '571'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '653'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '654'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '655'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '656'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '657'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '658'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '670'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '660'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '661'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '662'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '663'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '666'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '667'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '669'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '686'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '689'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '690'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '691'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '535'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100430' where code = '536'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100430' where code = '537'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '758'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '682'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '683'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '684'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '685'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '692'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '699'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '700'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '704'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '707'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '708'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '709'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '710'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '518'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '519'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '520'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '575'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '576'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '577'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '771'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '521'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '580'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '525'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '530'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '899'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '642'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '643'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '679'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '680'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '681'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '705'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '725'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '726'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '727'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '728'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '729'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '676'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '745'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '627'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '628'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '677'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '678'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '629'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '777'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '778'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '693'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '694'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '730'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '731'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '732'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '733'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '734'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '735'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '736'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '737'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '738'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '739'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '740'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '742'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '743'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '747'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '748'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '749'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '750'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '751'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '752'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100101' where code = '754'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '755'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '756'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '757'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '630'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '631'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '461'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '763'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '764'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '765'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '766'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '767'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '768'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '695'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100101' where code = '696'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '697'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '698'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '769'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '770'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '578'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '712'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '713'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '714'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '717'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '719'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '720'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '721'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '772'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '774'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '430'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '431'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '442'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '457'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20091231' where code = '487'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '607'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '616'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20100101' where code = '617'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '618'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '619'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '620'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '621'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '622'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '759'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '760'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '761'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '762'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '632'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '644'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '673'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '675'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120331' where code = '773'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '783'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '798'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '804'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110101' where code = '839'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '850'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '855'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '775'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110430' where code = '807'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '808'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110430' where code = '809'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '810'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111031' where code = '869'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111031' where code = '870'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '780'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '788'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '882'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '912'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '914'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '926'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '928'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '785'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '786'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '811'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '813'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111231' where code = '922'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '923'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '929'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101230' where code = '958'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '948'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '949'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120331' where code = '953'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120331' where code = '955'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '956'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20101231' where code = '805'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '951'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20120331' where code = '954'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20110430' where code = '803'
update  dbo.[REPORT_GROUP_KS] set dt_end = '20111230' where code = '930'
GO

GO
--- Добавление в навигатор 'Страны мира (ОКСМ)' ---
IF NOT EXISTS (SELECT * FROM dbo.S_NAVIGATOR WHERE CODE = 'DICTIONARY_COUNTRY')
	INSERT INTO dbo.S_NAVIGATOR (CODE, NAME, ORDERS, SYS, LINK_SELF, OBJECT, LINK_VAR, IMAGE_KEY, USERS, VISIBLE)
	SELECT 'DICTIONARY_COUNTRY', 'Страны мира (ОКСМ)', 18, 1, (SELECT LINK FROM dbo.S_NAVIGATOR WHERE CODE = 'BUDJ_CLASS'), (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_COUNTRY'), NULL, 'DICTIONARY', NULL, 3
GO



GO
-- Настройки документа: Корректировочный счет-фактура (полученный) (DOCUMENTS_INVOICE_COR_IN) --
DECLARE @intOBJ	INT
SELECT @intOBJ = LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_COR_IN'
-- 1. Добавление настроек в таблицу DOC_NASTR --
IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR WHERE LINK = @intOBJ)
	INSERT INTO dbo.DOC_NASTR (LINK, PRINT_SGU, PRINT_KBK, AN_PERIOD, AN_ORG, AN_BEGIN, AN_SHABLON)
	SELECT @intOBJ, 1, 1, 0, 0, 1, '%9'
ELSE
	UPDATE dbo.DOC_NASTR 
	SET	PRINT_SGU = 1,
		PRINT_KBK = 1,
		AN_PERIOD = 0,
		AN_ORG = 0,
		AN_BEGIN = 1,
		AN_SHABLON = '%9'
	WHERE LINK = @intOBJ

-- 3. Добавление настроек в таблицу DOC_NASTR_T3 (Документы основания) --
--- DOCUMENTS_INVOICE_RECEIVED ---
IF NOT EXISTS (SELECT 1 FROM dbo.OSNOV_VID WHERE OBJECT = 'DOCUMENTS_INVOICE_RECEIVED')
	INSERT INTO dbo.OSNOV_VID ([NAME], TYPE, OBJECT, [SYSTEM])
	SELECT 'Счет-фактура (полученный)', 1, 'DOCUMENTS_INVOICE_RECEIVED', 1

IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR_T3 T3, dbo.OSNOV_VID OV WHERE T3.LINK_UP = @intOBJ AND T3.LINK_OTHER = OV.LINK AND OV.OBJECT = 'DOCUMENTS_INVOICE_RECEIVED')
	INSERT INTO dbo.DOC_NASTR_T3 (LINK_UP, LINK_OTHER, FMETHOD)
	SELECT @intOBJ, (SELECT TOP 1 LINK FROM dbo.OSNOV_VID WHERE OBJECT = 'DOCUMENTS_INVOICE_RECEIVED'), ''
GO


GO
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 
-- Настройки документа: Корректировочный счет-фактура (выданный) (DOCUMENTS_INVOICE_COR_OUT) --
DECLARE @intOBJ	INT
SELECT @intOBJ = LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_COR_OUT'
-- 1. Добавление настроек в таблицу DOC_NASTR --
IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR WHERE LINK = @intOBJ)
	INSERT INTO dbo.DOC_NASTR (LINK, PRINT_SGU, PRINT_KBK, AN_PERIOD, AN_ORG, AN_BEGIN, AN_SHABLON)
	SELECT @intOBJ, 1, 1, 0, 0, 1, '%9'
ELSE
	UPDATE dbo.DOC_NASTR 
	SET	PRINT_SGU = 1,
		PRINT_KBK = 1,
		AN_PERIOD = 0,
		AN_ORG = 0,
		AN_BEGIN = 1,
		AN_SHABLON = '%9'
	WHERE LINK = @intOBJ

-- 3. Добавление настроек в таблицу DOC_NASTR_T3 (Документы основания) --
--- DOCUMENTS_INVOICE_ISSUED ---
IF NOT EXISTS (SELECT 1 FROM dbo.OSNOV_VID WHERE OBJECT = 'DOCUMENTS_INVOICE_ISSUED')
	INSERT INTO dbo.OSNOV_VID ([NAME], TYPE, OBJECT, [SYSTEM])
	SELECT 'Счет-фактура (выданный)', 1, 'DOCUMENTS_INVOICE_ISSUED', 1

IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR_T3 T3, dbo.OSNOV_VID OV WHERE T3.LINK_UP = @intOBJ AND T3.LINK_OTHER = OV.LINK AND OV.OBJECT = 'DOCUMENTS_INVOICE_ISSUED')
	INSERT INTO dbo.DOC_NASTR_T3 (LINK_UP, LINK_OTHER, FMETHOD)
	SELECT @intOBJ, (SELECT TOP 1 LINK FROM dbo.OSNOV_VID WHERE OBJECT = 'DOCUMENTS_INVOICE_ISSUED'), ''
GO


GO
-- Настройки документа: Счет на оплату (DOCUMENTS_INVOICE_PAY) --
DECLARE @intOBJ	INT
SELECT @intOBJ = LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_INVOICE_PAY'
-- 1. Добавление настроек в таблицу DOC_NASTR --
IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR WHERE LINK = @intOBJ)
	INSERT INTO dbo.DOC_NASTR (LINK, PRINT_SGU, PRINT_KBK, AN_PERIOD, AN_ORG, AN_BEGIN, AN_SHABLON)
	SELECT @intOBJ, 0, 0, 1, 0, 0, '%9'
ELSE
	UPDATE dbo.DOC_NASTR 
	SET	PRINT_SGU = 0,
		PRINT_KBK = 0,
		AN_PERIOD = 1,
		AN_ORG = 0,
		AN_BEGIN = 0,
		AN_SHABLON = '%9'
	WHERE LINK = @intOBJ

-- 3. Добавление настроек в таблицу DOC_NASTR_T3 (Документы основания) --
--- FINANS_CONTRACT ---
IF NOT EXISTS (SELECT 1 FROM dbo.OSNOV_VID WHERE OBJECT = 'FINANS_CONTRACT')
	INSERT INTO dbo.OSNOV_VID ([NAME], TYPE, OBJECT, [SYSTEM])
	SELECT 'Договор', 1, 'FINANS_CONTRACT', 1

IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR_T3 T3, dbo.OSNOV_VID OV WHERE T3.LINK_UP = @intOBJ AND T3.LINK_OTHER = OV.LINK AND OV.OBJECT = 'FINANS_CONTRACT')
	INSERT INTO dbo.DOC_NASTR_T3 (LINK_UP, LINK_OTHER, FMETHOD)
	SELECT @intOBJ, (SELECT TOP 1 LINK FROM dbo.OSNOV_VID WHERE OBJECT = 'FINANS_CONTRACT'), ''
--- FINANS_CONTRACT_CHANGE ---
IF NOT EXISTS (SELECT 1 FROM dbo.OSNOV_VID WHERE OBJECT = 'FINANS_CONTRACT_CHANGE')
	INSERT INTO dbo.OSNOV_VID ([NAME], TYPE, OBJECT, [SYSTEM])
	SELECT 'Изменение к договору', 1, 'FINANS_CONTRACT_CHANGE', 1

IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR_T3 T3, dbo.OSNOV_VID OV WHERE T3.LINK_UP = @intOBJ AND T3.LINK_OTHER = OV.LINK AND OV.OBJECT = 'FINANS_CONTRACT_CHANGE')
	INSERT INTO dbo.DOC_NASTR_T3 (LINK_UP, LINK_OTHER, FMETHOD)
	SELECT @intOBJ, (SELECT TOP 1 LINK FROM dbo.OSNOV_VID WHERE OBJECT = 'FINANS_CONTRACT_CHANGE'), ''
--- BD_OSNOV_OTHER ---
IF NOT EXISTS (SELECT 1 FROM dbo.OSNOV_VID WHERE OBJECT = 'BD_OSNOV_OTHER')
	INSERT INTO dbo.OSNOV_VID ([NAME], TYPE, OBJECT, [SYSTEM])
	SELECT 'Прочие документы-основания', 3, 'BD_OSNOV_OTHER', 1

IF NOT EXISTS (SELECT 1 FROM dbo.DOC_NASTR_T3 T3, dbo.OSNOV_VID OV WHERE T3.LINK_UP = @intOBJ AND T3.LINK_OTHER = OV.LINK AND OV.OBJECT = 'BD_OSNOV_OTHER')
	INSERT INTO dbo.DOC_NASTR_T3 (LINK_UP, LINK_OTHER, FMETHOD)
	SELECT @intOBJ, (SELECT TOP 1 LINK FROM dbo.OSNOV_VID WHERE OBJECT = 'BD_OSNOV_OTHER'), ''
GO


GO
EXEC DBO.W_SPERM_WRITE 'QUERY_CLASS', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'QUERY_CLASS', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'QUERY_CLASS', 'Свод-КС', 63,0
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_SAVE_REPORT_KBK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RN_SAVE_REPORT_KBK]
GO

/*
c Кейсистемс (Keysystems), 2006
*/
--сохранение REPORT_KBK
CREATE        PROCEDURE dbo.RN_SAVE_REPORT_KBK
  @iLINK     int  OUTPUT,
  @cCode         varchar (200)='', --код кбк
  @iLink_self   int = NULL,
  @cName         varchar(250)='', --наименование
  @cCode_Form    varchar(250)='',
  @iChildrens  bit=0,
  @cCode_str  varchar(50)='', --код строки
  @property  int =0, --свойства строки
  @add_info varchar(4000)='',  -- Доп информация
  @long_name varchar(4000)='',  -- длинное наименование
	@dBegin_date datetime = NULL,
	@dEnd_date	datetime = NULL,
   @bCheck     BIT = 0,       -- проверка для новых кодов, на то что уже есть в спраовчнике или в федеральном спрвочнике	
   @bSysJurnal BIT = 0        -- записывать в системный журнал    
AS

IF @bCheck = 1 
BEGIN
   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = @cCode_Form AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1100 
   END    

   IF EXISTS(SELECT * FROM dbo.report_kbk WHERE [Code_Form] = REPLACE(@cCode_Form, '_USER', '') AND [Code] = @cCode AND LINK <> ISNULL(@iLINK, 0) AND ISNULL(begin_date, '19000101') <= ISNULL(@dEnd_date, '30000101')  AND ISNULL(end_date, '30000101') >= ISNULL(@dBegin_date, '19000101'))
   BEGIN
      RETURN 1101 
   END    
END    

DECLARE @Date DATETIME , @dOldBeginDate DATETIME , @dOldEndDate DATETIME , @vcOldName VARCHAR(254), @vcOldLongName VARCHAR(8000), @bJastWas bit
-- очищение кэша проверки внутридокументных КС
delete report_control_protokol

set @cCode=RTRIM(@cCode)
set @iLink_self=isnull(@iLink_self,0) 

SET NOCOUNT ON
SET IMPLICIT_TRANSACTIONS OFF  -- Режим явного определения транзакций.
SET LOCK_TIMEOUT -1 -- Время ожидания разблокировки ресурсов 3 сек.

BEGIN TRANSACTION -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.
  -- Чтобы не было двойных кодов
 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') AND isnull(end_date, '30000101') >= ISNULL(@dend_date,'20990101')
   END

 IF (SELECT COUNT(*) 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form ) = 1 and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form
   END

 IF EXISTS(SELECT * 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101')) and ISNULL(@iLink,0)=0 AND @cCODE_FORM not IN ('SEND', 'MDKS_125')
   BEGIN
--    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
--      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
--    RETURN 4 -- Возврат кода ошибки.
        SELECT @iLINK=link 
          FROM  dbo.[REPORT_KBK]
          WHERE [CODE] = @cCODE AND [CODE_FORM]=@cCode_Form AND isnull(begin_date, '19000101') = ISNULL(@dBegin_date,'19000101') 
   END

SET @bJastWas = 0
   
IF isnull(@iLink, 0) <> 0
BEGIN
   SELECT @dOldBeginDate = begin_date, @dOldEndDate = end_date, @vcOldName = NAME, @vcOldLongName = Long_Name
   FROM dbo.report_kbk
   WHERE link = @iLink 
   
   set @bJastWas = 1

   IF (SELECT NAME FROM dbo.report_kbk WHERE link = @iLink) <> @cName OR  (SELECT LONG_NAME FROM dbo.report_kbk WHERE link = @iLink) <> @long_name
   BEGIN
      SET @Date = CONVERT(DATETIME,CONVERT(VARCHAR(10), GETDATE(), 112), 112)
      IF NOT EXISTS(SELECT * FROM dbo.[REPORT_KBK_HIST] WHERE [LINK_UP] = @iLink)
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         SELECT @iLink, '20000101', NAME, rk.[Long_name]
         FROM  dbo.[REPORT_KBK] rk
         WHERE link = @iLink
      END
      UPDATE dbo.[REPORT_KBK_HIST]
      SET NAME = @cName, [LONG_NAME] = @long_name
      WHERE LINK_UP =  @iLink AND [DATE] = @Date 
      IF @@ROWCOUNT = 0
      BEGIN
         INSERT dbo.[REPORT_KBK_HIST] ([LINK_UP], [DATE], [NAME], [LONG_NAME])
         VALUES( @iLink, @Date, @cName, @long_name)
      END 
   END
END    
   

   -- Обновление записи (если она существует).
  UPDATE [REPORT_KBK]
  SET   [CODE] =    @cCODE,
        [NAME] =    @cNAME,
        [CODE_FORM]=@cCODE_FORM,
        [CHILDRENS]=@iChildrens,
        [LINK_SELF]=@iLink_Self,
        [CODE_STR]=@cCode_str,
        [property]=@property,
        [add_info]=@add_info,
        [LONG_NAME] =    @LONG_NAME,
		[BEGIN_DATE] = @dBegin_date,
		[END_DATE] = @dEnd_date
  WHERE [LINK] = @iLINK

DECLARE @liRowCount   INT, -- Число обработанных строк.
        @liError      INT  -- Код ошибки.
   -- Сохранение количества обработанных строк и кода ошибки. 
   SELECT @liRowCount = @@ROWCOUNT, 
          @liError    = @@ERROR

   -- Восстановление точки сохранения при ошибке.
  IF @liError <> 0 BEGIN
    ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
      COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
    RETURN 7 -- Возврат кода ошибки.
  END
 
  IF @liRowCount = 0  
   BEGIN
    INSERT 
      INTO dbo.[REPORT_KBK] ([CODE],[NAME],[LINK_SELF],[CHILDRENS],[CODE_FORM],[CODE_STR],[property],[add_info],long_name, begin_date, end_date)
    VALUES (@cCODE, @cNAME,@iLink_Self,@iChildrens,@cCode_Form,@cCode_Str,@property,@add_info,@long_name, @dBegin_date, @dEnd_date)

      -- Сохранение первичного ключа и кода ошибки. 
    SELECT @iLINK   = @@IDENTITY 
    SELECT @liError = @@ERROR
      -- Восстановление точки сохранения при ошибке.
    IF @liError <> 0
    BEGIN
      ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
         COMMIT TRANSACTION -- Фиксация транзакции, которая ничего не изменила.
      RETURN 7 -- Возврат кода ошибки.
    END
  END

IF @cCode_Form='HEADER'
begin  
  UPDATE REPORT_KBK 
  SET childrens=case when exists(select * from REPORT_KBK A where A.link_self=REPORT_KBK.link) then 0 else 1 end
  WHERE link=@iLink OR link=@iLink_self
  update report_kbk 
  set imageindex=4  
  where code_form='header'
end

EXEC dbo.[RO_KBK_CASHE_UPDATE] @iLINK

DECLARE @LF INT, @LSF INT 

EXEC dbo.DropTempTable '#t_CodeRow' 
CREATE TABLE #t_CodeRow (Code VARCHAR(50))

if @bJastWas = 1 AND ((isnull(@dBegin_date, '19000101') <> isnull(@dOldBeginDate, '19000101')
    OR ISNULL(case when @dEnd_date > '20200101' THEN '30000101'  ELSE @dEnd_date END , '30000101') <> ISNULL(case when @dOldEnddate > '20200101' THEN '30000101'  ELSE @dOldEnddate END, '30000101')
      OR @vcOldName <> @cName OR @vcOldLongName <> @long_name)
   AND (@cCode_Form LIKE '%_2011_USER%' OR (RTRIM(@cCode_Form) LIKE '%_2011' AND NOT EXISTS(SELECT * FROM dbo.report_kbk WHERE code_form = RTRIM(@cCode_Form) + '_USER' AND @cCode = Code))))
BEGIN
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503117M','0503117G','0503127G','0503127M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_117_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   SET @LSF = NULL
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503114M','0503114G','0503137G','0503137M') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      TRUNCATE TABLE #t_CodeRow
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 12,3) = @cCode
      END
      IF @cCode_Form LIKE '%ЦСР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 5,7) = @cCode
      END
      IF @cCode_Form LIKE '%РЗПР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_114_2011')
               and SUBSTRING(CODE, 1,4) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   SET @LSF = NULL
   SELECT top 1 @LSF = RSF.link_saved_form, @LF = rf.Link_Form
   FROM dbo.report_saved_forms rsf
      JOIN dbo.report_forms rf ON rf.[Link_Form] = rsf.[Link_Form]
   WHERE rf.[Code] IN ( '0503317M_ФК','0503317G_ФК') AND YEAR(rf.[Start_Date]) >= 2011 AND rf.[End_Date] IS NULL  
   
   IF @LSF IS NOT NULL 
   BEGIN 
      TRUNCATE TABLE #t_CodeRow
      IF @cCode_Form LIKE '%ЭКР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               AND RIGHT(RTRIM(Code), 3) = @cCode
      END 
      IF @cCode_Form LIKE '%ВР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 15,3) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 15,3) = @cCode
      END
      IF @cCode_Form LIKE '%ЦСР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 8,7) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 8,7) = @cCode
      END
      IF @cCode_Form LIKE '%РЗПР%'
      BEGIN
          INSERT #t_CodeRow
          SELECT Code
          FROM  dbo.report_kbk 
          WHERE code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 4,4) = @cCode
               
         DELETE dbo.report_kbk WHERE  code_form IN ('R_SPR_RASH_317FK_2011')
               and SUBSTRING(CODE, 4,4) = @cCode
      END
      EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, 2
   END  
   
END     

COMMIT TRANSACTION -- Фиксация транзакции.
DECLARE @link_task INT, @vcText VARCHAR(250)

IF @bSysJurnal = 1
BEGIN 
   SELECT @link_task = ui.[LINK_TASK] 
   FROM dbo.[USER_INFO] ui

   SET @vcText = RTRIM(@cCode_Form) + ' редактирование строки ' + @cCode

   EXEC [dbo].[WF_GENERATEEVENT]
      @varKSevent = 'Универсальный справочник',
      @varKSText = @vcText,
      @varKSObject = @link_task,
      @varKSDB_Object = 'report_kbk',
      @varKSLinkObj = @iLINK
END       

RETURN 0 -- Ошибок нет.




GO
GRANT ALL ON dbo.[RN_SAVE_REPORT_KBK] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
EXEC dbo.W_SPERM_WRITE 'DICTIONARY_COUNTRY', 'Смета-КС', 63, 0
GO


GO
EXECUTE dbo.X_UPDATE_DELETE_TRIGGERS
GO


GO


UPDATE dbo.report_kbk
SET end_date = NULL
WHERE code_form LIKE '%2011_USER%' and end_date = '19000101'

DELETE dbo.report_kbk
WHERE code_form IN 
(SELECT S.code
FROM dbo.report_spr S
   JOIN dbo.report_coloumns rc ON S.code = rc.[Dictionary]
   JOIN dbo.report_tables rt ON rt.[Link_Table] = rc.[Link_Table]
   JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
   LEFT JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
WHERE S.NAME LIKE '%автозаполн%' AND S.code LIKE '%2011%'  AND charindex('AUTO_SPR_PARENT',rt.script_str)>0  
   AND S.Code = 'R_SPR_RASH_117_2011'
GROUP BY S.code)


DELETE dbo.report_kbk_cashe
 
INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
SELECT K.[LINK], 
      [begin_date] = isnull((case when isnull(K.[begin_date],'19000101') > isnull(KH.date_begin,'19000101') then K.[begin_date] ELSE KH.date_begin END), '19000101'),
      [end_date] = ISNULL((case when isnull(K.[end_date],'30000101') > isnull(KH.date_end,'30000101') then KH.[date_end] ELSE K.end_date END),'30000101'),
      isnull(KH.[NAME], K.Name),
      isnull(KH.[LONG_NAME], K.[LONG_NAME])
FROM dbo.report_kbk K
   LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   
INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
SELECT K.[LINK], 
      isnull(K.[begin_date], '19000101'),
      KH.[date_begin]-1,
      K.[NAME],
      K.[LONG_NAME]
FROM dbo.report_kbk K
       LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
WHERE isnull(K.begin_date, '19000101') < KH.date_begin
      AND KH.date_begin = (SELECT MIN(KH1.DATE)
                           FROM dbo.[REPORT_KBK_HIST] KH1
                           WHERE KH1.[LINK_UP] = K.[link])




exec dbo.droptemptable  '#t_CodeRow'
CREATE TABLE #t_CodeRow (Code VARCHAR(50)) 
exec dbo.droptemptable  '#LSF'
CREATE TABLE #LSF (lsf int) 


DECLARE @code VARCHAR(100), @LSF INT, @OT TINYINT, @LF INT, @LT int 

DECLARE cur CURSOR LOCAL STATIC FOR 
SELECT S.code, rt.orders,MAX(rsf.link_saved_form) link_saved_form FROM dbo.report_spr S
   JOIN dbo.report_coloumns rc ON S.code = rc.[Dictionary]
   JOIN dbo.report_tables rt ON rt.[Link_Table] = rc.[Link_Table]
   JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
   LEFT JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
WHERE S.NAME LIKE '%автозаполн%' AND S.code LIKE '%2011%'  AND charindex('AUTO_SPR_PARENT',rt.script_str)>0  
   AND S.Code = 'R_SPR_RASH_117_2011'
GROUP BY S.code, rt.orders

OPEN cur

 FETCH NEXT FROM cur INTO @code, @OT, @LSF

WHILE @@FETCH_STATUS = 0
BEGIN
   INSERT #LSF (lsf)
   SELECT rsf.link_saved_form
   FROM dbo.report_spr S
      JOIN dbo.report_coloumns rc ON S.code = rc.[Dictionary]
      JOIN dbo.report_tables rt ON rt.[Link_Table] = rc.[Link_Table]
      JOIN dbo.[REPORT_FORMS] rf ON rf.[Link_Form] = rt.[Link_Form]
      JOIN dbo.[REPORT_SAVED_FORMS] rsf ON rsf.[Link_Form] = rf.[Link_Form]
   WHERE rt.orders = @OT AND S.code = @code AND charindex('AUTO_SPR_PARENT',rt.script_str)>0  

   
   SELECT @LF = link_form FROM dbo.report_saved_forms rsf JOIN #lsf ON lsf = rsf.[Link_Saved_Form]

  
   INSERT #t_CodeRow
   SELECT DISTINCT rd.Code_row
   FROM dbo.report_dinamics rd
      JOIN #lsf ON lsf = rd.link_sf
      JOIN dbo.report_coloumns rc ON rc.[Link_Col] = rd.[Link_Col]
      JOIN dbo.[REPORT_TABLES] rt ON rt.[Link_Table] = rc.[Link_Table]
   WHERE RT.[orders] = @OT
   
   EXEC dbo.[RN_FILL_WITH_CODEROW] @LSF, @LF, @OT
   
   
   TRUNCATE TABLE #t_CodeRow
   TRUNCATE TABLE #LSF  
   
   FETCH NEXT FROM cur INTO @code, @OT, @LSF
END



GO
UPDATE STATISTICS report_kbk
GO


GO
DELETE dbo.report_kbk_cashe
 
INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
SELECT K.[LINK], 
      [begin_date] = isnull((case when isnull(K.[begin_date],'19000101') > isnull(KH.date_begin,'19000101') then K.[begin_date] ELSE KH.date_begin END), '19000101'),
      [end_date] = ISNULL((case when isnull(K.[end_date],'30000101') > isnull(KH.date_end,'30000101') then KH.[date_end] ELSE K.end_date END),'30000101'),
      isnull(KH.[NAME], K.Name),
      isnull(KH.[LONG_NAME], K.[LONG_NAME])
FROM dbo.report_kbk K
   LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
   
INSERT dbo.report_kbk_cashe(LINK_UP, BEGIN_DATE, END_DATE, NAME, LONG_NAME)
SELECT K.[LINK], 
      isnull(K.[begin_date], '19000101'),
      KH.[date_begin]-1,
      K.[NAME],
      K.[LONG_NAME]
FROM dbo.report_kbk K
       LEFT JOIN dbo.RO_KBK_HIST KH ON K.[link] = KH.[LINK_UP]
WHERE isnull(K.begin_date, '19000101') < KH.date_begin
      AND KH.date_begin = (SELECT MIN(KH1.DATE)
                           FROM dbo.[REPORT_KBK_HIST] KH1
                           WHERE KH1.[LINK_UP] = K.[link])


GO

GO
update statistics report_kbk
GO

GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Расходы (КОСГУ) С КОДОМ R_SPR_154_RASH------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
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, '''200''+Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 4, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_STR', 2, '', 'Код строки', '''200''', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('ST', 3, 'CODE', 'КОСГУ', '', 0,0)

insert #Data_tmp (Table_From, Filter)
values ('R_SPR_ST_2011', '')

declare @link int
select @link = link from report_spr where code = 'R_SPR_154_RASH'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_154_RASH', 'Расходы (КОСГУ)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_154_RASH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_154_RASH]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Расходы (КОСГУ) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_154_RASH]

AS

SELECT max(LINK) as Link, max(Link_Self) as Link_Self,'200'+Code as [CODE],'200' as [CODE_STR],CODE as [ST],max(Name) as [NAME],begin_date,end_date FROM R_SPR_ST_2011 GROUP BY '200'+Code,CODE,begin_date,end_date

	UNION

	select -1 as Link, 0 as Link_Self,'200000' as CODE,'200' as CODE_STR,'000' as ST,'Результат кассового обслуживания (дефицит/профицит)

' as NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

	UNION

	select -2 as Link, 0 as Link_Self,'450000' as CODE,'450' as CODE_STR,'000' as ST,'Результат кассового обслуживания (дефицит/профицит)' as NAME,convert(datetime, '19000101', 112) as begin_date,convert(datetime, '30000101', 112) as end_date

GO


GRANT SELECT ON dbo.[R_SPR_154_RASH] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_154_RASH')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_154_RASH'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH', 'Расходы (КОСГУ)', 211, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH', NAME = 'Расходы (КОСГУ)', ORDERS = '211', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH_CODE_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH_CODE_STR', 'Код строки', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH_CODE_STR', NAME = 'Код строки', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH_CODE_STR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH_ST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH_ST', 'КОСГУ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH_ST', NAME = 'КОСГУ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH_ST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_154_RASH_Name', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_154_RASH_Name', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_154_RASH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_154_RASH_Name'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH', 'SERVER_TABLE_NAME', 'R_SPR_154_RASH'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_154_RASH'''
GO
EXEC X_SET_PROP 'R_SPR_154_RASH', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_154_RASH'')'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_154_RASH'')'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH', 'TITLE', 'Расходы (КОСГУ)'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE_STR', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE_STR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE_STR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_STR"'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_CODE_STR', 'FIELD_DATA', 'CODE_STR'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_ST', 'TITLE', 'КОСГУ'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_ST', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_ST', 'CONTROLSOURCE', 'm.cAlias + ".ST"'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_ST', 'FIELD_DATA', 'ST'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_154_RASH_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_154_RASH', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_154_RASH', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_154_RASH', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Доходы (КОСГУ) С КОДОМ R_SPR_155_DOH------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE_STR', 3, 'Code_Str', 'Код строки', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_155_DOH'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_155_DOH', 'Доходы (КОСГУ)', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[R_SPR_155_DOH]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[R_SPR_155_DOH]


GO

/*******************************************************************************

	© Кейсистемс (Keysystems), 25.01.2012

	справочник Доходы (КОСГУ) (сгенерировано Редактором справочников)

*******************************************************************************/

CREATE     VIEW dbo.[R_SPR_155_DOH]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],Code_Str as [CODE_STR],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_155_DOH' GROUP BY Code,Code_Str, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_155_DOH] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_155_DOH')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_155_DOH'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_DOH', 'Доходы (КОСГУ)', 208, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_DOH', NAME = 'Доходы (КОСГУ)', ORDERS = '208', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_DOH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_DOH_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_DOH_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_DOH_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_DOH_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_DOH_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_DOH_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_DOH_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_DOH_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_DOH_Name'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH_CODE_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_155_DOH_CODE_STR', 'Код строки', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_155_DOH_CODE_STR', NAME = 'Код строки', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_155_DOH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_155_DOH_CODE_STR'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH', 'TITLE', 'Доходы (КОСГУ)'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_155_DOH'')'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_155_DOH'')'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH', 'SERVER_TABLE_NAME', 'R_SPR_155_DOH'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_155_DOH'''
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_Name', 'FIELD_DATA', 'Name'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE_STR', 'TITLE', 'Код строки'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE_STR', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE_STR', 'CONTROLSOURCE', 'm.cAlias + ".CODE_STR"'
GO
EXEC X_SET_PROP 'R_SPR_155_DOH_CODE_STR', 'FIELD_DATA', 'CODE_STR'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_155_DOH', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_155_DOH', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_155_DOH', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_155_DOH',0,'Доходы (КОСГУ)','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_155_DOH',@link_self,'Доходы (КОСГУ)','HEADER'
GO
declare @link_self int, @link int 
set @link_self=0
exec RN_SAVE_REPORT_KBK @link output,'110',@link_self,'Налоговые доходы','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'120',@link_self,'Доходы от собственности','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'130',@link_self,'Доходы от оказания платных услуг','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'140',@link_self,'Cуммы принудительного изъятия','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'150',@link_self,'Безвозмездные поступления от бюджетов','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'151',@link_self,'Поступления от других бюджетов бюджетной системы Российской Федерации','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'152',@link_self,'Поступления от наднациональных организаций и правительств иностранных государств','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'153',@link_self,'Поступления от международных финансовых организаций','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'160',@link_self,'Cтраховые взносы на обязательное социальное страхование','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'170',@link_self,'Доходы от операций с активами','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'180',@link_self,'Прочие доходы','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'410',@link_self,'Уменьшение стоимости основных средств','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'420',@link_self,'Уменьшение стоимости нематериальных активов','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'430',@link_self,'Уменьшение стоимости непроизведенных активов','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'440',@link_self,'Уменьшение стоимости материальных запасов.','R_SPR_155_DOH',0,'010',0,'','','19000101',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,'000',@link_self,'Всего','R_SPR_155_DOH',0,'010',0,'','',NULL,NULL
delete dbo.report_kbk_hist where link_up = @link


GO

GO

